text:
//  ---------------------------------------------------------------------------
//
//  @file       TwDirect3D10.cpp
//  @author     Philippe Decaudin - http://www.antisphere.com
//  @license    This file is part of the AntTweakBar library.
//              For conditions of distribution and use, see License.txt
//
//  ---------------------------------------------------------------------------

#include "TwPrecomp.h"
#include "TwDirect3D10.h"
#include "TwMgr.h"
#include "TwColors.h"

#include "d3d10vs2003.h" // Workaround to include D3D10.h with VS2003
#define D3D10_IGNORE_SDK_LAYERS // d3d10sdklayers.h may not exist
#include <d3d10.h>

using namespace std;

const char *g_ErrCantLoadD3D10   = "Cannot load Direct3D10 library dynamically";
const char *g_ErrCompileFX10     = "Direct3D10 effect compilation failed";
const char *g_ErrCreateFX10      = "Direct3D10 effect creation failed";
const char *g_ErrTechNotFound10  = "Cannot find Direct3D10 technique effect";
const char *g_ErrCreateLayout10  = "Direct3D10 vertex layout creation failed";
const char *g_ErrCreateBuffer10  = "Direct3D10 vertex buffer creation failed";

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

// Dynamically loaded D3D10 functions (to avoid static linkage with d3d10.lib)
HMODULE g_D3D10Module = NULL;
typedef HRESULT (WINAPI *D3D10CompileEffectFromMemoryProc)(void *pData, SIZE_T DataLength, LPCSTR pSrcFileName, CONST D3D10_SHADER_MACRO *pDefines, ID3D10Include *pInclude, UINT HLSLFlags, UINT FXFlags, ID3D10Blob **ppCompiledEffect, ID3D10Blob **ppErrors);
typedef HRESULT (WINAPI *D3D10CreateEffectFromMemoryProc)(void *pData, SIZE_T DataLength, UINT FXFlags, ID3D10Device *pDevice, ID3D10EffectPool *pEffectPool, ID3D10Effect **ppEffect);
typedef HRESULT (WINAPI *D3D10StateBlockMaskEnableAllProc)(D3D10_STATE_BLOCK_MASK *pMask);
typedef HRESULT (WINAPI *D3D10CreateStateBlockProc)(ID3D10Device *pDevice, D3D10_STATE_BLOCK_MASK *pStateBlockMask, ID3D10StateBlock **ppStateBlock);
D3D10CompileEffectFromMemoryProc _D3D10CompileEffectFromMemory = NULL;
D3D10CreateEffectFromMemoryProc _D3D10CreateEffectFromMemory = NULL;
D3D10StateBlockMaskEnableAllProc _D3D10StateBlockMaskEnableAll = NULL;
D3D10CreateStateBlockProc _D3D10CreateStateBlock = NULL;

const RECT FullRect = {0, 0, 16000, 16000};
static bool RectIsFull(const RECT& r) { return r.left==FullRect.left && r.right==FullRect.right && r.top==FullRect.top && r.bottom==FullRect.bottom; }

static int LoadDirect3D10()
{
    if( g_D3D10Module!=NULL )
        return 1; // Direct3D10 library already loaded

    g_D3D10Module = LoadLibrary("D3D10.DLL");
    if( g_D3D10Module )
    {
        int res = 1;
        _D3D10CompileEffectFromMemory = reinterpret_cast<D3D10CompileEffectFromMemoryProc>(GetProcAddress(g_D3D10Module, "D3D10CompileEffectFromMemory"));
        if( _D3D10CompileEffectFromMemory==NULL )
            res = 0;
        _D3D10CreateEffectFromMemory = reinterpret_cast<D3D10CreateEffectFromMemoryProc>(GetProcAddress(g_D3D10Module, "D3D10CreateEffectFromMemory"));
        if( _D3D10CreateEffectFromMemory==NULL )
            res = 0;
        _D3D10StateBlockMaskEnableAll = reinterpret_cast<D3D10StateBlockMaskEnableAllProc>(GetProcAddress(g_D3D10Module, "D3D10StateBlockMaskEnableAll"));
        if( _D3D10StateBlockMaskEnableAll==NULL )
            res = 0;
        _D3D10CreateStateBlock = reinterpret_cast<D3D10CreateStateBlockProc>(GetProcAddress(g_D3D10Module, "D3D10CreateStateBlock"));
        if( _D3D10CreateStateBlock==NULL )
            res = 0;
        return res;
    }
    else
        return 0;   // cannot load DLL
}

static int UnloadDirect3D10()
{
    _D3D10CompileEffectFromMemory = NULL;
    _D3D10CreateEffectFromMemory =  NULL;
    _D3D10StateBlockMaskEnableAll = NULL;
    _D3D10CreateStateBlock = NULL;

    if( g_D3D10Module==NULL )
        return 1; // Direct3D10 library not loaded

    if( FreeLibrary(g_D3D10Module) )
    {
        g_D3D10Module = NULL;
        return 1;
    }
    else
        return 0; // cannot unload d3d10.dll
}

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

static ID3D10ShaderResourceView *BindFont(ID3D10Device *_Dev, ID3D10EffectShaderResourceVariable *_ResVar, const CTexFont *_Font)
{
    assert(_Font!=NULL);
    assert(_ResVar!=NULL);

    int w = _Font->m_TexWidth;
    int h = _Font->m_TexHeight;
    color32 *font32 = new color32[w*h];
    color32 *p = font32;
    for( int i=0; i<w*h; ++i, ++p )
        *p = 0x00ffffff | (((color32)(_Font->m_TexBytes[i]))<<24);

    D3D10_TEXTURE2D_DESC desc;
    desc.Width = w;
    desc.Height = h;
    desc.MipLevels = 1;
    desc.ArraySize = 1;
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.Usage = D3D10_USAGE_IMMUTABLE;
    desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
    desc.CPUAccessFlags = 0;
    desc.MiscFlags = 0;
    D3D10_SUBRESOURCE_DATA data;
    data.pSysMem = font32;
    data.SysMemPitch = w*sizeof(color32);
    data.SysMemSlicePitch = 0;
    ID3D10Texture2D *tex = NULL;
    ID3D10ShaderResourceView *texRV = NULL;
    if( SUCCEEDED(_Dev->CreateTexture2D(&desc, &data, &tex)) )
    {
        if( SUCCEEDED(_Dev->CreateShaderResourceView(tex, NULL, &texRV)) )
            if( _ResVar )
                _ResVar->SetResource(texRV);
        tex->Release();
        tex = NULL;
    }

    delete[] font32;
    return texRV;
}

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

static void UnbindFont(ID3D10Device *_Dev, ID3D10EffectShaderResourceVariable *_ResVar, ID3D10ShaderResourceView *_TexRV)
{
    (void)_Dev;

    if( _ResVar )
        _ResVar->SetResource(NULL);

    if( _TexRV )
    {
        ULONG rc = _TexRV->Release();
        assert( rc==0 ); (void)rc;
    }
}

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

struct CState10
{
    ID3D10StateBlock *  m_StateBlock;

    void            Save();
    void            Restore();
                    CState10(ID3D10Device *_Dev);
                    ~CState10();
private:
    ID3D10Device *  m_D3DDev;
};

CState10::CState10(ID3D10Device *_Dev)
{
    ZeroMemory(this, sizeof(CState10));
    m_D3DDev = _Dev;
}

CState10::~CState10()
{
    if( m_StateBlock )
    {
        UINT rc = m_StateBlock->Release();
        assert( rc==0 ); (void)rc;
        m_StateBlock = NULL;
    }
}

void CState10::Save()
{
    if( !m_StateBlock )
    {
        D3D10_STATE_BLOCK_MASK stateMask;
        _D3D10StateBlockMaskEnableAll(&stateMask);
        _D3D10CreateStateBlock(m_D3DDev, &stateMask, &m_StateBlock);
    }

    if( m_StateBlock )
        m_StateBlock->Capture();
}

void CState10::Restore()
{
    if( m_StateBlock )
        m_StateBlock->Apply();
}

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

char g_ShaderFX[] = "// AntTweakBar shaders and techniques \n"
    " float4 g_Offset = 0; float4 g_CstColor = 1; \n"
    " struct LineRectPSInput { float4 Pos : SV_POSITION; float4 Color : COLOR0; }; \n"
    " LineRectPSInput LineRectVS(float4 pos : POSITION, float4 color : COLOR, uniform bool useCstColor) { \n"
    "   LineRectPSInput ps; ps.Pos = pos + g_Offset; \n"
    "   ps.Color = useCstColor ? g_CstColor : color; return ps; } \n"
    " float4 LineRectPS(LineRectPSInput input) : SV_Target { return input.Color; } \n"
    " technique10 LineRect { pass P0 { \n"
    "   SetVertexShader( CompileShader( vs_4_0, LineRectVS(false) ) ); \n"
    "   SetGeometryShader( NULL ); \n"
    "   SetPixelShader( CompileShader( ps_4_0, LineRectPS() ) ); \n"
    " } }\n"
    " technique10 LineRectCstColor { pass P0 { \n"
    "   SetVertexShader( CompileShader( vs_4_0, LineRectVS(true) ) ); \n"
    "   SetGeometryShader( NULL ); \n"
    "   SetPixelShader( CompileShader( ps_4_0, LineRectPS() ) ); \n"
    " } }\n"
    " Texture2D Font; \n"
    " SamplerState FontSampler { Filter = MIN_MAG_MIP_POINT; AddressU = BORDER; AddressV = BORDER; BorderColor=float4(0, 0, 0, 0); }; \n"
    " struct TextPSInput { float4 Pos : SV_POSITION; float4 Color : COLOR0; float2 Tex : TEXCOORD0; }; \n"
    " TextPSInput TextVS(float4 pos : POSITION, float4 color : COLOR, float2 tex : TEXCOORD0, uniform bool useCstColor) { \n"
    "   TextPSInput ps; ps.Pos = pos + g_Offset; \n"
    "   ps.Color = useCstColor ? g_CstColor : color; ps.Tex = tex; return ps; } \n"
    " float4 TextPS(TextPSInput input) : SV_Target { return Font.Sample(FontSampler, input.Tex)*input.Color; } \n"
    " technique10 Text { pass P0 { \n"
    "   SetVertexShader( CompileShader( vs_4_0, TextVS(false) ) ); \n"
    "   SetGeometryShader( NULL ); \n"
    "   SetPixelShader( CompileShader( ps_4_0, TextPS() ) ); \n"
    " } }\n"
    " technique10 TextCstColor { pass P0 { \n"
    "   SetVertexShader( CompileShader( vs_4_0, TextVS(true) ) ); \n"
    "   SetGeometryShader( NULL ); \n"
    "   SetPixelShader( CompileShader( ps_4_0, TextPS() ) ); \n"
    " } }\n"
    " // End of AntTweakBar shaders and techniques \n";

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

int CTwGraphDirect3D10::Init()
{
    assert(g_TwMgr!=NULL);
    assert(g_TwMgr->m_Device!=NULL);

    m_D3DDev = static_cast<ID3D10Device *>(g_TwMgr->m_Device);
    m_D3DDevInitialRefCount = m_D3DDev->AddRef() - 1;

    m_Drawing = false;
    m_OffsetX = m_OffsetY = 0;
    m_ViewportInit = new D3D10_VIEWPORT;
    m_FontTex = NULL;
    m_FontD3DTexRV = NULL;
    m_WndWidth = 0;
    m_WndHeight = 0;
    m_State = NULL;
    m_DepthStencilState = NULL;
    m_BlendState = NULL;
    m_RasterState = NULL;
    m_RasterStateAntialiased = NULL;
    m_RasterStateCullCW = NULL;
    m_RasterStateCullCCW = NULL;
    m_Effect = NULL;
    m_LineRectTech = NULL;
    m_LineRectCstColorTech = NULL;
    m_LineRectVertexLayout = NULL;
    m_LineVertexBuffer = NULL;
    m_RectVertexBuffer = NULL;
    m_TrianglesVertexBuffer = NULL;
    m_TrianglesVertexBufferCount = 0;
    m_TextTech = NULL;
    m_TextCstColorTech = NULL;
    m_TextVertexLayout = NULL;
    m_FontD3DResVar = NULL;
    m_OffsetVar = NULL;
    m_CstColorVar = NULL;

    // Load some D3D10 functions
    if( !LoadDirect3D10() )
    {
        g_TwMgr->SetLastError(g_ErrCantLoadD3D10);
        Shut();
        return 0;
    }

    // Allocate state object
    m_State = new CState10(m_D3DDev);

    // Compile shaders
    DWORD shaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
    #if defined( DEBUG ) || defined( _DEBUG )
        // shaderFlags |= D3D10_SHADER_DEBUG; // no more supported
    #endif
    ID3D10Blob *compiledFX = NULL;
    ID3D10Blob *errors = NULL;
    HRESULT hr = _D3D10CompileEffectFromMemory(g_ShaderFX, strlen(g_ShaderFX), "AntTweakBarFX", NULL, NULL, shaderFlags, 0, &compiledFX, &errors);
    if( FAILED(hr) )
    {
        const size_t ERR_MSG_MAX_LEN = 4096;
        static char s_ErrorMsg[ERR_MSG_MAX_LEN]; // must be static to be sent to SetLastError
        strncpy(s_ErrorMsg, g_ErrCompileFX10, ERR_MSG_MAX_LEN-1);
        size_t errOffset = strlen(s_ErrorMsg);
        size_t errLen = 0;
        if( errors!=NULL )
        {
            s_ErrorMsg[errOffset++] = ':';
            s_ErrorMsg[errOffset++] = '\n';
            errLen = min(errors->GetBufferSize(), ERR_MSG_MAX_LEN-errOffset-2);
            strncpy(s_ErrorMsg+errOffset, static_cast<char *>(errors->GetBufferPointer()), errLen);
            errors->Release();
            errors = NULL;
        }
        s_ErrorMsg[errOffset+errLen] = '\0';
        g_TwMgr->SetLastError(s_ErrorMsg);
        Shut();
        return 0;
    }
    hr = _D3D10CreateEffectFromMemory(compiledFX->GetBufferPointer(), compiledFX->GetBufferSize(), 0, m_D3DDev, NULL, &m_Effect);
    compiledFX->Release();
    if( FAILED(hr) )
    {
        g_TwMgr->SetLastError(g_ErrCreateFX10);
        Shut();
        return 0;
    }

    // Obtain the techniques
    m_LineRectTech = m_Effect->GetTechniqueByName("LineRect");
    m_LineRectCstColorTech = m_Effect->GetTechniqueByName("LineRectCstColor");
    m_TextTech = m_Effect->GetTechniqueByName("Text");
    m_TextCstColorTech = m_Effect->GetTechniqueByName("TextCstColor");
    if( m_LineRectTech==NULL || m_TextTech==NULL || m_LineRectCstColorTech==NULL || m_TextCstColorTech==NULL )
    {
        g_TwMgr->SetLastError(g_ErrTechNotFound10);
        Shut();
        return 0;
    }

    // Create input layout for lines & rect
    D3D10_INPUT_ELEMENT_DESC lineRectLayout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, offsetof(CLineRectVtx, m_Color), D3D10_INPUT_PER_VERTEX_DATA, 0 }
    };
    D3D10_PASS_DESC passDesc;
    hr = m_LineRectTech->GetPassByIndex(0)->GetDesc(&passDesc);
    if( SUCCEEDED(hr) )
        hr = m_D3DDev->CreateInputLayout(lineRectLayout, sizeof(lineRectLayout)/sizeof(lineRectLayout[0]), passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_LineRectVertexLayout);
    if( FAILED(hr) )
    {
        g_TwMgr->SetLastError(g_ErrCreateLayout10);
        Shut();
        return 0;
    }

    // Create line vertex buffer
    D3D10_BUFFER_DESC bd;
    bd.Usage = D3D10_USAGE_DYNAMIC;
    bd.ByteWidth = 2 * sizeof(CLineRectVtx);
    bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
    bd.MiscFlags = 0;
    hr = m_D3DDev->CreateBuffer(&bd, NULL, &m_LineVertexBuffer);
    if( FAILED(hr) )
    {
        g_TwMgr->SetLastError(g_ErrCreateBuffer10);
        Shut();
        return 0;
    }

    // Create rect vertex buffer
    bd.ByteWidth = 4 * sizeof(CLineRectVtx);
    hr = m_D3DDev->CreateBuffer(&bd, NULL, &m_RectVertexBuffer);
    if( FAILED(hr) )
    {
        g_TwMgr->SetLastError(g_ErrCreateBuffer10);
        Shut();
        return 0;
    }

    // Create input layout for text
    D3D10_INPUT_ELEMENT_DESC textLayout[] =
    {
        { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, offsetof(CTextVtx, m_Color), D3D10_INPUT_PER_VERTEX_DATA, 0 },
        { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(CTextVtx, m_UV), D3D10_INPUT_PER_VERTEX_DATA, 0 }
    };
    hr = m_TextTech->GetPassByIndex(0)->GetDesc(&passDesc);
    if( SUCCEEDED(hr) )
        hr = m_D3DDev->CreateInputLayout(textLayout, sizeof(textLayout)/sizeof(textLayout[0]), passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_TextVertexLayout);
    if( FAILED(hr) )
    {
        g_TwMgr->SetLastError(g_ErrCreateLayout10);
        Shut();
        return 0;
    }

    // Create depth stencil state object
    D3D10_DEPTH_STENCILOP_DESC od;
    od.StencilFunc = D3D10_COMPARISON_ALWAYS;
    od.StencilFailOp = D3D10_STENCIL_OP_KEEP;
    od.StencilPassOp = D3D10_STENCIL_OP_KEEP;
    od.StencilDepthFailOp = D3D10_STENCIL_OP_KEEP;
    D3D10_DEPTH_STENCIL_DESC dsd;
    dsd.DepthEnable = FALSE;
    dsd.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ZERO;
    dsd.DepthFunc = D3D10_COMPARISON_ALWAYS;
    dsd.StencilEnable = FALSE;
    dsd.StencilReadMask = D3D10_DEFAULT_STENCIL_READ_MASK;
    dsd.StencilWriteMask = D3D10_DEFAULT_STENCIL_WRITE_MASK;
    dsd.FrontFace = od;
    dsd.BackFace = od;
    m_D3DDev->CreateDepthStencilState(&dsd, &m_DepthStencilState);

    // Create blend state object
    D3D10_BLEND_DESC bsd;
    bsd.AlphaToCoverageEnable = FALSE;
    for(int i=0; i<8; ++i)
    {
        bsd.BlendEnable[i] = TRUE;
        bsd.RenderTargetWriteMask[i] = D3D10_COLOR_WRITE_ENABLE_ALL;
    }
    bsd.SrcBlend = D3D10_BLEND_SRC_ALPHA;
    bsd.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
    bsd.BlendOp =  D3D10_BLEND_OP_ADD;
    bsd.SrcBlendAlpha = D3D10_BLEND_SRC_ALPHA;
    bsd.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
    bsd.BlendOpAlpha = D3D10_BLEND_OP_ADD;
    m_D3DDev->CreateBlendState(&bsd, &m_BlendState);

    // Create rasterizer state object
    D3D10_RASTERIZER_DESC rd;
    rd.FillMode = D3D10_FILL_SOLID;
    rd.CullMode = D3D10_CULL_NONE;
    rd.FrontCounterClockwise = true;
    rd.DepthBias = false;
    rd.DepthBiasClamp = 0;
    rd.SlopeScaledDepthBias = 0;
    rd.DepthClipEnable = false;
    rd.ScissorEnable = true;
    rd.MultisampleEnable = false;
    rd.AntialiasedLineEnable = false;
    m_D3DDev->CreateRasterizerState(&rd, &m_RasterState);

    rd.AntialiasedLineEnable = true;
    m_D3DDev->CreateRasterizerState(&rd, &m_RasterStateAntialiased);
    rd.AntialiasedLineEnable = false;

    rd.CullMode = D3D10_CULL_BACK;
    m_D3DDev->CreateRasterizerState(&rd, &m_RasterStateCullCW);

    rd.CullMode = D3D10_CULL_FRONT;
    m_D3DDev->CreateRasterizerState(&rd, &m_RasterStateCullCCW);

    m_ViewportAndScissorRects[0] = FullRect;
    m_ViewportAndScissorRects[1] = FullRect;
    m_D3DDev->RSSetScissorRects(1, m_ViewportAndScissorRects);

    // Get effect globals
    if( m_Effect->GetVariableByName("Font") )
        m_FontD3DResVar = m_Effect->GetVariableByName("Font")->AsShaderResource();
    assert( m_FontD3DResVar!=NULL );
    if( m_Effect->GetVariableByName("g_Offset") )
        m_OffsetVar = m_Effect->GetVariableByName("g_Offset")->AsVector();
    assert( m_OffsetVar!=NULL );
    if( m_Effect->GetVariableByName("g_CstColor") )
        m_CstColorVar = m_Effect->GetVariableByName("g_CstColor")->AsVector();
    assert( m_CstColorVar!=NULL );

    return 1;
}

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

int CTwGraphDirect3D10::Shut()
{
    assert(m_Drawing==false);

    UnbindFont(m_D3DDev, m_FontD3DResVar, m_FontD3DTexRV);
    m_FontD3DTexRV = NULL;
    if( m_State )
    {
        delete m_State;
        m_State = NULL;
    }
    if( m_ViewportInit )
    {
        delete m_ViewportInit;
        m_ViewportInit = NULL;
    }

    if( m_DepthStencilState )
    {
        ULONG rc = m_DepthStencilState->Release();
        //assert( rc==0 ); // no assert: the client can use a similar (then shared) state
        (void)rc;
        m_DepthStencilState = NULL;
    }
    if( m_BlendState )
    {
        ULONG rc = m_BlendState->Release();
        //assert( rc==0 ); // no assert: the client can use a similar (then shared) state
        (void)rc;
        m_BlendState = NULL;
    }
    if( m_RasterState )
    {
        ULONG rc = m_RasterState->Release();
        //assert( rc==0 ); // no assert: the client can use a similar (then shared) state
        (void)rc;
        m_RasterState = NULL;
    }
    if( m_RasterStateAntialiased )
    {
        ULONG rc = m_RasterStateAntialiased->Release();
        //assert( rc==0 ); // no assert: the client can use a similar (then shared) state
        (void)rc;
        m_RasterStateAntialiased = NULL;
    }
    if( m_RasterStateCullCW )
    {
        ULONG rc = m_RasterStateCullCW->Release();
        //assert( rc==0 ); // no assert: the client can use a similar (then shared) state
        (void)rc;
        m_RasterStateCullCW = NULL;
    }
    if( m_RasterStateCullCCW )
    {
        ULONG rc = m_RasterStateCullCCW->Release();
        //assert( rc==0 ); // no assert: the client can use a similar (then shared) state
        (void)rc;
        m_RasterStateCullCCW = NULL;
    }

    m_FontD3DResVar = NULL;
    m_OffsetVar = NULL;
    m_CstColorVar = NULL;

    if( m_LineVertexBuffer )
    {
        ULONG rc = m_LineVertexBuffer->Release();
        assert( rc==0 ); (void)rc;
        m_LineVertexBuffer = NULL;
    }
    if( m_RectVertexBuffer )
    {
        ULONG rc = m_RectVertexBuffer->Release();
        assert( rc==0 ); (void)rc;
        m_RectVertexBuffer = NULL;
    }
    if( m_TrianglesVertexBuffer )
    {
        ULONG rc = m_TrianglesVertexBuffer->Release();
        assert( rc==0 ); (void)rc;
        m_TrianglesVertexBuffer = NULL;
        m_TrianglesVertexBufferCount = 0;
    }
    if( m_LineRectVertexLayout )
    {
        ULONG rc = m_LineRectVertexLayout->Release();
        assert( rc==0 ); (void)rc;
        m_LineRectVertexLayout = NULL;
    }
    if( m_TextVertexLayout )
    {
        ULONG rc = m_TextVertexLayout->Release();
        assert( rc==0 ); (void)rc;
        m_TextVertexLayout = NULL;
    }
    if( m_Effect )
    {
        ULONG rc = m_Effect->Release();
        assert( rc==0 ); (void)rc;
        m_Effect = NULL;
    }

    if( m_D3DDev )
    {
        //unsigned int rc = m_D3DDev->Release();
        //assert( m_D3DDevInitialRefCount==rc ); (void)rc;
        m_D3DDev->Release();
        m_D3DDev = NULL;
    }

    // Unload D3D10
    UnloadDirect3D10(); // this is not a problem if it cannot be unloaded

    return 1;
}

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

void CTwGraphDirect3D10::BeginDraw(int _WndWidth, int _WndHeight)
{
    assert(m_Drawing==false && _WndWidth>0 && _WndHeight>0);
    m_Drawing = true;

    m_WndWidth  = _WndWidth;
    m_WndHeight = _WndHeight;
    m_OffsetX = m_OffsetY = 0;

    // save context
    m_State->Save();

    // Setup the viewport
    D3D10_VIEWPORT vp;
    vp.Width = _WndWidth;
    vp.Height = _WndHeight;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
    m_D3DDev->RSSetViewports(1, &vp);
    *static_cast<D3D10_VIEWPORT *>(m_ViewportInit) = vp;

    m_D3DDev->RSSetState(m_RasterState);

    m_D3DDev->OMSetDepthStencilState(m_DepthStencilState, 0);
    float blendFactors[4] = { 1, 1, 1, 1 };
    m_D3DDev->OMSetBlendState(m_BlendState, blendFactors, 0xffffffff);
}

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

void CTwGraphDirect3D10::EndDraw()
{
    m_D3DDev->RSSetState(NULL);
    m_D3DDev->OMSetDepthStencilState(NULL, 0);
    m_D3DDev->OMSetBlendState(NULL, NULL, 0xffffffff);

    assert(m_Drawing==true);
    m_Drawing = false;

    // restore context
    m_State->Restore();
}

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

bool CTwGraphDirect3D10::IsDrawing()
{
    return m_Drawing;
}

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

void CTwGraphDirect3D10::Restore()
{
    if( m_State )
    {
        if( m_State->m_StateBlock )
        {
            UINT rc = m_State->m_StateBlock->Release();
            assert( rc==0 ); (void)rc;
            m_State->m_StateBlock = NULL;
        }
    }

    UnbindFont(m_D3DDev, m_FontD3DResVar, m_FontD3DTexRV);
    m_FontD3DTexRV = NULL;

    m_FontTex = NULL;
}

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

static inline float ToNormScreenX(int x, int wndWidth)
{
    return 2.0f*((float)x-0.5f)/wndWidth - 1.0f;
}

static inline float ToNormScreenY(int y, int wndHeight)
{
    return 1.0f - 2.0f*((float)y-0.5f)/wndHeight;
}

static inline color32 ToR8G8B8A8(color32 col)
{
    return (col & 0xff00ff00) | ((col>>16) & 0xff) | ((col<<16) & 0xff0000);
}

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

void CTwGraphDirect3D10::DrawLine(int _X0, int _Y0, int _X1, int _Y1, color32 _Color0, color32 _Color1, bool _AntiAliased)
{
    assert(m_Drawing==true);

    float x0 = ToNormScreenX(_X0 + m_OffsetX, m_WndWidth);
    float y0 = ToNormScreenY(_Y0 + m_OffsetY, m_WndHeight);
    float x1 = ToNormScreenX(_X1 + m_OffsetX, m_WndWidth);
    float y1 = ToNormScreenY(_Y1 + m_OffsetY, m_WndHeight);

    CLineRectVtx *vertices = NULL;
    HRESULT hr = m_LineVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, (void **)&vertices);
    if( SUCCEEDED(hr) )
    {
        // Fill vertex buffer
        vertices[0].m_Pos[0] = x0;
        vertices[0].m_Pos[1] = y0;
        vertices[0].m_Pos[2] = 0;
        vertices[0].m_Color = ToR8G8B8A8(_Color0);
        vertices[1].m_Pos[0] = x1;
        vertices[1].m_Pos[1] = y1;
        vertices[1].m_Pos[2] = 0;
        vertices[1].m_Color = ToR8G8B8A8(_Color1);

        m_LineVertexBuffer->Unmap();

        if( _AntiAliased )
            m_D3DDev->RSSetState(m_RasterStateAntialiased);

        // Reset shader globals
        float offsetVec[4] = { 0, 0, 0, 0 };
        if( m_OffsetVar )
            m_OffsetVar->SetFloatVector(offsetVec);
        float colorVec[4] = { 1, 1, 1, 1 };
        if( m_CstColorVar )
            m_CstColorVar->SetFloatVector(colorVec);

        // Set the input layout
        m_D3DDev->IASetInputLayout(m_LineRectVertexLayout);

        // Set vertex buffer
        UINT stride = sizeof(CLineRectVtx);
        UINT offset = 0;
        m_D3DDev->IASetVertexBuffers(0, 1, &m_LineVertexBuffer, &stride, &offset);

        // Set primitive topology
        m_D3DDev->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINELIST);

        // Render the line
        D3D10_TECHNIQUE_DESC techDesc;
        m_LineRectTech->GetDesc(&techDesc);
        for(UINT p=0; p<techDesc.Passes; ++p)
        {
            m_LineRectTech->GetPassByIndex(p)->Apply(0);
            m_D3DDev->Draw(2, 0);
        }

        if( _AntiAliased )
            m_D3DDev->RSSetState(m_RasterState); // restore default raster state
    }
}

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

void CTwGraphDirect3D10::DrawRect(int _X0, int _Y0, int _X1, int _Y1, color32 _Color00, color32 _Color10, color32 _Color01, color32 _Color11)
{
    assert(m_Drawing==true);

    // border adjustment
    if(_X0<_X1)
        ++_X1;
    else if(_X0>_X1)
        ++_X0;
    if(_Y0<_Y1)
        ++_Y1;
    else if(_Y0>_Y1)
        ++_Y0;

    float x0 = ToNormScreenX(_X0 + m_OffsetX, m_WndWidth);
    float y0 = ToNormScreenY(_Y0 + m_OffsetY, m_WndHeight);
    float x1 = ToNormScreenX(_X1 + m_OffsetX, m_WndWidth);
    float y1 = ToNormScreenY(_Y1 + m_OffsetY, m_WndHeight);

    CLineRectVtx *vertices = NULL;
    HRESULT hr = m_RectVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, (void **)&vertices);
    if( SUCCEEDED(hr) )
    {
        // Fill vertex buffer
        vertices[0].m_Pos[0] = x0;
        vertices[0].m_Pos[1] = y0;
        vertices[0].m_Pos[2] = 0;
        vertices[0].m_Color = ToR8G8B8A8(_Color00);
        vertices[1].m_Pos[0] = x1;
        vertices[1].m_Pos[1] = y0;
        vertices[1].m_Pos[2] = 0;
        vertices[1].m_Color = ToR8G8B8A8(_Color10);
        vertices[2].m_Pos[0] = x0;
        vertices[2].m_Pos[1] = y1;
        vertices[2].m_Pos[2] = 0;
        vertices[2].m_Color = ToR8G8B8A8(_Color01);
        vertices[3].m_Pos[0] = x1;
        vertices[3].m_Pos[1] = y1;
        vertices[3].m_Pos[2] = 0;
        vertices[3].m_Color = ToR8G8B8A8(_Color11);

        m_RectVertexBuffer->Unmap();

        // Reset shader globals
        float offsetVec[4] = { 0, 0, 0, 0 };
        if( m_OffsetVar )
            m_OffsetVar->SetFloatVector(offsetVec);
        float colorVec[4] = { 1, 1, 1, 1 };
        if( m_CstColorVar )
            m_CstColorVar->SetFloatVector(colorVec);

        // Set the input layout
        m_D3DDev->IASetInputLayout(m_LineRectVertexLayout);

        // Set vertex buffer
        UINT stride = sizeof(CLineRectVtx);
        UINT offset = 0;
        m_D3DDev->IASetVertexBuffers(0, 1, &m_RectVertexBuffer, &stride, &offset);

        // Set primitive topology
        m_D3DDev->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);

        // Render the rect
        D3D10_TECHNIQUE_DESC techDesc;
        m_LineRectTech->GetDesc(&techDesc);
        for(UINT p=0; p<techDesc.Passes; ++p)
        {
            m_LineRectTech->GetPassByIndex(p)->Apply(0);
            m_D3DDev->Draw(4, 0);
        }
    }
}

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

void *CTwGraphDirect3D10::NewTextObj()
{
    CTextObj *textObj = new CTextObj;
    memset(textObj, 0, sizeof(CTextObj));
    return textObj;
}

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

void CTwGraphDirect3D10::DeleteTextObj(void *_TextObj)
{
    assert(_TextObj!=NULL);
    CTextObj *textObj = static_cast<CTextObj *>(_TextObj);
    if( textObj->m_TextVertexBuffer )
        textObj->m_TextVertexBuffer->Release();
    if( textObj->m_BgVertexBuffer )
        textObj->m_BgVertexBuffer->Release();
    memset(textObj, 0, sizeof(CTextObj));
    delete textObj;
}

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

void CTwGraphDirect3D10::BuildText(void *_TextObj, const std::string *_TextLines, color32 *_LineColors, color32 *_LineBgColors, int _NbLines, const CTexFont *_Font, int _Sep, int _BgWidth)
{
    assert(m_Drawing==true);
    assert(_TextObj!=NULL);
    assert(_Font!=NULL);

    if( _Font != m_FontTex )
    {
        UnbindFont(m_D3DDev, m_FontD3DResVar, m_FontD3DTexRV);
        m_FontD3DTexRV = BindFont(m_D3DDev, m_FontD3DResVar, _Font);
        m_FontTex = _Font;
    }

    int nbTextVerts = 0;
    int line;
    for( line=0; line<_NbLines; ++line )
        nbTextVerts += 6 * (int)_TextLines[line].length();
    int nbBgVerts = 0;
    if( _BgWidth>0 )
        nbBgVerts = _NbLines*6;

    CTextObj *textObj = static_cast<CTextObj *>(_TextObj);
    textObj->m_LineColors = (_LineColors!=NULL);
    textObj->m_LineBgColors = (_LineBgColors!=NULL);

    // (re)create text vertex buffer if needed, and map it
    CTextVtx *textVerts = NULL;
    if( nbTextVerts>0 )
    {
        if( textObj->m_TextVertexBuffer==NULL || textObj->m_TextVertexBufferSize<nbTextVerts )
        {
            if( textObj->m_TextVertexBuffer!=NULL )
            {
                ULONG rc = textObj->m_TextVertexBuffer->Release();
                assert( rc==0 ); (void)rc;
                textObj->m_TextVertexBuffer = NULL;
            }
            textObj->m_TextVertexBufferSize = nbTextVerts + 6*256; // add a reserve of 256 characters
            D3D10_BUFFER_DESC bd;
            bd.Usage = D3D10_USAGE_DYNAMIC;
            bd.ByteWidth = textObj->m_TextVertexBufferSize * sizeof(CTextVtx);
            bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
            bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
            bd.MiscFlags = 0;
            m_D3DDev->CreateBuffer(&bd, NULL, &textObj->m_TextVertexBuffer);
        }

        if( textObj->m_TextVertexBuffer!=NULL )
            textObj->m_TextVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, (void **)&textVerts);
    }

    // (re)create bg vertex buffer if needed, and map it
    CLineRectVtx *bgVerts = NULL;
    if( nbBgVerts>0 )
    {
        if( textObj->m_BgVertexBuffer==NULL || textObj->m_BgVertexBufferSize<nbBgVerts )
        {
            if( textObj->m_BgVertexBuffer!=NULL )
            {
                ULONG rc = textObj->m_BgVertexBuffer->Release();
                assert( rc==0 ); (void)rc;
                textObj->m_BgVertexBuffer = NULL;
            }
            textObj->m_BgVertexBufferSize = nbBgVerts + 6*32; // add a reserve of 32 rects
            D3D10_BUFFER_DESC bd;
            bd.Usage = D3D10_USAGE_DYNAMIC;
            bd.ByteWidth = textObj->m_BgVertexBufferSize * sizeof(CLineRectVtx);
            bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
            bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
            bd.MiscFlags = 0;
            m_D3DDev->CreateBuffer(&bd, NULL, &textObj->m_BgVertexBuffer);
        }

        if( textObj->m_BgVertexBuffer!=NULL )
            textObj->m_BgVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, (void **)&bgVerts);
    }

    int x, x1, y, y1, i, len;
    float px, px1, py, py1;
    unsigned char ch;
    const unsigned char *text;
    color32 lineColor = COLOR32_RED;
    CTextVtx vtx;
    vtx.m_Pos[2] = 0;
    CLineRectVtx bgVtx;
    bgVtx.m_Pos[2] = 0;
    int textVtxIndex = 0;
    int bgVtxIndex = 0;
    for( line=0; line<_NbLines; ++line )
    {
        x = 0;
        y = line * (_Font->m_CharHeight+_Sep);
        y1 = y+_Font->m_CharHeight;
        len = (int)_TextLines[line].length();
        text = (const unsigned char *)(_TextLines[line].c_str());
        if( _LineColors!=NULL )
            lineColor = ToR8G8B8A8(_LineColors[line]);

        if( textVerts!=NULL )
            for( i=0; i<len; ++i )
            {
                ch = text[i];
                x1 = x + _Font->m_CharWidth[ch];

                px  = ToNormScreenX(x,  m_WndWidth);
                py  = ToNormScreenY(y,  m_WndHeight);
                px1 = ToNormScreenX(x1, m_WndWidth);
                py1 = ToNormScreenY(y1, m_WndHeight);

                vtx.m_Color  = lineColor;

                vtx.m_Pos[0] = px;
                vtx.m_Pos[1] = py;
                vtx.m_UV [0] = _Font->m_CharU0[ch];
                vtx.m_UV [1] = _Font->m_CharV0[ch];
                textVerts[textVtxIndex++] = vtx;

                vtx.m_Pos[0] = px1;
                vtx.m_Pos[1] = py;
                vtx.m_UV [0] = _Font->m_CharU1[ch];
                vtx.m_UV [1] = _Font->m_CharV0[ch];
                textVerts[textVtxIndex++] = vtx;

                vtx.m_Pos[0] = px;
                vtx.m_Pos[1] = py1;
                vtx.m_UV [0] = _Font->m_CharU0[ch];
                vtx.m_UV [1] = _Font->m_CharV1[ch];
                textVerts[textVtxIndex++] = vtx;

                vtx.m_Pos[0] = px1;
                vtx.m_Pos[1] = py;
                vtx.m_UV [0] = _Font->m_CharU1[ch];
                vtx.m_UV [1] = _Font->m_CharV0[ch];
                textVerts[textVtxIndex++] = vtx;

                vtx.m_Pos[0] = px1;
                vtx.m_Pos[1] = py1;
                vtx.m_UV [0] = _Font->m_CharU1[ch];
                vtx.m_UV [1] = _Font->m_CharV1[ch];
                textVerts[textVtxIndex++] = vtx;

                vtx.m_Pos[0] = px;
                vtx.m_Pos[1] = py1;
                vtx.m_UV [0] = _Font->m_CharU0[ch];
                vtx.m_UV [1] = _Font->m_CharV1[ch];
                textVerts[textVtxIndex++] = vtx;

                x = x1;
            }

        if( _BgWidth>0 && bgVerts!=NULL )
        {
            if( _LineBgColors!=NULL )
                bgVtx.m_Color = ToR8G8B8A8(_LineBgColors[line]);
            else
                bgVtx.m_Color = ToR8G8B8A8(COLOR32_BLACK);

            px  = ToNormScreenX(-1, m_WndWidth);
            py  = ToNormScreenY(y,  m_WndHeight);
            px1 = ToNormScreenX(_BgWidth+1, m_WndWidth);
            py1 = ToNormScreenY(y1, m_WndHeight);

            bgVtx.m_Pos[0] = px;
            bgVtx.m_Pos[1] = py;
            bgVerts[bgVtxIndex++] = bgVtx;

            bgVtx.m_Pos[0] = px1;
            bgVtx.m_Pos[1] = py;
            bgVerts[bgVtxIndex++] = bgVtx;

            bgVtx.m_Pos[0] = px;
            bgVtx.m_Pos[1] = py1;
            bgVerts[bgVtxIndex++] = bgVtx;

            bgVtx.m_Pos[0] = px1;
            bgVtx.m_Pos[1] = py;
            bgVerts[bgVtxIndex++] = bgVtx;

            bgVtx.m_Pos[0] = px1;
            bgVtx.m_Pos[1] = py1;
            bgVerts[bgVtxIndex++] = bgVtx;

            bgVtx.m_Pos[0] = px;
            bgVtx.m_Pos[1] = py1;
            bgVerts[bgVtxIndex++] = bgVtx;
        }
    }
    assert( textVtxIndex==nbTextVerts );
    assert( bgVtxIndex==nbBgVerts );
    textObj->m_NbTextVerts = nbTextVerts;
    textObj->m_NbBgVerts = nbBgVerts;

    if( textVerts!=NULL )
        textObj->m_TextVertexBuffer->Unmap();
    if( bgVerts!=NULL )
        textObj->m_BgVertexBuffer->Unmap();
}

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

void CTwGraphDirect3D10::DrawText(void *_TextObj, int _X, int _Y, color32 _Color, color32 _BgColor)
{
    assert(m_Drawing==true);
    assert(_TextObj!=NULL);
    CTextObj *textObj = static_cast<CTextObj *>(_TextObj);
    float dx = 2.0f*(float)(_X + m_OffsetX)/m_WndWidth;
    float dy = -2.0f*(float)(_Y + m_OffsetY)/m_WndHeight;

    float offsetVec[4] = { 0, 0, 0, 0 };
    offsetVec[0] = dx;
    offsetVec[1] = dy;
    if( m_OffsetVar )
        m_OffsetVar->SetFloatVector(offsetVec);

    // Draw background
    if( textObj->m_NbBgVerts>=4 && textObj->m_BgVertexBuffer!=NULL )
    {
        float color[4];
        Color32ToARGBf(_BgColor, color+3, color+0, color+1, color+2);
        if( m_CstColorVar )
            m_CstColorVar->SetFloatVector(color);

        // Set the input layout
        m_D3DDev->IASetInputLayout(m_LineRectVertexLayout);

        // Set vertex buffer
        UINT stride = sizeof(CLineRectVtx);
        UINT offset = 0;
        m_D3DDev->IASetVertexBuffers(0, 1, &textObj->m_BgVertexBuffer, &stride, &offset);

        // Set primitive topology
        m_D3DDev->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        // Render the bg rectangles
        ID3D10EffectTechnique *tech;
        if( _BgColor!=0 || !textObj->m_LineBgColors ) // use a constant bg color
            tech = m_LineRectCstColorTech;
        else // use vertex buffer colors
            tech = m_LineRectTech;
        D3D10_TECHNIQUE_DESC techDesc;
        tech->GetDesc(&techDesc);
        for( UINT p=0; p<techDesc.Passes; ++p )
        {
            tech->GetPassByIndex(p)->Apply(0);
            m_D3DDev->Draw(textObj->m_NbBgVerts, 0);
        }
    }

    // Draw text
    if( textObj->m_NbTextVerts>=4 && textObj->m_TextVertexBuffer!=NULL )
    {
        float color[4];
        Color32ToARGBf(_Color, color+3, color+0, color+1, color+2);
        if( m_CstColorVar )
            m_CstColorVar->SetFloatVector(color);

        // Set the input layout
        m_D3DDev->IASetInputLayout(m_TextVertexLayout);

        // Set vertex buffer
        UINT stride = sizeof(CTextVtx);
        UINT offset = 0;
        m_D3DDev->IASetVertexBuffers(0, 1, &textObj->m_TextVertexBuffer, &stride, &offset);

        // Set primitive topology
        m_D3DDev->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        // Render text
        ID3D10EffectTechnique *tech;
        if( _Color!=0 || !textObj->m_LineColors ) // use a constant color
            tech = m_TextCstColorTech;
        else // use vertex buffer colors
            tech = m_TextTech;
        D3D10_TECHNIQUE_DESC techDesc;
        tech->GetDesc(&techDesc);
        for( UINT p=0; p<techDesc.Passes; ++p )
        {
            tech->GetPassByIndex(p)->Apply(0);
            m_D3DDev->Draw(textObj->m_NbTextVerts, 0);
        }
    }
}

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

void CTwGraphDirect3D10::ChangeViewport(int _X0, int _Y0, int _Width, int _Height, int _OffsetX, int _OffsetY)
{
    if( _Width>0 && _Height>0 )
    {
	    /* viewport changes screen coordinates, use scissor instead
        D3D10_VIEWPORT vp;
        vp.TopLeftX = _X0;
        vp.TopLeftY = _Y0;
        vp.Width = _Width;
        vp.Height = _Height;
        vp.MinDepth = 0;
        vp.MaxDepth = 1;
        m_D3DDev->RSSetViewports(1, &vp);
        */

        m_ViewportAndScissorRects[0].left = _X0;
        m_ViewportAndScissorRects[0].right = _X0 + _Width - 1;
        m_ViewportAndScissorRects[0].top = _Y0;
        m_ViewportAndScissorRects[0].bottom = _Y0 + _Height - 1;
        if( RectIsFull(m_ViewportAndScissorRects[1]) )
            m_D3DDev->RSSetScissorRects(1, m_ViewportAndScissorRects); // viewport clipping only
        else
            m_D3DDev->RSSetScissorRects(2, m_ViewportAndScissorRects);

        m_OffsetX = _X0 + _OffsetX;
        m_OffsetY = _Y0 + _OffsetY;
    }
}

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

void CTwGraphDirect3D10::RestoreViewport()
{
    //m_D3DDev->RSSetViewports(1, static_cast<D3D10_VIEWPORT *>(m_ViewportInit));
    m_ViewportAndScissorRects[0] = FullRect;
    m_D3DDev->RSSetScissorRects(1, m_ViewportAndScissorRects+1); // scissor only

    m_OffsetX = m_OffsetY = 0;
}

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

void CTwGraphDirect3D10::SetScissor(int _X0, int _Y0, int _Width, int _Height)
{
    if( _Width>0 && _Height>0 )
    {
        m_ViewportAndScissorRects[1].left = _X0 - 2;
        m_ViewportAndScissorRects[1].right = _X0 + _Width - 3;
        m_ViewportAndScissorRects[1].top = _Y0 - 1;
        m_ViewportAndScissorRects[1].bottom = _Y0 + _Height - 1;
        if( RectIsFull(m_ViewportAndScissorRects[0]) )
            m_D3DDev->RSSetScissorRects(1, m_ViewportAndScissorRects+1); // no viewport clipping
        else
            m_D3DDev->RSSetScissorRects(2, m_ViewportAndScissorRects);
    }
    else
    {
        m_ViewportAndScissorRects[1] = FullRect;
        m_D3DDev->RSSetScissorRects(1, m_ViewportAndScissorRects); // apply viewport clipping only
    }
}

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

void CTwGraphDirect3D10::DrawTriangles(int _NumTriangles, int *_Vertices, color32 *_Colors, Cull _CullMode)
{
    assert(m_Drawing==true);

    if( _NumTriangles<=0 )
        return;

    if( m_TrianglesVertexBufferCount<3*_NumTriangles ) // force re-creation
    {
	    if( m_TrianglesVertexBuffer!=NULL )
	        m_TrianglesVertexBuffer->Release();
        m_TrianglesVertexBuffer = NULL;
        m_TrianglesVertexBufferCount = 0;
    }

    // DrawTriangles uses LineRect layout and technique

    if( m_TrianglesVertexBuffer==NULL )
    {
        // Create triangles vertex buffer
        D3D10_BUFFER_DESC bd;
        bd.Usage = D3D10_USAGE_DYNAMIC;
        bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
        bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
        bd.MiscFlags = 0;
        bd.ByteWidth = 3*_NumTriangles * sizeof(CLineRectVtx);
        HRESULT hr = m_D3DDev->CreateBuffer(&bd, NULL, &m_TrianglesVertexBuffer);
        if( SUCCEEDED(hr) )
            m_TrianglesVertexBufferCount = 3*_NumTriangles;
        else
        {
            m_TrianglesVertexBuffer = NULL;
            m_TrianglesVertexBufferCount = 0;
            return; // Problem: cannot create triangles VB
        }
    }
    assert( m_TrianglesVertexBufferCount>=3*_NumTriangles );
    assert( m_TrianglesVertexBuffer!=NULL );

    CLineRectVtx *vertices = NULL;
    HRESULT hr = m_TrianglesVertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, (void **)&vertices);
    if( SUCCEEDED(hr) )
    {
        // Fill vertex buffer
        for( int i=0; i<3*_NumTriangles; ++ i )
        {
            vertices[i].m_Pos[0] = ToNormScreenX(_Vertices[2*i+0] + m_OffsetX, m_WndWidth);
            vertices[i].m_Pos[1] = ToNormScreenY(_Vertices[2*i+1] + m_OffsetY, m_WndHeight);
            vertices[i].m_Pos[2] = 0;
            vertices[i].m_Color = ToR8G8B8A8(_Colors[i]);
        }
        m_TrianglesVertexBuffer->Unmap();

        // Reset shader globals
        float offsetVec[4] = { 0, 0, 0, 0 };
        if( m_OffsetVar )
            m_OffsetVar->SetFloatVector(offsetVec);
        float colorVec[4] = { 1, 1, 1, 1 };
        if( m_CstColorVar )
            m_CstColorVar->SetFloatVector(colorVec);

        // Set the input layout
        m_D3DDev->IASetInputLayout(m_LineRectVertexLayout);

        // Set vertex buffer
        UINT stride = sizeof(CLineRectVtx);
        UINT offset = 0;
        m_D3DDev->IASetVertexBuffers(0, 1, &m_TrianglesVertexBuffer, &stride, &offset);

        // Set primitive topology
        m_D3DDev->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        if( _CullMode==CULL_CW )
            m_D3DDev->RSSetState(m_RasterStateCullCW);
        else if( _CullMode==CULL_CCW )
            m_D3DDev->RSSetState(m_RasterStateCullCCW);

        // Render the triangles
        D3D10_TECHNIQUE_DESC techDesc;
        m_LineRectTech->GetDesc(&techDesc);
        for(UINT p=0; p<techDesc.Passes; ++p)
        {
            m_LineRectTech->GetPassByIndex(p)->Apply(0);
            m_D3DDev->Draw(3*_NumTriangles, 0);
        }

        if( _CullMode==CULL_CW || _CullMode==CULL_CCW )
            m_D3DDev->RSSetState(m_RasterState); // restore default raster state

        // Unset vertex buffer
        ID3D10Buffer *vb = NULL;
        m_D3DDev->IASetVertexBuffers(0, 1, &vb, &stride, &offset);
    }
}

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


text:
This file is currently only a template for future use.

Each change falls into one of the following categories: Added, Changed, Deprecated, Removed, Fixed or Security.

## [Unreleased]

### Changed
 - Enable modules schnorrsig, extrakeys and ECDH by default in ./configure

## [MAJOR.MINOR.PATCH] - YYYY-MM-DD

### Added/Changed/Deprecated/Removed/Fixed/Security
- [Title with link to Pull Request](https://link-to-pr)

redpajama_set_name: RedPajamaGithub


text:
  Dieue-sur-Meuse est
      une commune située dans le département de Meuse en Lorraine. Elle totalisait 1 382 habitants en 2008.

La commune compte quelques  aménagements, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et une salle de combat.

Le parc de logements, à Dieue-sur-Meuse, était réparti en 2011 en 88 appartements et 535 maisons soit
 un marché relativement équilibré.

À coté de Dieue-sur-Meuse sont positionnées géographiquement les communes de
Haudainville à 6 km, 1 003 habitants,
Sommedieue à 3 km, 944 habitants,
Génicourt-sur-Meuse localisée à 4 km, 272 habitants,
Dugny-sur-Meuse à 5 km, 1 324 habitants,
Les Monthairons localisée à 2 km, 361 habitants,
Villers-sur-Meuse à 5 km, 219 habitants,
 entre autres. De plus, Dieue-sur-Meuse est située à seulement dix km de Verdun.

À Dieue-sur-Meuse, la valeur moyenne à l'achat d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 509 € du m². À la location la valeur moyenne se situe à 6,5 € du m² par mois.


text:
/**
 * Lab: 8
 * @author Marc Woodyard
 */

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculator {

	public JTextField textField = new JTextField("", 28);
	public String[] buttonText = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "+", "=", "C"};
	public JButton[] button = new JButton[buttonText.length];

	public Calculator() {

	}

	public static void main(String[] args) {

		Calculator a = new Calculator();

		JFrame frame = new JFrame("Marc's Calculator");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Program Main Container
		Container container = frame.getContentPane();
		container.setLayout(new GridLayout(0, 1, 2, 2));

		// Program Title
		a.textField.setHorizontalAlignment(4);
		JPanel title = new JPanel();
		title.add(new JLabel("Calculator"));
		container.add(title);
		container.add(a.textField);

		// Label Buttons
		for (int i = 0; i < a.buttonText.length; i++) {
		    a.button[i] = new JButton(a.buttonText[i]);
		}

		// First Row
		JPanel row1 = new JPanel(new GridLayout(0, 4, 2, 2));
		row1.add(a.button[0]);
		row1.add(a.button[1]);
		row1.add(a.button[2]);
		row1.add(a.button[3]);
		container.add(row1);

		// Second Row
		JPanel row2 = new JPanel(new GridLayout(0, 4, 2, 2));
		row2.add(a.button[4]);
		row2.add(a.button[5]);
		row2.add(a.button[6]);
		row2.add(a.button[7]);
		container.add(row2);

		// Third Row
		JPanel row3 = new JPanel(new GridLayout(0, 4, 2, 2));
		row3.add(a.button[8]);
		row3.add(a.button[9]);
		row3.add(a.button[10]);
		row3.add(a.button[11]);
		container.add(row3);

		// Fourth Row
		JPanel row412 = new JPanel(new GridLayout(0, 2, 2, 2));
		row412.add(a.button[12]);

		JPanel row422 = new JPanel(new GridLayout(0, 2, 2, 2));
		row422.add(a.button[13]);
		row422.add(a.button[14]);

		row412.add(row422);
		container.add(row412);

		// Fifth Row
		JPanel row5 = new JPanel(new GridLayout(0, 2, 2, 2));
		row5.add(a.button[15]);
		row5.add(a.button[16]);
		container.add(row5);

		frame.pack();
		frame.setVisible(true);
	}
}


text:
namespace TeamBuilder.Data.Configurations
{
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata.Builders;
    using Models;

    internal class TeamEventConfiguration : IEntityTypeConfiguration<TeamEvent>
    {
        public void Configure(EntityTypeBuilder<TeamEvent> builder)
        {
            builder.HasKey(e => new { e.EventId, e.TeamId });

            builder.HasOne(e => e.Event)
                .WithMany(t => t.ParticipatingEventTeams)
                .HasForeignKey(e => e.EventId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.HasOne(e => e.Team)
                .WithMany(t => t.EventTeams)
                .HasForeignKey(e => e.TeamId)
                .OnDelete(DeleteBehavior.Restrict);
        }
    }
}


text:
if (typeof arguments[1] !== "boolean")
    throw "ctrlKey not boolean";
if (typeof arguments[2] !== "boolean")
    throw "shiftKey not boolean";
if (typeof arguments[3] !== "boolean")
    throw "altKey not boolean";

var pressKeyCode = (arguments[8] ? 0 : arguments[7]);

// var keyLogger = document.getElementById("output");
// keyLogger.appendChild(document.createTextNode(
//    `arguments[6]: ${arguments[6]}, arguments[7]: ${arguments[7]}, pressKeyCode: ${pressKeyCode}`));
// keyLogger.appendChild(document.createElement("br"));

var pressData = {
    bubbles: true,
    cancelable: true,
    view: window,
    ctrlKey: arguments[1],
    shiftKey: arguments[2],
    altKey: arguments[3],
    key: arguments[4],
    code: arguments[5],
    charCode: arguments[6],
    keyCode: pressKeyCode,
    which: arguments[6]
};

var downUpData = {
    bubbles: true,
    cancelable: true,
    view: window,
    ctrlKey: arguments[1],
    shiftKey: arguments[2],
    altKey: arguments[3],
    key: arguments[4],
    code: arguments[5],
    charCode: 0,
    keyCode: arguments[7],
    which: arguments[7]
};

var keydownEvent = new KeyboardEvent("keydown", downUpData);
var keypressEvent = new KeyboardEvent("keypress", pressData);
var keyupEvent = new KeyboardEvent("keyup", downUpData);

var element = arguments[0];

var ctrlData;
var ctrlKey = arguments[1];
if (ctrlKey) {
    ctrlData = {
        bubbles: true,
        cancelable: true,
        view: window,
        ctrlKey: true,
        shiftKey: false,
        altKey: false,
        key: "Control",
        code: "ControlLeft",
        charCode: 0,
        keyCode: 17,
        which: 17
    };

    element.dispatchEvent(new KeyboardEvent("keydown", ctrlData));
}

var shiftData;
var shiftKey = arguments[2];
if (shiftKey) {
    shiftData = {
        bubbles: true,
        cancelable: true,
        view: window,
        ctrlKey: true,
        shiftKey: true,
        altKey: false,
        key: "Shift",
        code: "ShiftLeft",
        charCode: 0,
        keyCode: 0x10,
        which: 0x10
    };

    element.dispatchEvent(new KeyboardEvent("keydown", shiftData));
}

window.setTimeout(function() {
    element.dispatchEvent(keydownEvent);
    element.dispatchEvent(keypressEvent);
    window.setTimeout(function() {
        element.dispatchEvent(keyupEvent);
        if (ctrlKey) {
            element.dispatchEvent(new KeyboardEvent("keyup", ctrlData));
        }
        if (shiftKey) {
            element.dispatchEvent(new KeyboardEvent("keyup", shiftData));
        }
    }, 10)
}, 0);


text:
<?php

if (!function_exists('is_field_translatable')) {
    /**
     * Check if a Field is translatable.
     *
     * @param Illuminate\Database\Eloquent\Model      $model
     * @param Illuminate\Database\Eloquent\Collection $row
     */
    function is_field_translatable($model, $row)
    {
        if (!is_crud_translatable($model)) {
            return;
        }

        return $model->translatable()
            && method_exists($model, 'getTranslatableAttributes')
            && in_array($row->field, $model->getTranslatableAttributes());
    }
}

if (!function_exists('get_field_translations')) {
    /**
     * Return all field translations.
     *
     * @param Illuminate\Database\Eloquent\Model $model
     * @param string                             $field
     * @param string                             $rowType
     * @param bool                               $stripHtmlTags
     */
    function get_field_translations($model, $field, $rowType = '', $stripHtmlTags = false)
    {
        $_out = $model->getTranslationsOf($field);

        if ($stripHtmlTags && $rowType == 'rich_text_box') {
            foreach ($_out as $language => $value) {
                $_out[$language] = strip_tags($_out[$language]);
            }
        }

        return json_encode($_out);
    }
}

if (!function_exists('is_crud_translatable')) {
    /**
     * Check if BREAD is translatable.
     *
     * @param Illuminate\Database\Eloquent\Model $model
     */
    function is_crud_translatable($model)
    {
        return config('admin.multilingual.enabled')
            && isset($model)
            && method_exists($model, 'translatable')
            && $model->translatable();
    }
}


text:
/* eslint-env jest */

var Mapper = require('../mapper')
var urlMapper = require('../index')

describe('mapper', function () {
  var parse = jest.fn()
  var stringify = jest.fn()
  var compileFn = jest.fn(function compileFn(route, options, cache) {
    parse.mockImplementation(function (url) {
      // match if url starts with route without colon
      // 'url' matches ':url'
      // 'url2' matches ':url'
      // 'url' does not matches ':url2'
      if (url.slice(0, route.length - 1) === route.slice(1)) return { route: route, url: url }
    })
    return {
      parse: parse,
      stringify: stringify
    }
  })

  it('should return object with expected methods', function () {
    var mapper = Mapper(compileFn)

    expect(typeof mapper.parse).toBe('function')
    expect(typeof mapper.stringify).toBe('function')
    expect(typeof mapper.map).toBe('function')
  })

  it('should throw if compileFn was not provided', function () {
    var options = {}

    expect(function () {
      Mapper(compileFn)
      Mapper(compileFn, options)
    }).not.toThrow()

    expect(function () {
      Mapper()
    }).toThrow()

    expect(function () {
      Mapper(options)
    }).toThrow()
  })

  describe('parse', function () {
    it('should pass route and options arguments to compileFn and its parse method', function () {
      var options = {}
      var mapper = Mapper(compileFn, options)
      mapper.parse('route', 'url')
      expect(compileFn).toBeCalledWith('route', options)
      expect(parse).toBeCalledWith('url')
    })

    it('should throw on missing arguments', function () {
      var mapper = Mapper(compileFn)

      expect(function () {
        mapper.parse('route')
      }).toThrow()

      expect(function () {
        mapper.parse()
      }).toThrow()
    })
  })

  describe('stringify', function () {
    it('should pass route and options arguments to compileFn and its stringify method', function () {
      var options = {}
      var object = {}
      var mapper = Mapper(compileFn, options)

      mapper.stringify('route', object)
      expect(compileFn).toBeCalledWith('route', options)
      expect(stringify).toBeCalledWith(object)
    })

    it('should throw on missing arguments', function () {
      var mapper = Mapper(compileFn)

      expect(function () {
        mapper.stringify('route')
      }).toThrow()

      expect(function () {
        mapper.stringify()
      }).toThrow()
    })
  })

  describe('map', function () {
    it('should pass route and options arguments to compileFn', function () {
      var options = {}
      var routes = {
        ':url': {}
      }
      var mapper = Mapper(compileFn, options)

      mapper.map('url', routes)
      expect(compileFn).toBeCalledWith(':url', options)
    })

    it('should return matched route and parsed values', function () {
      var routes = {
        ':url1': 'match1',
        ':url2': 'match2'
      }
      var mapper = Mapper(compileFn)

      expect(mapper.map('url1', routes)).toEqual({
        route: ':url1',
        match: 'match1',
        values: {
          route: ':url1',
          url: 'url1'
        }
      })

      expect(mapper.map('url2', routes)).toEqual({
        route: ':url2',
        match: 'match2',
        values: {
          route: ':url2',
          url: 'url2'
        }
      })
    })

    it('should return only first matched route and parsed values', function () {
      var routes = {
        ':url': 'match1',
        ':url1': 'match2'
      }
      var mapper = Mapper(compileFn)

      expect(mapper.map('url11', routes)).toEqual({
        route: ':url',
        match: 'match1',
        values: {
          route: ':url',
          url: 'url11'
        }
      })
    })

    it('should throw on missing arguments', function () {
      var mapper = Mapper(compileFn)

      expect(function () {
        mapper.map('url')
      }).toThrow()

      expect(function () {
        mapper.map()
      }).toThrow()
    })
  })
})

describe('urlMapper', function () {
  describe('without query support', function () {
    it('should parse url without query', function () {
      var mapper = urlMapper()

      expect(mapper.parse('/:foo/:bar', '/bar/baz')).toEqual({
        foo: 'bar',
        bar: 'baz'
      })
    })

    it('should parse url ignoring query', function () {
      var mapper = urlMapper()

      expect(mapper.parse('/:foo/:bar', '/bar/baz?query')).toEqual({
        foo: 'bar',
        bar: 'baz'
      })
    })

    it('should parse url ignoring hash', function () {
      var mapper = urlMapper()

      expect(mapper.parse('/:foo/:bar', '/bar/baz#hash')).toEqual({
        foo: 'bar',
        bar: 'baz'
      })
    })

    it('should not parse if url does not matches to route', function () {
      var mapper = urlMapper()

      expect(mapper.parse('/:foo/:bar', '/bar')).toBeNull()
    })

    it('should stringify object using only params defined in route', function () {
      var mapper = urlMapper()

      expect(
        mapper.stringify('/:foo/:bar', {
          foo: 'bar',
          bar: 'baz',
          baz: 'foo',
          qux: {}
        })
      ).toEqual('/bar/baz')
    })

    it('should parse stringified object with booleans and numbers as params defined in route', function () {
      var mapper = urlMapper()
      var object = {
        foo: true,
        bar: false,
        baz: 42,
        qux: null
      }
      // URLON-like notation
      var url = '/:true/:false/:42/:null'

      expect(mapper.stringify('/:foo/:bar/:baz/:qux', object)).toEqual(url)
      expect(mapper.parse('/:foo/:bar/:baz/:qux', url)).toEqual(object)
    })

    it('should properly escape unsafe symbols in segments', function () {
      var mapper = urlMapper()
      var object = {
        foo: 'foo/?#\'"bar'
      }

      var url = '/foo%2F%3F%23%27%22bar'

      expect(mapper.stringify('/:foo', object)).toEqual(url)
      expect(mapper.parse('/:foo', url)).toEqual(object)
    })

    it('should throw if property mapped to a part of path is object', function () {
      var mapper = urlMapper()

      expect(function () {
        mapper.stringify('/:foo', {
          foo: {},
          bar: 'baz',
          baz: 'foo'
        })
      }).toThrow()
    })
  })

  describe('with query support', function () {
    it('should parse url without query', function () {
      var mapper = urlMapper({ query: true })

      expect(mapper.parse('/:foo/:bar', '/bar/baz')).toEqual({
        foo: 'bar',
        bar: 'baz'
      })
    })

    it('should parse url with qs-like query', function () {
      var mapper = urlMapper({ query: true })

      expect(mapper.parse('/:foo/:bar', '/bar/baz?baz=foo')).toEqual({
        foo: 'bar',
        bar: 'baz',
        baz: 'foo'
      })
    })

    it('should parse url ignoring hash', function () {
      var mapper = urlMapper({ query: true })

      expect(mapper.parse('/:foo/:bar', '/bar/baz#hash')).toEqual({
        foo: 'bar',
        bar: 'baz'
      })

      expect(mapper.parse('/:foo/:bar', '/bar/baz?baz=foo#hash')).toEqual({
        foo: 'bar',
        bar: 'baz',
        baz: 'foo'
      })
    })

    it('should not parse if url does not matches to route', function () {
      var mapper = urlMapper({ query: true })

      expect(mapper.parse('/:foo/:bar', '/bar')).toBeNull()
    })

    it('should stringify object without query', function () {
      var mapper = urlMapper({ query: true })

      expect(
        mapper.stringify('/:foo/:bar', {
          foo: 'bar',
          bar: 'baz'
        })
      ).toEqual('/bar/baz')
    })

    it('should not stringify undefined query params', function () {
      var mapper = urlMapper({ query: true })

      expect(
        mapper.stringify('/:foo', {
          foo: 'bar',
          bar: undefined
        })
      ).toEqual('/bar')
    })

    it('should parse stringified object including params not defined in route', function () {
      var mapper = urlMapper({ query: true })
      var object = {
        foo: 'bar',
        bar: true,
        baz: {
          foo: true,
          bar: 2,
          baz: ['foo', 'bar', 'baz'],
          e: ''
        }
      }

      // we do not test which url it stringified to
      // but if you are curious:
      // '/bar?bar:true&baz_foo:true&bar:2&baz@=foo&=bar&=baz;&e='
      expect(mapper.parse('/:foo', mapper.stringify('/:foo', object))).toEqual(object)
    })

    it('should allow custom query separator', function () {
      var mapper = urlMapper({ query: true, querySeparator: '#' })
      expect(mapper.stringify('/:foo', { foo: 'bar', bar: 'baz' })).toEqual('/bar#bar=baz')
      expect(mapper.parse('/:foo', '/bar#bar=baz')).toEqual({ foo: 'bar', bar: 'baz' })

      mapper = urlMapper({ query: true, querySeparator: '@' })
      expect(mapper.stringify('/:foo', { foo: 'bar', bar: 'baz' })).toEqual('/bar@bar=baz')
      expect(mapper.parse('/:foo', '/bar@bar=baz')).toEqual({ foo: 'bar', bar: 'baz' })

      mapper = urlMapper({ query: true, querySeparator: '@@' })
      expect(mapper.stringify('/:foo', { foo: 'bar', bar: 'baz' })).toEqual('/bar@@bar=baz')
      expect(mapper.parse('/:foo', '/bar@@bar=baz')).toEqual({ foo: 'bar', bar: 'baz' })

      mapper = urlMapper({ query: true, querySeparator: '#@' })
      expect(mapper.stringify('/:foo', { foo: 'bar', bar: 'baz' })).toEqual('/bar#@bar=baz')
      expect(mapper.parse('/:foo', '/bar#@bar=baz')).toEqual({ foo: 'bar', bar: 'baz' })
    })

    it('should parse optional paramters as undefined', function () {
      var mapper = urlMapper()

      expect(mapper.parse('/:foo/:bar?', '/bar/')).toEqual({
        foo: 'bar',
        bar: undefined
      })
    })
  })
})


text:
package org.apache.flink.table.planner.plan.utils

import org.apache.flink.table.functions.BuiltInFunctionDefinitions
import org.apache.flink.table.planner.calcite.FlinkRelBuilder
import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction

import org.apache.calcite.plan.RelOptUtil
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.core.{JoinRelType, SetOp}
import org.apache.calcite.rex.RexNode
import org.apache.calcite.sql.fun.SqlStdOperatorTable
import org.apache.calcite.tools.RelBuilder
import org.apache.calcite.util.Util

import java.util
import java.util.Collections

/** Util class that rewrite [[SetOp]]. */
object SetOpRewriteUtil {

  /**
   * Generate equals condition by keys (The index on both sides is the same) to join left relNode
   * and right relNode.
   */
  def generateEqualsCondition(
      relBuilder: RelBuilder,
      left: RelNode,
      right: RelNode,
      keys: Seq[Int]): Seq[RexNode] = {
    val rexBuilder = relBuilder.getRexBuilder
    val leftTypes = RelOptUtil.getFieldTypeList(left.getRowType)
    val rightTypes = RelOptUtil.getFieldTypeList(right.getRowType)
    val conditions = keys.map {
      key =>
        val leftRex = rexBuilder.makeInputRef(leftTypes.get(key), key)
        val rightRex = rexBuilder.makeInputRef(rightTypes.get(key), leftTypes.size + key)
        val equalCond = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, leftRex, rightRex)
        relBuilder.or(
          equalCond,
          relBuilder.and(relBuilder.isNull(leftRex), relBuilder.isNull(rightRex)))
    }
    conditions
  }

  /**
   * Use table function to replicate the row N times. First field is long type, and the rest are the
   * row fields.
   */
  def replicateRows(
      relBuilder: RelBuilder,
      outputRelDataType: RelDataType,
      fields: util.List[Integer]): RelNode = {
    val cluster = relBuilder.getCluster

    val sqlFunction =
      BridgingSqlFunction.of(cluster, BuiltInFunctionDefinitions.INTERNAL_REPLICATE_ROWS)

    FlinkRelBuilder.pushFunctionScan(
      relBuilder,
      sqlFunction,
      0,
      relBuilder.fields(Util.range(fields.size() + 1)),
      outputRelDataType.getFieldNames)

    // correlated join
    val corSet = Collections.singleton(cluster.createCorrel())
    val output = relBuilder
      .join(JoinRelType.INNER, relBuilder.literal(true), corSet)
      .project(relBuilder.fields(Util.range(fields.size() + 1, fields.size() * 2 + 1)))
      .build()
    output
  }
}


text:
using System.Xml.Serialization;

namespace EConnectApi.Definitions
{
    [XmlType(AnonymousType = true, Namespace = "http://ws.vg.pw.com/external/1.0")]
    [XmlRoot(Namespace = "http://ws.vg.pw.com/external/1.0", ElementName = "GetDocuments", IsNullable = false)]
    public class GetDocumentsFromGroup : GetDocumentsFromGroupBase, IDocumentsRequest
    {
        // Nothing extra
    }
}


text:
package it.unibz.krdb.odba;

import it.unibz.krdb.obda.io.ModelIOManager;
import it.unibz.krdb.obda.model.OBDADataFactory;
import it.unibz.krdb.obda.model.OBDAModel;
import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl;
import it.unibz.krdb.obda.owlrefplatform.core.QuestConstants;
import it.unibz.krdb.obda.owlrefplatform.core.QuestPreferences;
import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWL;
import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWLConnection;
import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWLFactory;
import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWLResultSet;
import it.unibz.krdb.obda.owlrefplatform.owlapi3.QuestOWLStatement;
import it.unibz.krdb.obda.utils.SQLScriptRunner;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.SimpleConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 * A simple test that check if the system is able to handle Mappings for
 * classes/roles and attributes even if there are no URI templates. i.e., the
 * database stores URI's directly.
 *
 * We are going to create an H2 DB, the .sql file is fixed. We will map directly
 * there and then query on top.
 */
public class ReverseURITestH2 {

	// TODO We need to extend this test to import the contents of the mappings
	// into OWL and repeat everything taking form OWL

	private static OBDADataFactory fac;
	private static QuestOWLConnection conn;

	static Logger log = LoggerFactory.getLogger(ReverseURITestH2.class);
	private static OBDAModel obdaModel;
	private static OWLOntology ontology;

	final static String owlfile = "src/test/resources/reverse-uri-test.owl";
	final static String obdafile = "src/test/resources/reverse-uri-test.obda";
	private static QuestOWL reasoner;

	private static Connection sqlConnection;

	private static void runUpdateOnSQLDB(String sqlscript, Connection sqlConnection)
			throws Exception {

		Statement st = sqlConnection.createStatement();

		FileReader reader = new FileReader(sqlscript);
		BufferedReader in = new BufferedReader(reader);
		StringBuilder bf = new StringBuilder();
		String line = in.readLine();
		while (line != null) {
			bf.append(line);
			bf.append("\n");
			line = in.readLine();
		}
		in.close();

		System.out.println(bf.toString());
		st.executeUpdate(bf.toString());
		if (!sqlConnection.getAutoCommit())
			sqlConnection.commit();
	}

	@Before
	public void init() {

	}

	@After
	public void after() {

	}

	@BeforeClass
	public static void setUp() throws Exception {

		 String url = "jdbc:h2:mem:questrepository;";
		 String username = "fish";
		 String password = "fish";

//		String url = "jdbc:mysql://33.33.33.1:3306/ontop?sessionVariables=sql_mode='ANSI'&allowMultiQueries=true";
		//String url = "jdbc:postgresql://localhost/ontop";
//		String url = "jdbc:db2://192.168.99.100:50000/ontop";
//		String url = "jdbc:oracle:thin:@192.168.99.100:49161:xe";

//		String username = "db2inst1";
//		String password = "ontop";

		// system/oracle

		System.out.println("Test");
		fac = OBDADataFactoryImpl.getInstance();

		try {

			sqlConnection = DriverManager
					.getConnection(url, username, password);

//			runUpdateOnSQLDB("src/test/resources/reverse-uri-test.sql",
//					sqlConnection);

			FileReader reader = new FileReader("src/test/resources/reverse-uri-test.sql");
			BufferedReader in = new BufferedReader(reader);
			SQLScriptRunner runner = new SQLScriptRunner(sqlConnection, true, false);
			runner.runScript(in);

			// Loading the OWL file
			OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
			ontology = manager.loadOntologyFromOntologyDocument((new File(
					owlfile)));

			// Loading the OBDA data
			fac = OBDADataFactoryImpl.getInstance();
			obdaModel = fac.getOBDAModel();

			ModelIOManager ioManager = new ModelIOManager(obdaModel);
			ioManager.load(obdafile);

			QuestPreferences p = new QuestPreferences();
			p.setCurrentValueOf(QuestPreferences.ABOX_MODE,
					QuestConstants.VIRTUAL);
			p.setCurrentValueOf(QuestPreferences.OBTAIN_FULL_METADATA,
					QuestConstants.FALSE);
			// Creating a new instance of the reasoner
			QuestOWLFactory factory = new QuestOWLFactory();
			factory.setOBDAController(obdaModel);

			factory.setPreferenceHolder(p);

			reasoner = (QuestOWL) factory.createReasoner(ontology,
					new SimpleConfiguration());

			// Now we are ready for querying
			conn = reasoner.getConnection();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			log.error(e.getMessage(), e);
			throw e;
		}

	}

	@AfterClass
	public static void tearDown() throws Exception {

		FileReader reader = new FileReader("src/test/resources/reverse-uri-test.sql.drop");
		BufferedReader in = new BufferedReader(reader);
		SQLScriptRunner runner = new SQLScriptRunner(sqlConnection, true, false);
		runner.runScript(in);

		conn.close();
		reasoner.dispose();
		if (!sqlConnection.isClosed()) {
			java.sql.Statement s = sqlConnection.createStatement();
			try {
				s.execute("DROP ALL OBJECTS DELETE FILES");
			} catch (SQLException sqle) {
				System.out.println("Table not found, not dropping");
			} finally {
				s.close();
				sqlConnection.close();
			}
		}

	}

	private void runTests(String query, int numberOfResults) throws Exception {
		QuestOWLStatement st = conn.createStatement();
		try {

			QuestOWLResultSet rs = st.executeTuple(query);
			/*
			 * boolean nextRow = rs.nextRow();
			 */
			// assertTrue(rs.nextRow());
			int count = 0;
			while (rs.nextRow()) {
				OWLObject ind1 = rs.getOWLObject("x");
				System.out.println("Result " + ind1.toString());
				count += 1;
			}
			org.junit.Assert.assertTrue(count == numberOfResults);

			/*
			 * assertEquals("<uri1>", ind1.toString()); assertEquals("<uri1>",
			 * ind2.toString()); assertEquals("\"value1\"", val.toString());
			 */

		} catch (Exception e) {
			throw e;
		} finally {
			try {

			} catch (Exception e) {
				st.close();
				org.junit.Assert.assertTrue(false);
			}
			conn.close();
			reasoner.dispose();
		}
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testSingleColum2() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-Cote%20D%22ivore> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testSingleColum() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-John%20Smith> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testTwoColum2() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-Cote%20D%22ivore-Cote%20D%22ivore> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testTwoColum2Value() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-John%20Smith-John%20Smith%202> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testTwoColum22Vaule() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-Cote%20D%22ivore-Cote%20D%22ivore%202> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testTwoColum() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-John%20Smith-John%20Smith> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testThreeColum2() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-Cote%20D%22ivore-Cote%20D%22ivore-Cote%20D%22ivore> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testThreeColum() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-John%20Smith-John%20Smith-John%20Smith> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testThreeColum23Value() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-Cote%20D%22ivore-Cote%20D%22ivore%202-Cote%20D%22ivore%203> a ?x}";
		runTests(query, 1);
	}

	/**
	 * Test use of two aliases to same table
	 *
	 * @throws Exception
	 */
	@Test
	public void testThreeColum3Value() throws Exception {
		String query = "PREFIX : <http://www.ontop.org/> SELECT ?x WHERE {<http://www.ontop.org/test-John%20Smith-John%20Smith%202-John%20Smith%203> a ?x}";
		runTests(query, 1);
	}

}


text:
<?php
namespace xz1mefx\multilang\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%message}}".
 *
 * @property integer       $id
 * @property string        $language
 * @property string        $translation
 *
 * @property SourceMessage $id0
 */
class Message extends ActiveRecord
{

    const TABLE_NAME = '{{%ml_message}}';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return self::TABLE_NAME;
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['id', 'language'];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => time(),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'created_at', 'updated_at'], 'integer'],
            [['translation'], 'string'],
            [['language'], 'string', 'max' => 16],
            [['id', 'language'], 'unique', 'targetAttribute' => ['id', 'language'], 'message' => Yii::t('multilang-tools', 'The combination of ID and Language has already been taken.')],
            [['id'], 'exist', 'skipOnError' => TRUE, 'targetClass' => SourceMessage::className(), 'targetAttribute' => ['id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function afterSave($insert, $changedAttributes)
    {
        Yii::$app->multilangCache->flush();
        parent::afterSave($insert, $changedAttributes);
    }

    /**
     * @inheritdoc
     */
    public function afterDelete()
    {
        Yii::$app->multilangCache->flush();
        parent::afterDelete();
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('multilang-tools', 'ID'),
            'language' => Yii::t('multilang-tools', 'Language'),
            'translation' => Yii::t('multilang-tools', 'Translation'),
        ];
    }
}


text:
---
title: Sapient Guardian | Microsoft Docs
author: rowanmiller
ms.author: divega

ms.date: 10/27/2016

ms.assetid: 8a1ee790-0015-4392-b9cd-8ae313b287c5
ms.technology: entity-framework-core

uid: core/providers/sapient-guardian/index
---
# Sapient Guardian

> [!NOTE]
> This documentation is for EF Core. For EF6.x, see [Entity Framework 6](../../../ef6/index.md).

This database provider allows Entity Framework Core to be used with MySQL. The provider is maintained in the [SapientGuardian/SapientGuardian.EntityFrameworkCore.MySql GitHub project](https://github.com/SapientGuardian/SapientGuardian.EntityFrameworkCore.MySql).

> [!NOTE]
> This provider is not maintained as part of the Entity Framework Core project. When considering a third party provider, be sure to evaluate quality, licensing, support, etc. to ensure they meet your requirements.

## Install

Install the [SapientGuardian.EntityFrameworkCore.MySql NuGet package](https://www.nuget.org/packages/SapientGuardian.EntityFrameworkCore.MySql).

<!-- literal_block"ids  "classes  "xml:space": "preserve", "backrefs  "linenos": false, "dupnames  : "csharp",", highlight_args}, "names": [] -->
````text
   PM>  Install-Package SapientGuardian.EntityFrameworkCore.MySql
````

## Get Started

Visit the [project site](https://github.com/SapientGuardian/SapientGuardian.EntityFrameworkCore.MySql) to get started with this provider.

## Supported Database Engines

* MySQL

## Supported Platforms

* .NET Framework (4.5.1 onwards)
* .NET Core
* Mono (4.2.0 onwards)


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

<title>ANYONE-WHO-IS</title>
<meta http-equiv="Content-Language" content="en-gb">

I interact with anyone who meets my conditions.

	Begin micro-behaviour

ANYONE-WHO-IS

	Begin NetLogo code:

substitute-text-area-for condition true
anyone-who-is condition
       [add-behaviours-to self list-of-micro-behaviours "My Additional Behaviours" []
        add-behaviours-to the-other list-of-micro-behaviours "Other's Additional Behaviours" []]

	End NetLogo code

Variants

You can replace true with any condition. You can add behaviours
	(and REMOVE-BEHAVIOURS) to the lists.

Related Micro-behaviours

	This uses the Modelling4All NetLogo command

	anyone-who-is which sets

	the-other
	to refer to another agent.

	How this works

I select someone at random that satisfies the condition and if
	there is anyone adds and removes micro-behaviours from the other and myself.

History

This was implemented by Ken Kahn.


text:
package com.jacksay.sgarnish.events;

import com.jacksay.sgarnish.components.JckTabRenderer;

/**
 *
 * @author Stéphane Bouvry<stephane.bouvry@unicaen.fr>
 */
public interface IJckTabRendererListenner {
    void onTabRendererLabelChanged( JckTabRenderer tabRenderer );
    void onTabRendererRemoved( JckTabRenderer tabRenderer );
}


text:
package LBJ2.util;

import java.util.Arrays;

/**
  * Represents a String by directly storing an encoding of that
  * String in an array of bytes.  This can save a
  * lot of memory if all of the application's characters fit in a single byte
  * when encoded by, for instance, UTF-8.  In fact, the default encoding used
  * by this class is UTF-8.
  *
  * @author Nick Rizzolo
 **/
public class ByteString implements Cloneable, Comparable
{
  /** The default character encoding for instances of this class. */
  public static final String defaultEncoding = "UTF-8";
  /** A byte string representing "". */
  public static final ByteString emptyString =
    new ByteString("", defaultEncoding);

  /**
    * Handles exceptions generated by unsupported encodings.
    *
    * @param e  The exception.
   **/
  protected void handleEncodingException(Exception e) {
    System.err.println(
        "ERROR: Encoding \"" + encoding + "\" is not supported.");
    e.printStackTrace();
    System.exit(1);
  }

  /**
    * Reads and returns a byte string from an input stream.
    *
    * @param in The input stream.
    * @return The byte string.
   **/
  public static ByteString readByteString(ExceptionlessInputStream in) {
    ByteString result = new ByteString(false);
    result.read(in);
    return result;
  }

  /**
    * Reads and returns a byte string as written by a lexicon.
    *
    * @param in The input stream.
    * @param i  The assumed identifier.  If no identifier is given in the
    *           input stream, the instantiated feature is given this
    *           identifier.
    * @return The byte string.
   **/
  public static ByteString lexReadByteString(ExceptionlessInputStream in,
                                             ByteString i) {
    ByteString result = new ByteString(false);
    result.lexRead(in, i);
    return result;
  }

  /** The encoding method used by this instance. */
  protected String encoding;
  /** The encoded characters. */
  protected byte[] value;
  /**
    * The hash code of the String decoding of this byte string.
   **/
  protected int hashCode;

  /**
    * For internal use only.
    *
    * @param b  Dummy variable to make a new signature.
   **/
  protected ByteString(boolean b) { }

  /** Creates an empty byte string. */
  public ByteString() { this(""); }

  /**
    * Creates a byte string by using the default encoding to encode the
    * specified string.
    *
    * @param s  The string to encode.
   **/
  public ByteString(String s) { this(s, null); }

  /**
    * Creates a byte string by using the specified encoding to encode the
    * specified string.
    *
    * @param s  The string to encode.
    * @param e  The encoding method.
   **/
  public ByteString(String s, String e) {
    encoding = e == null ? defaultEncoding : e.intern();
    setValue(s);
  }

  /**
    * Creates a byte string with the given encoding, which may involve
    * converting the specified byte string's contents if the encodings differ.
    *
    * @param b  The original byte string.
    * @param e  The new encoding.
   **/
  public ByteString(ByteString b, String e) {
    encoding = e.intern();
    if (b.encoding == encoding) {
      value = b.value;
      hashCode = b.hashCode;
    }
    else setValue(b.toString());
  }

  /** Returns the name of the encoding method of this byte string. */
  public String getEncoding() { return encoding; }

  /**
    * Sets the value of this byte string to the byte encoding of the specified
    * string.
    *
    * @param s  The string to encode.
   **/
  public void setValue(String s) {
    try { value = s.getBytes(encoding); }
    catch (Exception e) { handleEncodingException(e); }
    hashCode = s.hashCode();
  }

  /** Returns the length of {@link #value}. */
  public int length() { return value.length; }

  /**
    * Returns the byte at index i of {@link #value}.
    *
    * @param i  The index of the requested byte.
    * @return The value of the requested byte.
   **/
  public byte getByte(int i) { return value[i]; }

  /**
    * Appends the encoding of the given string onto the existing encoding in
    * this object.  This operation changes the {@link #value} reference in
    * this object.
    *
    *
 Warning: Depending on the character encoding in use, this may
    * introduce byte order markers into the middle of this object's byte
    * array, which usually is not desired.
    *
    * @param s  The string whose encoding will be appended.
    * @return This object.
   **/
  public ByteString append(String s) {
    hashCode = (toString() + s).hashCode();
    byte[] v = null;
    try { v = s.getBytes(encoding); }
    catch (Exception e) { handleEncodingException(e); }

    byte[] t = new byte[value.length + v.length];
    System.arraycopy(value, 0, t, 0, value.length);
    System.arraycopy(v, 0, t, value.length, v.length);
    value = t;
    return this;
  }

  /**
    * Appends the encodings of all the given strings onto the existing
    * encoding in this object.  This operation changes the {@link #value}
    * reference in this object.
    *
    *
 Warning: Depending on the character encoding in use, this may
    * introduce byte order markers into the middle of this object's byte
    * array, which usually is not desired.
    *
    * @param s  The strings whose encodings will be appended.
    * @return This object.
   **/
  public ByteString append(String[] s) {
    StringBuffer buffer = new StringBuffer(toString());
    for (int i = 0; i < s.length; ++i) buffer.append(s[i]);
    hashCode = buffer.toString().hashCode();

    byte[][] v = new byte[s.length][];
    int length = 0;
    try {
      for (int i = 0; i < v.length; ++i) {
        v[i] = s[i].getBytes(encoding);
        length += v[i].length;
      }
    }
    catch (Exception e) { handleEncodingException(e); }

    byte[] t = new byte[length];
    length = value.length;
    System.arraycopy(value, 0, t, 0, length);
    for (int i = 0; i < v.length; ++i) {
      System.arraycopy(v[i], 0, t, length, v[i].length);
      length += v[i].length;
    }

    value = t;
    return this;
  }

  /**
    * Appends the string represented by the given byte string onto the
    * existing content in this object.  This operation changes the
    * {@link #value} reference in this object.
    *
    *
 Warning: Depending on the character encoding in use, this may
    * introduce byte order markers into the middle of this object's byte
    * array, which usually is not desired.
    *
    * @param b  The string whose encoding will be appended.
    * @return This object.
   **/
  public ByteString append(ByteString b) {
    String s = b.toString();
    hashCode = (toString() + s).hashCode();
    if (encoding != b.encoding) return append(s);
    byte[] t = new byte[value.length + b.value.length];
    System.arraycopy(value, 0, t, 0, value.length);
    System.arraycopy(b.value, 0, t, value.length, b.value.length);
    value = t;
    return this;
  }

  /**
    * Appends the strings represented by the given byte strings onto the
    * existing content in this object.  This operation changes the
    * {@link #value} reference in this object.
    *
    *
 Warning: Depending on the character encoding in use, this may
    * introduce byte order markers into the middle of this object's byte
    * array, which usually is not desired.
    *
    * @param b  The strings whose encodings will be appended.
    * @return This object.
   **/
  public ByteString append(ByteString[] b) {
    int length = 0;
    StringBuffer buffer = new StringBuffer(toString());
    for (int i = 0; i < b.length; ++i) {
      String s = b[i].toString();
      buffer.append(s);
      if (encoding != b[i].encoding)
        b[i] = new ByteString(s, encoding);
      length += b[i].value.length;
    }
    hashCode = buffer.toString().hashCode();

    byte[] t = new byte[length];
    length = value.length;
    System.arraycopy(value, 0, t, 0, length);
    for (int i = 0; i < b.length; ++i) {
      System.arraycopy(b[i].value, 0, t, length, b[i].value.length);
      length += b[i].value.length;
    }

    value = t;
    return this;
  }

  /**
    * If the argument object is a byte string, this object's byte array and
    * the argument object's byte array are compared lexicographically.
    * Otherwise, -1 is returned.  Of course, this operation is considerably
    * more expensive if the two strings do not share the same encoding.
   **/
  public int compareTo(Object o) {
    if (!(o instanceof ByteString)) return -1;
    ByteString b = (ByteString) o;
    if (encoding != b.encoding) return toString().compareTo(b.toString());

    int n1 = value.length;
    int n2 = b.value.length;
    int n = Math.min(n1, n2);

    for (int i = 0; i < n; ++i) {
      byte b1 = value[i];
      byte b2 = b.value[i];
      if (b1 != b2) return b1 - b2;
    }

    return n1 - n2;
  }

  /** Returns a hash code for this object. */
  public int hashCode() { return hashCode; }

  /**
    * Two byte strings are equivalent if they encode the same string.  This
    * operation is more expensive if the two byte strings use different
    * encodings.
   **/
  public boolean equals(Object o) {
    if (o instanceof String) return toString().equals(o);
    if (!(o instanceof ByteString)) return false;
    ByteString b = (ByteString) o;
    if (encoding != b.encoding) return toString().equals(b.toString());
    if (value.length != b.value.length) return false;

    for (int i = 0; i < value.length; ++i)
      if (value[i] != b.value[i]) return false;
    return true;
  }

  /**
    * Writes a complete binary representation of this byte string.
    *
    * @param out  The output stream.
   **/
  public void write(ExceptionlessOutputStream out) {
    out.writeString(encoding);
    out.writeInt(hashCode);
    out.writeBytes(value);
  }

  /**
    * Reads in a complete binary representation of a byte string.
    *
    * @param in The input stream.
   **/
  public void read(ExceptionlessInputStream in) {
    encoding = in.readString().intern();
    hashCode = in.readInt();
    value = in.readBytes();
  }

  /**
    * Writes a binary representation of this byte string intended for use by
    * a lexicon, omitting redundant information when possible.
    *
    * @param out  The output stream.
    * @param i    The assumed identifier string.  This byte strings value,
    *             encoding, or both may be omitted if they are equivalent to
    *             i.
   **/
  public void lexWrite(ExceptionlessOutputStream out, ByteString i) {
    if (i != null && encoding == i.encoding && Arrays.equals(value, i.value))
      out.writeBytes(null);
    else {
      out.writeBytes(value);
      out.writeInt(hashCode);
      out.writeString(i != null && encoding == i.encoding ? null : encoding);
    }
  }

  /**
    * Reads the representation of a byte string as stored by a lexicon,
    * overwriting the data in this object.
    *
    *
 This method is appropriate for reading byte strings as written by
    * {@link #lexWrite(ExceptionlessOutputStream,ByteString)}.
    *
    * @param in The input stream.
    * @param i  The assumed identifier string.
   **/
  public void lexRead(ExceptionlessInputStream in, ByteString i) {
    value = in.readBytes();
    if (value == null) {
      value = i.value;
      hashCode = i.hashCode;
      encoding = i.encoding;
    }
    else {
      hashCode = in.readInt();
      encoding = in.readString();
      if (encoding == null) encoding = i.encoding;
      else encoding = encoding.intern();
    }
  }

  /** Returns a decoded string. */
  public String toString() {
    try { return new String(value, encoding); }
    catch (Exception e) { handleEncodingException(e); }
    return null;
  }

  /**
    * Returns a shallow copy of this string.  Note that this class does not
    * provide any operations that modify the contents of the objects
    * referenced by its fields, making a deep clone unnecessary.
    * ({@link #append(String)}, {@link #append(ByteString)}, and
    * {@link #setValue(String)} modify the {@link #value} field itself, but
    * the reference is merely replaced; the contents of the original array do
    * not change.)
   **/
  public Object clone() {
    Object result = null;

    try { result = super.clone(); }
    catch (Exception e) {
      System.err.println("Can't clone byte string '" + this + "':");
      e.printStackTrace();
    }

    return result;
  }
}


text:
namespace Merchello.Bazaar.Models
{
    using System.ComponentModel.DataAnnotations;

    /// <summary>
    /// The customer profile model.
    /// </summary>
    public class CustomerProfileModel
    {
        /// <summary>
        /// Gets or sets the first name.
        /// </summary>
        [Required(ErrorMessage = "First name is required."), Display(Name = "First Name")]
        public string FirstName { get; set; }

        /// <summary>
        /// Gets or sets the last name.
        /// </summary>
        [Required(ErrorMessage = "Last name is required."), Display(Name = "Last Name")]
        public string LastName { get; set; }

        /// <summary>
        /// Gets or sets the email address.
        /// </summary>
        [Required(ErrorMessage = "A valid email address is required."), Display(Name = "Email Address")]
        [EmailAddress]
        public string EmailAddress { get; set; }

        /// <summary>
        /// Gets or sets the new password.
        /// </summary>
        [Required(ErrorMessage = "Password is required"), Display(Name = "Password"), DataType(DataType.Password)]
        public string Password { get; set; }
    }
}


text:
require 'spec_helper'

describe ::Skills::UserSkillRates::Update do
  subject do
    described_class.new(
      user_skill_rate_id: user_skill_rate.id,
      params: params
    )
  end

  describe '#call' do
    let(:user) { create(:user) }
    let(:user_skill_rate) do
      create(:user_skill_rate, note: 'abc', rate: 0, favorite: false, user: user)
    end
    let(:params) do
      {
        id: user_skill_rate.id,
        note: 'def',
        rate: 1,
        favorite: true
      }
    end

    it 'updates note on user rate skill' do
      expect { subject.call }.to change { user_skill_rate.reload.note }.from('abc').to('def')
    end

    it 'updates favorite on user rate skill' do
      expect { subject.call }.to change { user_skill_rate.reload.rate }.from(0).to(1)
    end

    it 'updates favorite on user favorite skill' do
      expect { subject.call }.to change { user_skill_rate.reload.favorite }.from(false).to(true)
    end

    context "when user_skill_rate_content doesn't exist today" do
      let(:last_content) { user_skill_rate.contents.last }

      it 'creates new user_skill_rate_content' do
        expect { subject.call }.to change { user_skill_rate.contents.count }.by(1)
      end

      it 'sets correct values on new content', :aggregate_failures do
        subject.call
        user_skill_rate.reload
        expect(last_content.favorite).to eq(user_skill_rate.favorite)
        expect(last_content.note).to eq(user_skill_rate.note)
        expect(last_content.rate).to eq(user_skill_rate.rate)
      end
    end

    context 'when user_skill_rate_content exists today' do
      let!(:user_skill_rate_content) do
        create(
          :user_skill_rate_content,
          user_skill_rate_id: user_skill_rate.id
        )
      end

      it "doesn't create new user_skill_rate_content" do
        expect { subject.call }.to_not change { user_skill_rate.contents.count }
      end

      it 'updates content', :aggregate_failures do
        subject.call
        user_skill_rate_content.reload
        user_skill_rate.reload
        expect(user_skill_rate_content.favorite)
          .to eq(user_skill_rate.favorite)
        expect(user_skill_rate_content.note).to eq(user_skill_rate.note)
        expect(user_skill_rate_content.rate).to eq(user_skill_rate.rate)
      end
    end

    context 'when two last user_skill_rate_contents are equal' do
      let(:params) do
        {
          id: user_skill_rate.id,
          note: 'def',
          rate: 1,
          favorite: true
        }
      end

      before do
        Timecop.freeze(DateTime.now - 3.days) do
          create(
            :user_skill_rate_content,
            user_skill_rate_id: user_skill_rate.id,
            note: 'def',
            rate: 1,
            favorite: true
          )
        end
      end

      context 'when add new user_skill_rate_content' do
        it "doesn't add new user_skill_rate_content" do
          expect { subject.call }.to_not change { user_skill_rate.contents.count }
        end
      end

      context 'when update last user_skill_rate_content' do
        let!(:user_skill_rate_content) do
          create(
            :user_skill_rate_content,
            user_skill_rate_id: user_skill_rate.id,
            note: 'def',
            rate: 1,
            favorite: true
          )
        end

        it 'removes last user_skill_rate_content' do
          expect { subject.call }.to change { user_skill_rate.contents.count }.by(-1)
        end
      end
    end
  end
end


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.cpd;

import java.util.ArrayList;

/**
 * @author Romain PELISSE - romain.pelisse@atosorigin.com
 *
 */
public class FortranTokenizer extends AbstractTokenizer implements Tokenizer
{
	public FortranTokenizer()
	{
		this.spanMultipleLinesString = false; // No such thing in Fortran !
//		 setting markers for "string" in Fortran
		this.stringToken = new ArrayList<String>();
		this.stringToken.add("\'");
		// setting markers for 'ignorable character' in Fortran
		this.ignorableCharacter = new ArrayList<String>();
		this.ignorableCharacter.add("(");
		this.ignorableCharacter.add(")");
		this.ignorableCharacter.add(",");

		// setting markers for 'ignorable string' in Fortran
		this.ignorableStmt = new ArrayList<String>();
		this.ignorableStmt.add("do");
		this.ignorableStmt.add("while");
		this.ignorableStmt.add("end");
		this.ignorableStmt.add("if");
		// Fortran comment start with an !
		this.oneLineCommentChar = '!';
	}
}