<commit_before>#include "MaterialElement.h"
#include "PhysicalElement.h"
#include <iostream>

//Constructors & destructor-------------------------------
	MaterialElement::MaterialElement()
	{}

	MaterialElement::MaterialElement(Point P, double masse , double charge_)
	{
		position = P;  // does a shallow copy of P
		mass = masse;
        charge = charge_;
	}

	MaterialElement::~MaterialElement()
	{}

//Accessors---------------------------------------------
    Point * MaterialElement::pointerToPosition()
    {
     Point *pos= NULL;
        pos = &position;
     return pos;
	}

    double MaterialElement::getMass()
	{
        return mass;
    }

//Display-----------------------------------------------
	void MaterialElement::consoleShow()
	{
		position.show();
		std::cout<<"mass: "<<mass<<'\n';
	}

//Modifier----------------------------------------------
	void MaterialElement::setPosition(Point &P)
	{
	 position = P;
	}

	void MaterialElement::setPosition(double x, double y, double z)
	{
        position.place(x,y,z);
	}

	void MaterialElement::setMass(double m)
	{
        mass=m;
	}

//Simulation tool-------------------------------------
	void MaterialElement::update(double dt) //computes and updates the state of the element at t+dt
	{
	  Acceleration a;
		a = getAcceleration();
		updateSpeedandPosition(a, dt);

	}

	Acceleration MaterialElement::getAcceleration()
	{
	  Acceleration a;
        a.nullify();

	  Vector V = netForce.getDirection();

        if( mass != 0 )
			{
                V = V*( 1 / mass);
                a.setDirection(V);
			}
		else
			{
				std::cout<<"** No mass no accs :-( **"<<'\n';
			}

	  return a;
	}

	void MaterialElement::updateSpeedandPosition(Acceleration a, double dt)
	{
	  double Vx,Vy,Vz,X,Y,Z;

     //Initial speeds
        Vx = V.getDirection().getx();
        Vy = V.getDirection().gety();
        Vz = V.getDirection().getz();

     //Double integration of the accelerations gives final positions
        X = 0.5*a.getDirection().getx()*dt*dt + Vx*dt + position.getX();
        Y = 0.5*a.getDirection().gety()*dt*dt + Vy*dt + position.getY();
        Z = 0.5*a.getDirection().getz()*dt*dt + Vz*dt + position.getZ();
        position.place(X,Y,Z);

     //integration of the accelerations gives final speeds
        Vx = a.getDirection().getx()*dt + V.getDirection().getx();
        Vy = a.getDirection().gety()*dt + V.getDirection().gety();
        Vz = a.getDirection().getz()*dt + V.getDirection().getz();
        V.setDirection(Vx,Vy,Vz);
	}

<commit_msg>Update MaterialElement.cpp<commit_after>#include "MaterialElement.h"
#include "PhysicalElement.h"
#include <iostream>

//Constructors & destructor-------------------------------
	MaterialElement::MaterialElement()
	{}

	MaterialElement::MaterialElement(Point p, double masse , double charge_)
	{
		Position = p;  // does a shallow copy of P
		Mass = masse;
        Charge = charge_;
	}

	MaterialElement::~MaterialElement()
	{}

//Accessors---------------------------------------------
    Point * MaterialElement::pointerToPosition()
    {
     Point *pos= NULL;
        pos = &Position;
     return pos;
	}

    double MaterialElement::getMass()
	{
        return Mass;
    }

//Display-----------------------------------------------
	void MaterialElement::consoleShow()
	{
		Position.show();
		std::cout<<"mass: "<<Mass<<'\n';
	}

//Modifier----------------------------------------------
	void MaterialElement::setPosition(Point &P)
	{
		Position = P;
	}

	void MaterialElement::setPosition(double x, double y, double z)
	{
        Position.set(x,y,z);
	}

	void MaterialElement::setMass(double m)
	{
        Mass=m;
	}

//Simulation tool-------------------------------------
	void MaterialElement::update(double dt) //computes and updates the state of the element at t+dt
	{
	  Acceleration a;
		a = getAcceleration();
		updateSpeedandPosition(a, dt);

	}

	Acceleration MaterialElement::getAcceleration()
	{
	  Acceleration a;
        a.nullify();

	  Vect V = NetForce.getDirection();

        if( Mass != 0 )
			{
                V = V / Mass;
                a.setDirection(V);
			}
		else
			{
				std::cout<<"** No mass no accs :-( **"<<'\n';
			}

	  return a;
	}

	void MaterialElement::updateSpeedandPosition(Acceleration a, double dt)
	{
	  double Vx,Vy,Vz,X,Y,Z;

     //Initial speeds
        Vx = V.getDirection().getX();
        Vy = V.getDirection().getY();
        Vz = V.getDirection().getZ();

     //Double integration of the accelerations gives final positions
        X = 0.5*a.getDirection().getX()*dt*dt + Vx*dt + Position.getX();
        Y = 0.5*a.getDirection().getY()*dt*dt + Vy*dt + Position.getY();
        Z = 0.5*a.getDirection().getZ()*dt*dt + Vz*dt + Position.getZ();
        Position.set(X,Y,Z);

     //integration of the accelerations gives final speeds
        Vx = a.getDirection().getX()*dt + V.getDirection().getX();
        Vy = a.getDirection().getY()*dt + V.getDirection().getY();
        Vz = a.getDirection().getZ()*dt + V.getDirection().getZ();
        V.setDirection(Vx,Vy,Vz);
	}

<|endoftext|>


<commit_before>#include "MaterialElement.h"
#include "Geo.h"
#include <iostream>

//Constructors & destructor-------------------------------
MaterialElement::MaterialElement()
{}

MaterialElement::MaterialElement(Point p, Vect resultantForce, Vect velocity,
	double masse, double charge_ )
{
	Charge = charge_; 	// in Coulomb
	Mass = masse;   	// in kg
	Velocity = velocity;	// m/s
	NetForce = resultantForce;		// Newton
	Position = p;		// m
}

MaterialElement::~MaterialElement()
{}

//Accessors---------------------------------------------
Point * MaterialElement::pointerToPosition()
{
	Point *pos = NULL;
	pos = &Position;
	return pos;
}

double MaterialElement::getMass()
{
	return Mass;
}

double MaterialElement::getCharge()
{
	return Charge;
}

//Display-----------------------------------------------
void MaterialElement::consoleShow()
{
	Position.show();
	std::cout << "mass: " << Mass << '\n';
	std::cout << "charge: " << Charge << '\n';
}

//Modifier----------------------------------------------
void MaterialElement::setPosition(Point &P)
{
	Position = P;
}

void MaterialElement::setPosition(double x, double y, double z)
{
	Position.place(x, y, z);
}

void MaterialElement::setMass(double m)
{
	Mass = m;
}
void MaterialElement::setCharge(double c)
{
	Charge = c;
}

void MaterialElement::setResultant(Vect force)
{
	NetForce = force;
}

//Simulation tool-------------------------------------
void MaterialElement::update(double dt) //computes and updates the state of the element at t+dt
{
	Vect a;
	a = getAcceleration();
	updateSpeedandPosition(a, dt);

}

Vect MaterialElement::getAcceleration()
{
	Vect a;
	a.nullify();

	Vect V = NetForce;

	if (Mass != 0)
	{
		a = V / Mass;
	}
	else
	{
		std::cout << "** No mass no accs :-( **" << '\n';
	}

	return a;
}

void MaterialElement::updateSpeedandPosition(Vect a, double dt)
{
	CartesianElement Acceleration = a;
	CartesianElement InitialVelocity = Velocity;

	//double integration of the acceleration gives final position
	Position = Acceleration*0.5*dt*dt + InitialVelocity*dt + Position;

	//integration of the acceleration gives final speeds
	Velocity = InitialVelocity + Acceleration;
}

// ------------------- Material Point ----------------

MaterialPoint::MaterialPoint() {}
MaterialPoint::~MaterialPoint() {}
<commit_msg>external actions used, calculator helper added<commit_after>#include "MaterialElement.h"
#include "Geo.h"
#include "Calculator.h"
#include<vector>
#include <iostream>

//Constructors & destructor-------------------------------
MaterialElement::MaterialElement()
{}

MaterialElement::MaterialElement(Point p, std::vector<Vect> actions, Vect velocity,
	double masse, double charge_)
{
	Charge = charge_; 			// in Coulomb
	Mass = masse;   			// in kg
	Velocity = velocity;		// m/s
	ExternalActions = actions;  //Newton
	Position = p;				// m
}

MaterialElement::~MaterialElement()
{}

//Accessors---------------------------------------------
Point * MaterialElement::pointerToPosition()
{
	Point *pos = NULL;
	pos = &Position;
	return pos;
}

double MaterialElement::getMass()
{
	return Mass;
}

double MaterialElement::getCharge()
{
	return Charge;
}

//Display-----------------------------------------------
void MaterialElement::consoleShow()
{
	Position.show();
	std::cout << "mass: " << Mass << '\n';
	std::cout << "charge: " << Charge << '\n';
}

//Modifier----------------------------------------------
void MaterialElement::place(Point &P)
{
	Position = P;
}

void MaterialElement::place(double x, double y, double z)
{
	Position.place(x, y, z);
}

void MaterialElement::setMass(double m)
{
	Mass = m;
}

void MaterialElement::setCharge(double c)
{
	Charge = c;
}

void MaterialElement::addExternalAction(Vect MechanicalAction)
{
	ExternalActions.push_back(MechanicalAction);
}

//Simulation tool-------------------------------------
void MaterialElement::update(double dt)		//computes and updates the state of the element at t+dt
{
	updateSpeedandPosition(dt);
}

Vect MaterialElement::Acceleration()
{
	Calculator C;
	return C.acceleration(ExternalActions,Mass);
}

void MaterialElement::updateSpeedandPosition(double dt)
{
	Calculator C;
	Position = C.Position(C.acceleration(ExternalActions, Mass), Velocity, Position, dt);
	Velocity = C.Velocity(C.acceleration(ExternalActions, Mass), Velocity, dt);
}

// ------------------- Material Point ----------------

MaterialPoint::MaterialPoint() {}
MaterialPoint::~MaterialPoint() {}
<|endoftext|>


<commit_before>//--------------------------------------------------------------------------------------
// File: SpriteFontTest.cpp
//
// Developer unit test for DirectXTK SpriteFont
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------

#include "SpriteFont.h"
#include "DirectXColors.h"
#include "ScreenGrab.h"

using namespace DirectX;

std::unique_ptr<SpriteBatch> g_spriteBatch;

#pragma warning(push)
#pragma warning(disable : 4005)
#include <wincodec.h>
#pragma warning(pop)

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_CLOSE:
            DestroyWindow(hwnd);
            return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;

        case WM_KEYDOWN:
            switch( wParam )
            {
            case VK_LEFT:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE270 );
                break;

            case VK_RIGHT:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE90 );
                break;

            case VK_UP:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_IDENTITY );
                break;

            case VK_DOWN:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE180 );
                break;

            }
            return 0;

        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
}

int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR, _In_ int nCmdShow )
{
    HRESULT hr;

    wchar_t *const className = L"TestWindowClass";

    WNDCLASSEX wndClass = { 0 };

    wndClass.cbSize = sizeof(WNDCLASSEX);
    wndClass.lpfnWndProc = WndProc;
    wndClass.hInstance = hInstance;
    wndClass.lpszClassName = className;
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);

    RegisterClassEx(&wndClass);

    UINT width = 1024;
    UINT height = 768;

    HWND hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, className, L"Test Window", WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, hInstance, NULL);

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    RECT client;
    GetClientRect(hwnd, &client);

    ID3D11Device* device;
    ID3D11DeviceContext* context;
    IDXGISwapChain* swapChain;
    ID3D11Texture2D* backBufferTexture;
    ID3D11RenderTargetView* backBuffer;
    ID3D11RasterizerState* scissorState;

    DXGI_SWAP_CHAIN_DESC swapChainDesc = { 0 };

    swapChainDesc.BufferCount = 1;
    swapChainDesc.BufferDesc.Width = client.right;
    swapChainDesc.BufferDesc.Height = client.bottom;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_BACK_BUFFER;
    swapChainDesc.OutputWindow = hwnd;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.Windowed = TRUE;

    D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_10_0;

    DWORD d3dFlags = 0;
#ifdef _DEBUG
    d3dFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    if (FAILED(hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, d3dFlags, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, NULL, &context)))
        return 1;

    if (FAILED(hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBufferTexture)))
        return 1;

    D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc = { DXGI_FORMAT_UNKNOWN, D3D11_RTV_DIMENSION_TEXTURE2D };

    if (FAILED(hr = device->CreateRenderTargetView(backBufferTexture, &renderTargetViewDesc, &backBuffer)))
        return 1;

    g_spriteBatch.reset( new SpriteBatch(context) );

    SpriteFont comicFont(device, L"comic.spritefont");
    SpriteFont italicFont(device, L"italic.spritefont");
    SpriteFont scriptFont(device, L"script.spritefont");
    SpriteFont nonproportionalFont(device, L"nonproportional.spritefont");
    SpriteFont multicoloredFont(device, L"multicolored.spritefont");
    SpriteFont japaneseFont(device, L"japanese.spritefont");
    SpriteFont ctrlFont(device, L"xboxController.spritefont");
    SpriteFont consolasFont(device, L"consolas.spritefont");

    comicFont.SetDefaultCharacter('-');

    bool quit = false;

    D3D11_VIEWPORT vp = { 0, 0, (float)client.right, (float)client.bottom, 0, 1 };

    context->RSSetViewports(1, &vp);

    context->OMSetRenderTargets(1, &backBuffer, NULL);

    CD3D11_RASTERIZER_DESC rsDesc(D3D11_FILL_SOLID, D3D11_CULL_BACK, FALSE, 0, 0.f, 0.f, TRUE, TRUE, TRUE, FALSE);
    if (FAILED(device->CreateRasterizerState(&rsDesc, &scissorState)))
        return 1;

    LARGE_INTEGER freq;
    QueryPerformanceFrequency(&freq);

    LARGE_INTEGER start;
    QueryPerformanceCounter(&start);

    size_t frame = 0;

    while (!quit)
    {
        MSG msg;

        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
                quit = true;

            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        LARGE_INTEGER counter;
        QueryPerformanceCounter(&counter);

        float time = 60 * (float)(counter.QuadPart - start.QuadPart) / (float)freq.QuadPart;

        context->ClearRenderTargetView(backBuffer, Colors::CornflowerBlue);

        g_spriteBatch->Begin();

        comicFont.DrawString(g_spriteBatch.get(), L"Hello, world!", XMFLOAT2(0, 0));
        italicFont.DrawString(g_spriteBatch.get(), L"This text is in italics.\nIs it well spaced?", XMFLOAT2(220, 0));
        scriptFont.DrawString(g_spriteBatch.get(), L"Script font, yo...", XMFLOAT2(0, 50));

        SpriteEffects flip = (SpriteEffects)((int)(time / 100) & 3);
        multicoloredFont.DrawString(g_spriteBatch.get(), L"OMG it's full of stars!", XMFLOAT2(610, 130), Colors::White, XM_PIDIV2, XMFLOAT2(0, 0), 1, flip);

        comicFont.DrawString(g_spriteBatch.get(), L"This is a larger block\nof text using a\nfont scaled to a\nsmaller size.\nSome c\x1234ha\x1543rac\x2453te\x1634r\x1563s are not in the font, but should show up as hyphens.", XMFLOAT2(10, 90), Colors::Black, 0, XMFLOAT2(0, 0), 0.5f);

        wchar_t tmp[256];
        swprintf_s(tmp, L"%Iu frames", frame );

        nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(201, 130), Colors::Black);
        nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 131), Colors::Black);
        nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 130), Colors::Red);

        float scale = sin(time / 100) + 1;
        auto spinText = L"Spinning\nlike a cat";
        auto size = comicFont.MeasureString(spinText);
        comicFont.DrawString(g_spriteBatch.get(), spinText, XMVectorSet(150, 350, 0, 0), Colors::Blue, time / 60, size / 2, scale);

        auto mirrorText = L"It's a\nmirror...";
        auto mirrorSize = comicFont.MeasureString(mirrorText);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Black, 0, mirrorSize * XMVectorSet(0, 1, 0, 0), 1, SpriteEffects_None);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(1, 1, 0, 0), 1, SpriteEffects_FlipHorizontally);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(0, 0, 0, 0), 1, SpriteEffects_FlipVertically);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::DarkGray, 0, mirrorSize * XMVectorSet(1, 0, 0, 0), 1, SpriteEffects_FlipBoth);

        japaneseFont.DrawString(g_spriteBatch.get(), L"\x79C1\x306F\x65E5\x672C\x8A9E\x304C\x8A71\x305B\x306A\x3044\x306E\x3067\x3001\n\x79C1\x306F\x3053\x308C\x304C\x4F55\x3092\x610F\x5473\x3059\x308B\x306E\x304B\x308F\x304B\x308A\x307E\x305B\x3093", XMFLOAT2(10, 512));

        {
            char ascii[256] = {0};
            int i = 0;
            for (size_t j = 32; j < 256; ++j)
            {
                if (j == L'\n' || j == L'\r' || j == L'\t')
                    continue;

                if (j > 0 && (j % 128) == 0)
                {
                    ascii[i++] = L'\n';
                    ascii[i++] = L'\n';
                }

                ascii[i++] = static_cast<char>(j + 1);
            }

            wchar_t unicode[256] = { 0 };
            if (!MultiByteToWideChar(437, MB_PRECOMPOSED, ascii, i, unicode, 256))
                wcscpy_s(unicode, L"<ERROR!>\n");

            consolasFont.DrawString(g_spriteBatch.get(), unicode, XMFLOAT2(10, 600), Colors::Cyan);
        }

        ctrlFont.DrawString(g_spriteBatch.get(), L" !\"\n#$%\n&'()\n*+,-", XMFLOAT2(650, 130), Colors::White, 0.f, XMFLOAT2(0.f, 0.f), 0.5f);

        UINT w, h;

        switch( g_spriteBatch->GetRotation() )
        {
        case DXGI_MODE_ROTATION_ROTATE90:
        case DXGI_MODE_ROTATION_ROTATE270:
            w = height;
            h = width;
            break;

        default:
            w = width;
            h = height;
            break;
        }

        for( UINT x = 0; x < w; x += 100 )
        {
            swprintf_s( tmp, L"%u\n", x );
            nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float(x), float( h - 100 ) ), Colors::Yellow );
        }

        for( UINT y = 0; y < h; y += 100 )
        {
            swprintf_s( tmp, L"%u\n", y );
            nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float( w - 100 ), float(y) ), Colors::Red );
        }

        g_spriteBatch->End();

        g_spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, scissorState, [&]()
        {
            CD3D11_RECT r(640, 20, 740, 38);
            context->RSSetScissorRects(1, &r);
        });

        comicFont.DrawString(g_spriteBatch.get(), L"Clipping!", XMFLOAT2(640, 0), Colors::DarkGreen);

        g_spriteBatch->End();

        swapChain->Present(1, 0);
        ++frame;

        if ( frame == 10 )
        {
            ID3D11Texture2D* backBufferTex = nullptr;
            hr = swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&backBufferTex);
            if ( SUCCEEDED(hr) )
            {
                hr = SaveWICTextureToFile( context, backBufferTex, GUID_ContainerFormatBmp, L"SCREENSHOT.BMP" );
                hr = SaveDDSTextureToFile( context, backBufferTex, L"SCREENSHOT.DDS" );
                backBufferTex->Release();
            }
        }
    }

    g_spriteBatch.reset();

    scissorState->Release();
    backBuffer->Release();
    backBufferTexture->Release();
    swapChain->Release();
    context->Release();
    device->Release();

    return 0;
}
<commit_msg>Updated SpriteFontTest<commit_after>//--------------------------------------------------------------------------------------
// File: SpriteFontTest.cpp
//
// Developer unit test for DirectXTK SpriteFont
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------

#include "SpriteFont.h"
#include "DirectXColors.h"
#include "ScreenGrab.h"

#include <wrl/client.h>
using Microsoft::WRL::ComPtr;

using namespace DirectX;

std::unique_ptr<SpriteBatch> g_spriteBatch;

#pragma warning(push)
#pragma warning(disable : 4005)
#include <wincodec.h>
#pragma warning(pop)

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_CLOSE:
            DestroyWindow(hwnd);
            return 0;

        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;

        case WM_KEYDOWN:
            switch( wParam )
            {
            case VK_LEFT:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE270 );
                break;

            case VK_RIGHT:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE90 );
                break;

            case VK_UP:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_IDENTITY );
                break;

            case VK_DOWN:
                if ( g_spriteBatch )
                    g_spriteBatch->SetRotation( DXGI_MODE_ROTATION_ROTATE180 );
                break;

            }
            return 0;

        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
}

int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE, _In_ LPWSTR, _In_ int nCmdShow )
{
    HRESULT hr;

    wchar_t *const className = L"TestWindowClass";

    WNDCLASSEX wndClass = { 0 };

    wndClass.cbSize = sizeof(WNDCLASSEX);
    wndClass.lpfnWndProc = WndProc;
    wndClass.hInstance = hInstance;
    wndClass.lpszClassName = className;
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);

    RegisterClassEx(&wndClass);

    UINT width = 1024;
    UINT height = 768;

    HWND hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, className, L"Test Window", WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, hInstance, NULL);

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    RECT client;
    GetClientRect(hwnd, &client);

    ComPtr<ID3D11Device> device;
    ComPtr<ID3D11DeviceContext> context;
    ComPtr<IDXGISwapChain> swapChain;
    ComPtr<ID3D11Texture2D> backBufferTexture;
    ComPtr<ID3D11RenderTargetView> backBuffer;
    ComPtr<ID3D11RasterizerState> scissorState;

    DXGI_SWAP_CHAIN_DESC swapChainDesc = { 0 };

    swapChainDesc.BufferCount = 1;
    swapChainDesc.BufferDesc.Width = client.right;
    swapChainDesc.BufferDesc.Height = client.bottom;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_BACK_BUFFER;
    swapChainDesc.OutputWindow = hwnd;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.Windowed = TRUE;

    D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_10_0;

    DWORD d3dFlags = 0;
#ifdef _DEBUG
    d3dFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    if (FAILED(hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, d3dFlags, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &swapChain, &device, NULL, &context)))
        return 1;

    if (FAILED(hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&backBufferTexture)))
        return 1;

    D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc = { DXGI_FORMAT_UNKNOWN, D3D11_RTV_DIMENSION_TEXTURE2D };

    if (FAILED(hr = device->CreateRenderTargetView(backBufferTexture.Get(), &renderTargetViewDesc, &backBuffer)))
        return 1;

    g_spriteBatch.reset( new SpriteBatch(context.Get()) );

    SpriteFont comicFont(device.Get(), L"comic.spritefont");
    SpriteFont italicFont(device.Get(), L"italic.spritefont");
    SpriteFont scriptFont(device.Get(), L"script.spritefont");
    SpriteFont nonproportionalFont(device.Get(), L"nonproportional.spritefont");
    SpriteFont multicoloredFont(device.Get(), L"multicolored.spritefont");
    SpriteFont japaneseFont(device.Get(), L"japanese.spritefont");
    SpriteFont ctrlFont(device.Get(), L"xboxController.spritefont");
    SpriteFont consolasFont(device.Get(), L"consolas.spritefont");

    if ( comicFont.GetDefaultCharacter() != 0 )
    {
        MessageBox( hwnd, L"GetDefaultCharacter failed", L"SpriteFontTest", MB_OK | MB_ICONERROR );
    }

    // ContainsCharacter tests
    if ( comicFont.ContainsCharacter( 27 )
         || !comicFont.ContainsCharacter( '-' ) )
    {
        MessageBox( hwnd, L"ContainsCharacter failed", L"SpriteFontTest", MB_OK | MB_ICONERROR );
    }

    // FindGlyph/GetSpriteSheet tests
    {
        auto g = comicFont.FindGlyph( '-' );
        if ( g->Character != '-' || g->XOffset != 6 || g->YOffset != 24 )
        {
            MessageBox( hwnd, L"FindGlyph failed", L"SpriteFontTest", MB_OK | MB_ICONERROR );
        }

        ComPtr<ID3D11ShaderResourceView> sheet;
        comicFont.GetSpriteSheet( sheet.GetAddressOf() );
        if ( !sheet )
        {
            MessageBox( hwnd, L"GetSpriteSheet failed", L"SpriteFontTest", MB_OK | MB_ICONERROR );
        }
    }

    // DefaultCharacter tests
    comicFont.SetDefaultCharacter('-');
    if ( comicFont.GetDefaultCharacter() != '-' )
    {
        MessageBox( hwnd, L"Get/SetDefaultCharacter failed", L"SpriteFontTest", MB_OK | MB_ICONERROR );
    }

    // Linespacing tests
    float s=ctrlFont.GetLineSpacing();
    if ( s != 186.f )
    {
        MessageBox( hwnd, L"GetLineSpacing failed", L"SpriteFontTest", MB_OK | MB_ICONERROR );
    }
    ctrlFont.SetLineSpacing(256.f);
    s=ctrlFont.GetLineSpacing();
    if ( s != 256.f )
    {
        MessageBox( hwnd, L"Get/SetLineSpacing failed", L"SpriteFontTest", MB_OK | MB_ICONERROR );
    }
    ctrlFont.SetLineSpacing(186.f);

    bool quit = false;

    D3D11_VIEWPORT vp = { 0, 0, (float)client.right, (float)client.bottom, 0, 1 };

    context->RSSetViewports(1, &vp);

    context->OMSetRenderTargets(1, backBuffer.GetAddressOf(), NULL);

    CD3D11_RASTERIZER_DESC rsDesc(D3D11_FILL_SOLID, D3D11_CULL_BACK, FALSE, 0, 0.f, 0.f, TRUE, TRUE, TRUE, FALSE);
    if (FAILED(device->CreateRasterizerState(&rsDesc, &scissorState)))
        return 1;

    LARGE_INTEGER freq;
    QueryPerformanceFrequency(&freq);

    LARGE_INTEGER start;
    QueryPerformanceCounter(&start);

    size_t frame = 0;

    while (!quit)
    {
        MSG msg;

        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
                quit = true;

            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        LARGE_INTEGER counter;
        QueryPerformanceCounter(&counter);

        float time = 60 * (float)(counter.QuadPart - start.QuadPart) / (float)freq.QuadPart;

        context->ClearRenderTargetView(backBuffer.Get(), Colors::CornflowerBlue);

        g_spriteBatch->Begin();

        comicFont.DrawString(g_spriteBatch.get(), L"Hello, world!", XMFLOAT2(0, 0));
        italicFont.DrawString(g_spriteBatch.get(), L"This text is in italics.\nIs it well spaced?", XMFLOAT2(220, 0));
        scriptFont.DrawString(g_spriteBatch.get(), L"Script font, yo...", XMFLOAT2(0, 50));

        SpriteEffects flip = (SpriteEffects)((int)(time / 100) & 3);
        multicoloredFont.DrawString(g_spriteBatch.get(), L"OMG it's full of stars!", XMFLOAT2(610, 130), Colors::White, XM_PIDIV2, XMFLOAT2(0, 0), 1, flip);

        comicFont.DrawString(g_spriteBatch.get(), L"This is a larger block\nof text using a\nfont scaled to a\nsmaller size.\nSome c\x1234ha\x1543rac\x2453te\x1634r\x1563s are not in the font, but should show up as hyphens.", XMFLOAT2(10, 90), Colors::Black, 0, XMFLOAT2(0, 0), 0.5f);

        wchar_t tmp[256];
        swprintf_s(tmp, L"%Iu frames", frame );

        nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(201, 130), Colors::Black);
        nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 131), Colors::Black);
        nonproportionalFont.DrawString(g_spriteBatch.get(), tmp, XMFLOAT2(200, 130), Colors::Red);

        float scale = sin(time / 100) + 1;
        auto spinText = L"Spinning\nlike a cat";
        auto size = comicFont.MeasureString(spinText);
        comicFont.DrawString(g_spriteBatch.get(), spinText, XMVectorSet(150, 350, 0, 0), Colors::Blue, time / 60, size / 2, scale);

        auto mirrorText = L"It's a\nmirror...";
        auto mirrorSize = comicFont.MeasureString(mirrorText);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Black, 0, mirrorSize * XMVectorSet(0, 1, 0, 0), 1, SpriteEffects_None);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(1, 1, 0, 0), 1, SpriteEffects_FlipHorizontally);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::Gray, 0, mirrorSize * XMVectorSet(0, 0, 0, 0), 1, SpriteEffects_FlipVertically);
        comicFont.DrawString(g_spriteBatch.get(), mirrorText, XMVectorSet(400, 400, 0, 0), Colors::DarkGray, 0, mirrorSize * XMVectorSet(1, 0, 0, 0), 1, SpriteEffects_FlipBoth);

        japaneseFont.DrawString(g_spriteBatch.get(), L"\x79C1\x306F\x65E5\x672C\x8A9E\x304C\x8A71\x305B\x306A\x3044\x306E\x3067\x3001\n\x79C1\x306F\x3053\x308C\x304C\x4F55\x3092\x610F\x5473\x3059\x308B\x306E\x304B\x308F\x304B\x308A\x307E\x305B\x3093", XMFLOAT2(10, 512));

        {
            char ascii[256] = {0};
            int i = 0;
            for (size_t j = 32; j < 256; ++j)
            {
                if (j == L'\n' || j == L'\r' || j == L'\t')
                    continue;

                if (j > 0 && (j % 128) == 0)
                {
                    ascii[i++] = L'\n';
                    ascii[i++] = L'\n';
                }

                ascii[i++] = static_cast<char>(j + 1);
            }

            wchar_t unicode[256] = { 0 };
            if (!MultiByteToWideChar(437, MB_PRECOMPOSED, ascii, i, unicode, 256))
                wcscpy_s(unicode, L"<ERROR!>\n");

            consolasFont.DrawString(g_spriteBatch.get(), unicode, XMFLOAT2(10, 600), Colors::Cyan);
        }

        ctrlFont.DrawString(g_spriteBatch.get(), L" !\"\n#$%\n&'()\n*+,-", XMFLOAT2(650, 130), Colors::White, 0.f, XMFLOAT2(0.f, 0.f), 0.5f);

        UINT w, h;

        switch( g_spriteBatch->GetRotation() )
        {
        case DXGI_MODE_ROTATION_ROTATE90:
        case DXGI_MODE_ROTATION_ROTATE270:
            w = height;
            h = width;
            break;

        default:
            w = width;
            h = height;
            break;
        }

        for( UINT x = 0; x < w; x += 100 )
        {
            swprintf_s( tmp, L"%u\n", x );
            nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float(x), float( h - 100 ) ), Colors::Yellow );
        }

        for( UINT y = 0; y < h; y += 100 )
        {
            swprintf_s( tmp, L"%u\n", y );
            nonproportionalFont.DrawString( g_spriteBatch.get(), tmp, XMFLOAT2( float( w - 100 ), float(y) ), Colors::Red );
        }

        g_spriteBatch->End();

        g_spriteBatch->Begin(SpriteSortMode_Deferred, nullptr, nullptr, nullptr, scissorState.Get(), [&]()
        {
            CD3D11_RECT r(640, 20, 740, 38);
            context->RSSetScissorRects(1, &r);
        });

        comicFont.DrawString(g_spriteBatch.get(), L"Clipping!", XMFLOAT2(640, 0), Colors::DarkGreen);

        g_spriteBatch->End();

        swapChain->Present(1, 0);
        ++frame;

        if ( frame == 10 )
        {
            ComPtr<ID3D11Texture2D> backBufferTex;
            hr = swapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&backBufferTex);
            if ( SUCCEEDED(hr) )
            {
                hr = SaveWICTextureToFile( context.Get(), backBufferTex.Get(), GUID_ContainerFormatBmp, L"SCREENSHOT.BMP" );
                hr = SaveDDSTextureToFile( context.Get(), backBufferTex.Get(), L"SCREENSHOT.DDS" );
            }
        }
    }

    g_spriteBatch.reset();

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

//
//
// C++ Implementation: $MODULE$
//
// Description:
//
//
// Author: sven <sven@ares>, (C) 2003
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "copasi.h"

#include "CMetabNameInterface.h"
#include "CModel.h"
#include "CChemEqParser.h"

#include "report/CCopasiContainer.h"
#include "report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"

CMetabNameInterface::~CMetabNameInterface()
{}

std::string CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key, const bool & quoted)
{
  CMetab * metab = dynamic_cast< CMetab * >(CCopasiRootContainer::getKeyFactory()->get(key));

  if (metab)
    return getDisplayName(model, *metab, quoted);
  else
    return "";
}

std::string CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab, const bool & quoted)
{
  return getDisplayName(model, metab.getObjectName(), metab.getCompartment()->getObjectName(), quoted);
}

std::string CMetabNameInterface::getDisplayName(const CModel* model,
    const std::string & metabolite,
    const std::string & compartment,
    const bool & quoted)
{
  std::string DefaultCompartment;

  if (model->getCompartments().size() == 0)
    DefaultCompartment = "compartment";
  else
    DefaultCompartment = model->getCompartments()[0]->getObjectName();

  std::string Metabolite = quoted ? quote(metabolite, "{}") : metabolite;

  if (quoted && isNumber(Metabolite))
    Metabolite = "\"" + Metabolite + "\"";

  if ((CMetabNameInterface::doesExist(model, metabolite, compartment) &&
       CMetabNameInterface::isUnique(model, metabolite)) ||
      (!CMetabNameInterface::doesExist(model, metabolite, "") &&
       compartment == DefaultCompartment))
    return Metabolite;

  std::string Compartment = quoted ? quote(compartment, "{}") : compartment;

  if (quoted && isNumber(Compartment))
    Compartment = "\"" + Compartment + "\"";

  return Metabolite + '{' + Compartment + '}';
}

std::string CMetabNameInterface::getMetaboliteKey(const CModel* model,
    const std::string & metabolite,
    const std::string & compartment)
{
  CMetab * metab = getMetabolite(model, metabolite, compartment);

  if (metab)
    return metab->getKey();
  else
    return "";
}

CMetab * CMetabNameInterface::getMetabolite(const CModel* model,
    const std::string & metabolite,
    const std::string & compartment)
{
  size_t Index;

  if (compartment != "")
    {
      Index = model->getCompartments().getIndex(compartment);

      if (Index != C_INVALID_INDEX)
        {
          CCompartment *pCompartment = model->getCompartments()[Index];

          Index = pCompartment->getMetabolites().getIndex(metabolite);

          if (Index != C_INVALID_INDEX)
            return pCompartment->getMetabolites()[Index];
        }

      return NULL;
    }

  Index = model->findMetabByName(metabolite);

  if (Index != C_INVALID_INDEX)
    return model->getMetabolites()[Index];

  return NULL;
}

bool CMetabNameInterface::isUnique(const CModel* model, const std::string & name)
{
  bool unique = true;
  size_t i;
  const CCopasiVector< CMetab > & metabs = model->getMetabolites();
  std::string metabName;

  for (i = 0; i < metabs.size(); i++)
    {
      metabName = metabs[i]->getObjectName();

      if (metabName == name)
        {
          if (unique)
            unique = false;
          else
            return false; //return true
        }
    }

  return true; //return unique;
}

bool CMetabNameInterface::doesExist(const CModel* model,
                                    const std::string & metabolite,
                                    const std::string & compartment)
{
  if (compartment != "")
    {
      size_t Index = model->getCompartments().getIndex(compartment);

      if (Index == C_INVALID_INDEX) return false;

      Index = model->getCompartments()[Index]->getMetabolites().getIndex(metabolite);

      return (Index != C_INVALID_INDEX);
    }
  else
    return (model->findMetabByName(metabolite) != C_INVALID_INDEX);
}

// static
std::pair< std::string, std::string > CMetabNameInterface::splitDisplayName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(quote(name) + " ->");

  CChemEqParser Parser(&buffer);

  std::pair< std::string, std::string > Result;

  if (Parser.yyparse() != 0)
    {
      Result.first = "";
      Result.second = "";
    }
  else
    {
      Result.first = Parser.getSubstrateNames()[0];
      Result.second = Parser.getSubstrateCompartments()[0];
    }

  return Result;
}

// static
std::string CMetabNameInterface::unQuote(const std::string & displayName)
{
  // parse the description into a linked node tree
  std::stringstream buffer(displayName + " ->");

  CChemEqParser Parser(&buffer);

  std::pair< std::string, std::string > Names;

  if (Parser.yyparse() != 0)
    {
      Names.first = "";
      Names.second = "";
    }
  else
    {
      Names.first = Parser.getSubstrateNames()[0];
      Names.second = Parser.getSubstrateCompartments()[0];
    }

  std::string Name = Names.first;

  if (Names.second != "")
    {
      Name += "{" + Names.second + "}";
    }

  return Name;
}

#ifdef XXXX
std::string CMetabNameInterface::extractCompartmentName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(name);
  buffer << " ->";

  CChemEqParser Parser(&buffer);

  if (Parser.yyparse() != 0) return "";

  return Parser.getSubstrateCompartments()[0];
}

std::string CMetabNameInterface::extractMetabName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(name);
  buffer << " ->";

  CChemEqParser Parser(&buffer);

  if (Parser.yyparse() != 0) return "";

  return Parser.getSubstrateNames()[0];
}

bool CMetabNameInterface::isValidMetabDisplayName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(name);
  buffer << " ->";

  CChemEqParser Parser(&buffer);

  return (Parser.yyparse() == 0);
}
#endif // XXXX
<commit_msg>Fixed problem occurring when unquoting a metabolite name which requires quotes has already been unquoted before.<commit_after>// Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

// Copyright (C) 2003 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

//
//
// C++ Implementation: $MODULE$
//
// Description:
//
//
// Author: sven <sven@ares>, (C) 2003
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "copasi.h"

#include "CMetabNameInterface.h"
#include "CModel.h"
#include "CChemEqParser.h"

#include "report/CCopasiContainer.h"
#include "report/CKeyFactory.h"
#include "copasi/report/CCopasiRootContainer.h"

CMetabNameInterface::~CMetabNameInterface()
{}

std::string CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key, const bool & quoted)
{
  CMetab * metab = dynamic_cast< CMetab * >(CCopasiRootContainer::getKeyFactory()->get(key));

  if (metab)
    return getDisplayName(model, *metab, quoted);
  else
    return "";
}

std::string CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab, const bool & quoted)
{
  return getDisplayName(model, metab.getObjectName(), metab.getCompartment()->getObjectName(), quoted);
}

std::string CMetabNameInterface::getDisplayName(const CModel* model,
    const std::string & metabolite,
    const std::string & compartment,
    const bool & quoted)
{
  std::string DefaultCompartment;

  if (model->getCompartments().size() == 0)
    DefaultCompartment = "compartment";
  else
    DefaultCompartment = model->getCompartments()[0]->getObjectName();

  std::string Metabolite = quoted ? quote(metabolite, "{}") : metabolite;

  if (quoted && isNumber(Metabolite))
    Metabolite = "\"" + Metabolite + "\"";

  if ((CMetabNameInterface::doesExist(model, metabolite, compartment) &&
       CMetabNameInterface::isUnique(model, metabolite)) ||
      (!CMetabNameInterface::doesExist(model, metabolite, "") &&
       compartment == DefaultCompartment))
    return Metabolite;

  std::string Compartment = quoted ? quote(compartment, "{}") : compartment;

  if (quoted && isNumber(Compartment))
    Compartment = "\"" + Compartment + "\"";

  return Metabolite + '{' + Compartment + '}';
}

std::string CMetabNameInterface::getMetaboliteKey(const CModel* model,
    const std::string & metabolite,
    const std::string & compartment)
{
  CMetab * metab = getMetabolite(model, metabolite, compartment);

  if (metab)
    return metab->getKey();
  else
    return "";
}

CMetab * CMetabNameInterface::getMetabolite(const CModel* model,
    const std::string & metabolite,
    const std::string & compartment)
{
  size_t Index;

  if (compartment != "")
    {
      Index = model->getCompartments().getIndex(compartment);

      if (Index != C_INVALID_INDEX)
        {
          CCompartment *pCompartment = model->getCompartments()[Index];

          Index = pCompartment->getMetabolites().getIndex(metabolite);

          if (Index != C_INVALID_INDEX)
            return pCompartment->getMetabolites()[Index];
        }

      return NULL;
    }

  Index = model->findMetabByName(metabolite);

  if (Index != C_INVALID_INDEX)
    return model->getMetabolites()[Index];

  return NULL;
}

bool CMetabNameInterface::isUnique(const CModel* model, const std::string & name)
{
  bool unique = true;
  size_t i;
  const CCopasiVector< CMetab > & metabs = model->getMetabolites();
  std::string metabName;

  for (i = 0; i < metabs.size(); i++)
    {
      metabName = metabs[i]->getObjectName();

      if (metabName == name)
        {
          if (unique)
            unique = false;
          else
            return false; //return true
        }
    }

  return true; //return unique;
}

bool CMetabNameInterface::doesExist(const CModel* model,
                                    const std::string & metabolite,
                                    const std::string & compartment)
{
  if (compartment != "")
    {
      size_t Index = model->getCompartments().getIndex(compartment);

      if (Index == C_INVALID_INDEX) return false;

      Index = model->getCompartments()[Index]->getMetabolites().getIndex(metabolite);

      return (Index != C_INVALID_INDEX);
    }
  else
    return (model->findMetabByName(metabolite) != C_INVALID_INDEX);
}

// static
std::pair< std::string, std::string > CMetabNameInterface::splitDisplayName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(quote(name) + " ->");

  CChemEqParser Parser(&buffer);

  std::pair< std::string, std::string > Result;

  if (Parser.yyparse() != 0)
    {
      Result.first = "";
      Result.second = "";
    }
  else
    {
      Result.first = Parser.getSubstrateNames()[0];
      Result.second = Parser.getSubstrateCompartments()[0];
    }

  return Result;
}

// static
std::string CMetabNameInterface::unQuote(const std::string & displayName)
{
  // parse the description into a linked node tree
  std::stringstream buffer(displayName + " ->");

  CChemEqParser Parser(&buffer);

  std::pair< std::string, std::string > Names;

  if (Parser.yyparse() != 0)
    {
      Names.first = displayName;
      Names.second = "";
    }
  else
    {
      Names.first = Parser.getSubstrateNames()[0];
      Names.second = Parser.getSubstrateCompartments()[0];
    }

  std::string Name = Names.first;

  if (Names.second != "")
    {
      Name += "{" + Names.second + "}";
    }

  return Name;
}

#ifdef XXXX
std::string CMetabNameInterface::extractCompartmentName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(name);
  buffer << " ->";

  CChemEqParser Parser(&buffer);

  if (Parser.yyparse() != 0) return "";

  return Parser.getSubstrateCompartments()[0];
}

std::string CMetabNameInterface::extractMetabName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(name);
  buffer << " ->";

  CChemEqParser Parser(&buffer);

  if (Parser.yyparse() != 0) return "";

  return Parser.getSubstrateNames()[0];
}

bool CMetabNameInterface::isValidMetabDisplayName(const std::string & name)
{
  // parse the description into a linked node tree
  std::stringstream buffer(name);
  buffer << " ->";

  CChemEqParser Parser(&buffer);

  return (Parser.yyparse() == 0);
}
#endif // XXXX
<|endoftext|>


<commit_before>#include "include/vkalloc.h"

#include <vector>
#include <unordered_map>

namespace vka {
    struct Page {
        VkDeviceMemory deviceMemory = VK_NULL_HANDLE;
        Node* head = nullptr;
    };

    struct Node {
        Node* next = nullptr;
        uint64_t offset = 0;
        uint64_t size = 0;
    };

    struct PageMapping {
        uint32_t heapIndex;
        uint32_t pageIndex;
    };

    VkPhysicalDevice physicalDevice;
    VkDevice device;
    VkPhysicalDeviceMemoryProperties properties;
    VkAllocationCallbacks* callbacks;
    std::unordered_map<VkDeviceMemory, PageMapping> pageMap;    //caches index into one of the vector<Page> heaps
    std::vector<Page> heaps[32];    //32 possible heaps
}

void vkaInit(VkPhysicalDevice physicalDevice, VkDevice device, VkAllocationCallbacks* allocator){
    vka::physicalDevice = physicalDevice;
    vka::device = device;
    vka::callbacks = allocator;

    vkGetPhysicalDeviceMemoryProperties(physicalDevice, &vka::properties);
}

using namespace vka;
static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements);
static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements);
static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements);
static void Split(Node* current, Node** last, uint64_t start, uint64_t size);
static void Free(VkAllocation allocation, Page& page);
static void Merge(VkAllocation allocation, Node* current);

void vkaTerminate(){
    pageMap.clear();

    for (size_t i = 0; i < 32; i++) {
        for (size_t j = 0; j < heaps[i].size(); j++) {
            Node* current = heaps[i][j].head;

            while (current){
                Node* next = current->next;
                delete current;
                current = next;
            }
        }

        heaps[i].clear();
    }
}

VkAllocation vkAllocFlag(VkMemoryRequirements requirements, VkMemoryPropertyFlags flags) {
    for (size_t i = 0; i < properties.memoryTypeCount; i++) {
        if ((requirements.memoryTypeBits & (1 << i))
            && properties.memoryTypes[i].propertyFlags == flags) {
            std::vector<Page> &heap = heaps[i];

            VkAllocation result = AttemptAlloc(heap, i, requirements);
            if (result.deviceMemory != VK_NULL_HANDLE) {
                return result;
            }
        }
    }

    return {};
}

void vkFree(VkAllocation allocation){
    if (allocation.deviceMemory == VK_NULL_HANDLE) return;

    PageMapping& mapping = pageMap[allocation.deviceMemory];
    Page& page = heaps[mapping.heapIndex][mapping.pageIndex];

    Free(allocation, page);
}

VkAllocation vkAlloc(VkMemoryRequirements requirements){
    return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}

VkAllocation vkAllocHost(VkMemoryRequirements requirements){
    return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
}

static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) {
    //attempt to allocate from existing pages
    for (size_t i = 0; i < heap.size(); i++) {
        Page& page = heap[i];

        VkAllocation result = AttemptAlloc(page, requirements);
        if (result.deviceMemory != VK_NULL_HANDLE) {
            return result;
        }
    }

    //attempt to allocate from new page
    Page* newPage = AllocNewPage(heap, heapIndex, requirements);
    if (newPage) {
        VkAllocation result = AttemptAlloc(*newPage, requirements);
        if (result.deviceMemory != VK_NULL_HANDLE) {
            return result;
        }
    }

    //give up
    return {};
}

static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements) {
    Node* current = page.head;
    Node** last = &page.head;

    while (current) {
        uint64_t start = current->offset;
        uint64_t available = current->size;

        uint64_t unalign = (start % requirements.alignment);
        uint64_t align;

        if (unalign == 0) {
            align = 0;
        } else {
            align = requirements.alignment - unalign;
        }

        start += align;
        available -= align;

        if (available >= requirements.size) {
            Split(current, last, start, requirements.size);
            return {page.deviceMemory, start, requirements.size};
        }

        last = &(current->next);
        current = current->next;
    }

    return {};
}

static void Split(Node* current, Node** last, uint64_t start, uint64_t size) {
    uint64_t startSpace = start - current->offset;
    uint64_t endSpace = current->size - (start + size);

    if (startSpace == 0 && endSpace == 0) {
        *last = current->next;
        delete current;
    } else if (startSpace == 0 && endSpace > 0) {
        current->offset = start + size;
        current->size = endSpace;
    } else if (startSpace > 0 && endSpace == 0) {
        current->size = startSpace;
    } else {    //startSpace > 0 && endSpace > 0
        Node* newNode = new Node;
        newNode->next = current->next;
        newNode->offset = start + size;
        newNode->size = endSpace;

        current->next = newNode;
        current->size = startSpace;
    }
}

static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) {
    uint64_t allocSize = VKA_ALLOC_SIZE;
    if (requirements.size > allocSize) {
        allocSize = requirements.size;
    }

    VkMemoryAllocateInfo info = {};
    info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
    info.allocationSize = allocSize;
    info.memoryTypeIndex = heapIndex;

    VkDeviceMemory memory;
    VkResult result = vkAllocateMemory(device, &info, callbacks, &memory);

    if (result == VK_SUCCESS){
        Page page = {};
        page.deviceMemory = memory;

        Node* node = new Node;
        node->size = allocSize;

        page.head = node;

        heap.emplace_back(page);

        pageMap[memory] = {heapIndex, static_cast<uint32_t>(heap.size() - 1)};

        return &(heap[heap.size() - 1]);
    } else {
        //TODO: add way for user to check the error
        return nullptr;
    }
}

static void Free(VkAllocation allocation, Page& page) {
    Node* current = page.head;

    while (current) {
        if (allocation.offset > current->offset && allocation.offset < current->next->offset) {
            Merge(allocation, current);
            return;
        }
    }
}

static void Merge(VkAllocation allocation, Node* current) {
    if (allocation.offset == current->offset + current->size) {
        current->size += allocation.size;
    } else {
        Node* newNode = new Node;
        newNode->next = current->next,
        newNode->offset = allocation.offset,
        newNode->size = allocation.size;

        current = newNode;
    }

    Node* next = current->next;
    if (next->offset == current->offset + current->size) {
        current->size += next->size;
        current->next = next->next;
        delete next;
    }
}<commit_msg>Remove vka::physicalDevice<commit_after>#include "include/vkalloc.h"

#include <vector>
#include <unordered_map>

namespace vka {
    struct Page {
        VkDeviceMemory deviceMemory = VK_NULL_HANDLE;
        Node* head = nullptr;
    };

    struct Node {
        Node* next = nullptr;
        uint64_t offset = 0;
        uint64_t size = 0;
    };

    struct PageMapping {
        uint32_t heapIndex;
        uint32_t pageIndex;
    };

    VkDevice device;
    VkPhysicalDeviceMemoryProperties properties;
    VkAllocationCallbacks* callbacks;
    std::unordered_map<VkDeviceMemory, PageMapping> pageMap;    //caches index into one of the vector<Page> heaps
    std::vector<Page> heaps[32];    //32 possible heaps
}

void vkaInit(VkPhysicalDevice physicalDevice, VkDevice device, VkAllocationCallbacks* allocator){
    vka::device = device;
    vka::callbacks = allocator;

    vkGetPhysicalDeviceMemoryProperties(physicalDevice, &vka::properties);
}

using namespace vka;
static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements);
static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements);
static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements);
static void Split(Node* current, Node** last, uint64_t start, uint64_t size);
static void Free(VkAllocation allocation, Page& page);
static void Merge(VkAllocation allocation, Node* current);

void vkaTerminate(){
    pageMap.clear();

    for (size_t i = 0; i < 32; i++) {
        for (size_t j = 0; j < heaps[i].size(); j++) {
            Node* current = heaps[i][j].head;

            while (current){
                Node* next = current->next;
                delete current;
                current = next;
            }
        }

        heaps[i].clear();
    }
}

VkAllocation vkAllocFlag(VkMemoryRequirements requirements, VkMemoryPropertyFlags flags) {
    for (size_t i = 0; i < properties.memoryTypeCount; i++) {
        if ((requirements.memoryTypeBits & (1 << i))
            && properties.memoryTypes[i].propertyFlags == flags) {
            std::vector<Page> &heap = heaps[i];

            VkAllocation result = AttemptAlloc(heap, i, requirements);
            if (result.deviceMemory != VK_NULL_HANDLE) {
                return result;
            }
        }
    }

    return {};
}

void vkFree(VkAllocation allocation){
    if (allocation.deviceMemory == VK_NULL_HANDLE) return;

    PageMapping& mapping = pageMap[allocation.deviceMemory];
    Page& page = heaps[mapping.heapIndex][mapping.pageIndex];

    Free(allocation, page);
}

VkAllocation vkAlloc(VkMemoryRequirements requirements){
    return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}

VkAllocation vkAllocHost(VkMemoryRequirements requirements){
    return vkAllocFlag(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
}

static VkAllocation AttemptAlloc(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) {
    //attempt to allocate from existing pages
    for (size_t i = 0; i < heap.size(); i++) {
        Page& page = heap[i];

        VkAllocation result = AttemptAlloc(page, requirements);
        if (result.deviceMemory != VK_NULL_HANDLE) {
            return result;
        }
    }

    //attempt to allocate from new page
    Page* newPage = AllocNewPage(heap, heapIndex, requirements);
    if (newPage) {
        VkAllocation result = AttemptAlloc(*newPage, requirements);
        if (result.deviceMemory != VK_NULL_HANDLE) {
            return result;
        }
    }

    //give up
    return {};
}

static VkAllocation AttemptAlloc(Page& page, VkMemoryRequirements requirements) {
    Node* current = page.head;
    Node** last = &page.head;

    while (current) {
        uint64_t start = current->offset;
        uint64_t available = current->size;

        uint64_t unalign = (start % requirements.alignment);
        uint64_t align;

        if (unalign == 0) {
            align = 0;
        } else {
            align = requirements.alignment - unalign;
        }

        start += align;
        available -= align;

        if (available >= requirements.size) {
            Split(current, last, start, requirements.size);
            return {page.deviceMemory, start, requirements.size};
        }

        last = &(current->next);
        current = current->next;
    }

    return {};
}

static void Split(Node* current, Node** last, uint64_t start, uint64_t size) {
    uint64_t startSpace = start - current->offset;
    uint64_t endSpace = current->size - (start + size);

    if (startSpace == 0 && endSpace == 0) {
        *last = current->next;
        delete current;
    } else if (startSpace == 0 && endSpace > 0) {
        current->offset = start + size;
        current->size = endSpace;
    } else if (startSpace > 0 && endSpace == 0) {
        current->size = startSpace;
    } else {    //startSpace > 0 && endSpace > 0
        Node* newNode = new Node;
        newNode->next = current->next;
        newNode->offset = start + size;
        newNode->size = endSpace;

        current->next = newNode;
        current->size = startSpace;
    }
}

static Page* AllocNewPage(std::vector<Page>& heap, uint32_t heapIndex, VkMemoryRequirements requirements) {
    uint64_t allocSize = VKA_ALLOC_SIZE;
    if (requirements.size > allocSize) {
        allocSize = requirements.size;
    }

    VkMemoryAllocateInfo info = {};
    info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
    info.allocationSize = allocSize;
    info.memoryTypeIndex = heapIndex;

    VkDeviceMemory memory;
    VkResult result = vkAllocateMemory(device, &info, callbacks, &memory);

    if (result == VK_SUCCESS){
        Page page = {};
        page.deviceMemory = memory;

        Node* node = new Node;
        node->size = allocSize;

        page.head = node;

        heap.emplace_back(page);

        pageMap[memory] = {heapIndex, static_cast<uint32_t>(heap.size() - 1)};

        return &(heap[heap.size() - 1]);
    } else {
        //TODO: add way for user to check the error
        return nullptr;
    }
}

static void Free(VkAllocation allocation, Page& page) {
    Node* current = page.head;

    while (current) {
        if (allocation.offset > current->offset && allocation.offset < current->next->offset) {
            Merge(allocation, current);
            return;
        }
    }
}

static void Merge(VkAllocation allocation, Node* current) {
    if (allocation.offset == current->offset + current->size) {
        current->size += allocation.size;
    } else {
        Node* newNode = new Node;
        newNode->next = current->next,
        newNode->offset = allocation.offset,
        newNode->size = allocation.size;

        current = newNode;
    }

    Node* next = current->next;
    if (next->offset == current->offset + current->size) {
        current->size += next->size;
        current->next = next->next;
        delete next;
    }
}<|endoftext|>


<commit_before>/*
 *	Written by   : BinHong Lee
 *	Last edited  : 5/12/2016
 */

#include <iostream>
#include <string>
#include <stack>
#include <fstream>
#include "Person.cpp"
using namespace std;

//Declaration of functions
void getUser(string);
void login();
void adminLogin();
void loggedIn();
void registration();
void editCredentials();
void update(Person);
void chgUsername();
void chgPassword();
void chgEmail();
void chgPhoneNo();
void quit();

//Stacks to store the users' personal data
stack<Person> users;

//Declaration of place holding variables
Person currentUser;
string username;
string password;
string password2;
string email;
string phoneNo;
int wrongPass = 0;

int main()
{
	//Reading from file to build the database
	ifstream fin("database.txt");
	while (!fin.eof())
	{
		//Reading in line-by-line into the placeholding variables
		fin >> username >> password >> email >> phoneNo;

		//Create the Person and push it into the stack
		Person temp(username, password, email, phoneNo);
		users.push(temp);
	}

	//Pop off the additional data added into the stack due to the empty line
	users.pop();

	getOption:
	//Display user input options
	cout << "Please choose one of the following options :" << endl;
	cout << "Log In       - 1" << endl;
	cout << "Registration - 2" << endl;
	cout << "Exit         - 0" << endl;

	//Get user input
	int choice;
	cin >> choice;

	//Switch according to user input
	switch (choice)
	{
	case 1:
		login();
		break;
	case 2:
		registration();
		break;
	case 0:
		break;
	default:
		//Display error message
		cout << "Invalid input. Please try again." << endl;
		goto getOption;
	}

	//Saving data into file
	ofstream fout("database.txt");

	//Check if the stack is empty
	while (!users.empty())
	{
		//Move the data into the files each Person per line
		fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl;
		//Pop the Person out of stack after the data is moved
		users.pop();
	}

	//End the program
  return 0;
}

void getUser()
{
	//Duplicate the current stack to be checked through
	stack<Person> temp = users;

	//Loop while the temporary stack is not empty
	while (!temp.empty())
	{
		//Check if the username match the query
		//If so, set it as the currentUser
		if (users.top().getName() == username) currentUser = users.top();

		//Pop the checked user
		users.pop();
	}

	//Throw invalid_argument error to be caught if the person is not found
	throw std::invalid_argument("");
}

void login()
{
	//If the user already has 3 fail attempt to login
	if (wrongPass >= 3)
	{
		//Print error message and exit
		cout << "Too much failed login attempt. The program will now be terminated." << endl;
		quit();
	}

	try {
		//Ask for username
		cout << "Username:";
		cin >> username;

		//Ask for password
		cout << "Password:";
		cin >> password;

		//Get the user
		getUser();

	} catch (invalid_argument inae) {
		//Print error message
		cout << "Invalid username or password. Please try again.";
		//Increase wrongPass count that indicate the amount of times of invalid
		//credentials input by the user
		wrongPass++;
		login();
	}

	//Check if the password is correct
	if (!currentUser.checkPassword(password))
	{
		//Print error message
		cout << "Invalid username or password. Please try again.";
		//Increase wrongPass count that indicate the amount of times of invalid
		//credentials input by the user
		wrongPass++;
		login();
	}

	//User is successfully logged in
	loggedIn();
}

void registration()
{
	//Initialize boolean
	bool available;

	do
	{
		try
		{
			//Get username
			cout << "Username: ";
			cin >> username;

			//Check if username is already in use
			//If not, it will throw an invalid_argument error to be caught
			getUser();

			//Print error message
			cout << "Username unavailable. Please try again." << endl;
			//Set available as false and continue the loop
			available = false;
		//Catch the invalid_argument error thrown by getUser()
		} catch (invalid_argument inae)
		{
			//Set available to true and quit the loop
			available = true;
		}
	} while (available == false);

	//Print success message
	cout << "Username is available." << endl;

	do
	{
		//Get password
		cout << "Password : ";
		cin >> password;

		//Confirm password
		cout << "Confirm password :";
		cin >> password2;

		//Print error message if both password is not the same
		if (password != password2)
			cout << "Password unmatched. Please try again.";
	//Loop until both password input is the same
	} while (password != password2);

	//Get email
	cout << "Email : ";
	cin >> email;

	//Get phone number
	cout << "Phone No. : ";
	cin >> phoneNo;

	//Create and push the new 'Person' into stack
	Person newUser(username, password, email, phoneNo);
	users.push(newUser);

	//Print success message
	cout << "Account is successfully registered." << endl;

	//Automatically login user
	currentUser = newUser;
	loggedIn();
}

void loggedIn()
{
	int choice;

	cout << "Please choose one of the following option :" << endl;
	cout << "View credentials - 1" << endl;
	cout << "Edit credentials - 2" << endl;
	cout << "Exit             - 0" << endl;
	cin >> choice;

	switch (choice)
	{
	case 1:
		cout << "Username : " << currentUser.getName() << "\nEmail : " << currentUser.getEmail() << "\nPhone No. : " << currentUser.getPhoneNo() << endl;
		loggedIn();
		break;
	case 2:
		editCredentials();
		loggedIn();
		break;
	case 0:
		quit();
	default:
		cout << "Invalid option. Please try again." << endl;
		cout << endl;
		loggedIn();
	}
}

void editCredentials()
{
	int choice;

	cout << "Which of the following to edit?" << endl;
	cout << "Username  - 1" << endl;
	cout << "Password  - 2" << endl;
	cout << "Email     - 3" << endl;
	cout << "Phone No. - 4" << endl;
	cout << "Exit      - 0" << endl;

	cin >> choice;

	switch (choice)
	{
	case 1:
		chgUsername();
		break;
	case 2:
		chgPassword();
		break;
	case 3:
		chgEmail();
		break;
	case 4:
		chgPhoneNo();
		break;
	}
}

void update(Person newUser)
{
	stack<Person> newUsers;

	while (!users.empty())
	{
		if (users.top().getName() == currentUser.getName())
		{
			cout << "replaced" << endl;
			newUsers.push(newUser);
		}
		else
		{
			newUsers.push(users.top());
		}

		users.pop();
	}

	users = newUsers;
	currentUser = newUser;
}

void chgUsername()
{
	bool available;
	Person newUsers;

	do
	{
		available = true;
		cout << available << endl;
		cout << "Username : ";
		cin >> username;

		stack<Person> temp = users;

		while (!temp.empty())
		{
			if (temp.top().getName() == username)
			{
				cout << "Username unavailable. Please try again." << endl;
				cout << temp.top().getName() << " " << temp.top().getPhoneNo() << endl;
				available = false;
				break;
			}

			temp.pop();
		}
	}	while (available == false);

	cout << "Username is available." << endl;
	Person newPerson(username, currentUser.getPassword(), currentUser.getEmail(), currentUser.getPhoneNo());
	update(newPerson);

	cout << "Username is updated." << endl;
}

void chgPassword()
{
	cout << "Please input the current password : ";
	cin >> password;

	while (!currentUser.checkPassword(password))
	{
		cout << "Wrong password. Please try again." << endl;
		wrongPass++;

		cout << "Please input the current password : ";
		cin >> password;
	}

	do {
		cout << "Please input the new password : ";
		cin >> password;

		cout << "Please confirm your new password : ";
		cin >> password2;
	} while(password2 != password);

	currentUser.setPassword(password);
	update(currentUser);
}

void chgEmail()
{
	cout << "Please input the new email : ";
	cin >> email;

	currentUser.setEmail(email);
	update(currentUser);
}

void chgPhoneNo()
{
	cout << "Please input the new phone no. : ";
	cin >> phoneNo;

	currentUser.setPhoneNo(phoneNo);
	update(currentUser);
}

void quit()
{
	ofstream fout("database.txt");

	while (!users.empty())
	{
		fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl;
		users.pop();
	}

	exit (EXIT_SUCCESS);
}
<commit_msg>Removed quit()<commit_after>/*
 *	Written by   : BinHong Lee
 *	Last edited  : 7/7/2016
 */

#include <iostream>
#include <string>
#include <stack>
#include <fstream>
#include "Person.cpp"
using namespace std;

//Declaration of functions
void getUser(string);
void login();
void adminLogin();
void loggedIn();
void registration();
void editCredentials();
void update(Person);
void chgUsername();
void chgPassword();
void chgEmail();
void chgPhoneNo();
//void quit();

//Stacks to store the users' personal data
stack<Person> users;

//Declaration of place holding variables
Person currentUser;
string username;
string password;
string password2;
string email;
string phoneNo;
int wrongPass = 0;

int main()
{
	//Reading from file to build the database
	ifstream fin("database.txt");
	while (!fin.eof())
	{
		//Reading in line-by-line into the placeholding variables
		fin >> username >> password >> email >> phoneNo;

		//Create the Person and push it into the stack
		Person temp(username, password, email, phoneNo);
		users.push(temp);
	}

	//Pop off the additional data added into the stack due to the empty line
	users.pop();

	getOption:
	//Display user input options
	cout << "Please choose one of the following options :" << endl;
	cout << "Log In       - 1" << endl;
	cout << "Registration - 2" << endl;
	cout << "Exit         - 0" << endl;

	//Get user input
	int choice;
	cin >> choice;

	//Switch according to user input
	switch (choice)
	{
	case 1:
		login();
		break;
	case 2:
		registration();
		break;
	case 0:
		break;
	default:
		//Display error message
		cout << "Invalid input. Please try again." << endl;
		goto getOption;
	}

	//Saving data into file
	ofstream fout("database.txt");

	//Check if the stack is empty
	while (!users.empty())
	{
		//Move the data into the files each Person per line
		fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl;
		//Pop the Person out of stack after the data is moved
		users.pop();
	}

	//End the program
  return 0;
}

void getUser()
{
	//Duplicate the current stack to be checked through
	stack<Person> temp = users;

	//Loop while the temporary stack is not empty
	while (!temp.empty())
	{
		//Check if the username match the query
		//If so, set it as the currentUser
		if (users.top().getName() == username) currentUser = users.top();

		//Pop the checked user
		users.pop();
	}

	//Throw invalid_argument error to be caught if the person is not found
	throw std::invalid_argument("");
}

void login()
{
	//If the user already has 3 fail attempt to login
	if (wrongPass >= 3)
	{
		//Print error message and exit
		cout << "Too much failed login attempt. The program will now be terminated." << endl;
		return;
	}

	try {
		//Ask for username
		cout << "Username:";
		cin >> username;

		//Ask for password
		cout << "Password:";
		cin >> password;

		//Get the user
		getUser();

	} catch (invalid_argument inae) {
		//Print error message
		cout << "Invalid username or password. Please try again.";
		//Increase wrongPass count that indicate the amount of times of invalid
		//credentials input by the user
		wrongPass++;
		login();
	}

	//Check if the password is correct
	if (!currentUser.checkPassword(password))
	{
		//Print error message
		cout << "Invalid username or password. Please try again.";
		//Increase wrongPass count that indicate the amount of times of invalid
		//credentials input by the user
		wrongPass++;
		login();
	}

	//User is successfully logged in
	loggedIn();
}

void registration()
{
	//Initialize boolean
	bool available;

	do
	{
		try
		{
			//Get username
			cout << "Username: ";
			cin >> username;

			//Check if username is already in use
			//If not, it will throw an invalid_argument error to be caught
			getUser();

			//Print error message
			cout << "Username unavailable. Please try again." << endl;
			//Set available as false and continue the loop
			available = false;
		//Catch the invalid_argument error thrown by getUser()
		} catch (invalid_argument inae)
		{
			//Set available to true and quit the loop
			available = true;
		}
	} while (available == false);

	//Print success message
	cout << "Username is available." << endl;

	do
	{
		//Get password
		cout << "Password : ";
		cin >> password;

		//Confirm password
		cout << "Confirm password :";
		cin >> password2;

		//Print error message if both password is not the same
		if (password != password2)
			cout << "Password unmatched. Please try again.";
	//Loop until both password input is the same
	} while (password != password2);

	//Get email
	cout << "Email : ";
	cin >> email;

	//Get phone number
	cout << "Phone No. : ";
	cin >> phoneNo;

	//Create and push the new 'Person' into stack
	Person newUser(username, password, email, phoneNo);
	users.push(newUser);

	//Print success message
	cout << "Account is successfully registered." << endl;

	//Automatically login user
	currentUser = newUser;
	loggedIn();
}

void loggedIn()
{
	//Declare space to save user's option
	int choice;

	//Print options
	cout << "Please choose one of the following option :" << endl;
	cout << "View credentials - 1" << endl;
	cout << "Edit credentials - 2" << endl;
	cout << "Exit             - 0" << endl;
	//Get user selection
	cin >> choice;

	switch (choice)
	{
	case 1:
		//Print out user credentials
		cout << "Username : " << currentUser.getName() << "\nEmail : " << currentUser.getEmail() << "\nPhone No. : " << currentUser.getPhoneNo() << endl;
		//Nested call back into the menu
		loggedIn();
		break;
	case 2:
		editCredentials();
		//Nested call back into the menu
		loggedIn();
		break;
	case 0:
		break;
	default:
		cout << "Invalid option. Please try again." << endl;
		cout << endl;
		loggedIn();
	}
}

void editCredentials()
{
	int choice;

	cout << "Which of the following to edit?" << endl;
	cout << "Username  - 1" << endl;
	cout << "Password  - 2" << endl;
	cout << "Email     - 3" << endl;
	cout << "Phone No. - 4" << endl;
	cout << "Exit      - 0" << endl;

	cin >> choice;

	switch (choice)
	{
	case 1:
		chgUsername();
		break;
	case 2:
		chgPassword();
		break;
	case 3:
		chgEmail();
		break;
	case 4:
		chgPhoneNo();
		break;
	}
}

void update(Person newUser)
{
	stack<Person> newUsers;

	while (!users.empty())
	{
		if (users.top().getName() == currentUser.getName())
		{
			cout << "replaced" << endl;
			newUsers.push(newUser);
		}
		else
		{
			newUsers.push(users.top());
		}

		users.pop();
	}

	users = newUsers;
	currentUser = newUser;
}

void chgUsername()
{
	bool available;
	Person newUsers;

	do
	{
		available = true;
		cout << available << endl;
		cout << "Username : ";
		cin >> username;

		stack<Person> temp = users;

		while (!temp.empty())
		{
			if (temp.top().getName() == username)
			{
				cout << "Username unavailable. Please try again." << endl;
				cout << temp.top().getName() << " " << temp.top().getPhoneNo() << endl;
				available = false;
				break;
			}

			temp.pop();
		}
	}	while (available == false);

	cout << "Username is available." << endl;
	Person newPerson(username, currentUser.getPassword(), currentUser.getEmail(), currentUser.getPhoneNo());
	update(newPerson);

	cout << "Username is updated." << endl;
}

void chgPassword()
{
	cout << "Please input the current password : ";
	cin >> password;

	while (!currentUser.checkPassword(password))
	{
		cout << "Wrong password. Please try again." << endl;
		wrongPass++;

		cout << "Please input the current password : ";
		cin >> password;
	}

	do {
		cout << "Please input the new password : ";
		cin >> password;

		cout << "Please confirm your new password : ";
		cin >> password2;
	} while(password2 != password);

	currentUser.setPassword(password);
	update(currentUser);
}

void chgEmail()
{
	cout << "Please input the new email : ";
	cin >> email;

	currentUser.setEmail(email);
	update(currentUser);
}

void chgPhoneNo()
{
	cout << "Please input the new phone no. : ";
	cin >> phoneNo;

	currentUser.setPhoneNo(phoneNo);
	update(currentUser);
}

/*
void quit()
{
	ofstream fout("database.txt");

	while (!users.empty())
	{
		fout << users.top().getName() << " " << users.top().getPassword() << " " << users.top().getEmail() << " " << users.top().getPhoneNo() << " " << endl;
		users.pop();
	}

	exit (EXIT_SUCCESS);
}
*/
<|endoftext|>


<commit_before>/*
  Copyright (c) 2015 Arduino LLC.  All right reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#define ARDUINO_MAIN
#include "Arduino.h"

// Weak empty variant initialization function.
// May be redefined by variant files.
//void initVariant(void) __attribute__((weak));
//void initVariant(void) { }

/*
 * \brief Main entry point of Arduino application
 */
int main( void )
{
  /* Setup vectors in RAM */
  vectorSetOrigin( &exception_table );

  /* Initialize watchdog */
  watchdogSetup();

  /* Initialize the Arduino Core API */
  init();

  /* Initialize the variant */
  initVariant();

  delay(1);
#if 0
#if defined(USBCON)
  USBDevice.init();
  USBDevice.attach();
#endif
#endif

  setup();

  for (;;)
  {
    loop();
    if (serialEventRun) serialEventRun();
  }

  return 0;
}
<commit_msg>Rolling back unnecessary change to core_main.cpp<commit_after>/*
  Copyright (c) 2015 Arduino LLC.  All right reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#define ARDUINO_MAIN
#include "Arduino.h"

// Weak empty variant initialization function.
// May be redefined by variant files.
//void initVariant(void) __attribute__((weak));
//void initVariant(void) { }

/*
 * \brief Main entry point of Arduino application
 */
int main( void )
{
  /* Setup vectors in RAM */
  vectorSetOrigin( &exception_table );

  /* Initialize watchdog */
  watchdogSetup();

  /* Initialize the Arduino Core API */
  init();

  /* Initialize the variant */
  initVariant();

  delay(1);
#if defined(USBCON)
  USBDevice.init();
  USBDevice.attach();
#endif

  setup();

  for (;;)
  {
    loop();
    if (serialEventRun) serialEventRun();
  }

  return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkCropImageFilter.h"

#include "itksys/SystemTools.hxx"

#ifdef ENABLE_QUICKVIEW
#  include "QuickView.h"
#endif

using PixelType = itk::RGBPixel<unsigned char>;
using ImageType = itk::Image<PixelType, 2>;

static void
CreateImage(ImageType::Pointer image);

int
main(int argc, char * argv[])
{
  ImageType::Pointer  image = ImageType::New();
  ImageType::SizeType cropSize;
  std::stringstream   desc;

  if (argc > 1)
  {
    using ReaderType = itk::ImageFileReader<ImageType>;
    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(argv[1]);
    if (argc > 2)
    {
      cropSize[0] = std::stoi(argv[2]);
      cropSize[1] = std::stoi(argv[3]);
    }
    reader->Update();
    image = reader->GetOutput();
    desc << itksys::SystemTools::GetFilenameName(argv[1]);
  }
  else
  {
    CreateImage(image);
    cropSize[0] = 10;
    cropSize[1] = 14;
    desc << "Synthetic image";
  }

  using CropImageFilterType = itk::CropImageFilter<ImageType, ImageType>;

  CropImageFilterType::Pointer cropFilter = CropImageFilterType::New();
  cropFilter->SetInput(image);
  // The SetBoundaryCropSize( cropSize ) method specifies the size of
  // the boundary to be cropped at both the uppper & lower ends of the
  // image eg. cropSize/2 pixels will be removed at both upper & lower
  // extents

  cropFilter->SetBoundaryCropSize(cropSize);

  // The below three lines are equivalent to the above two lines:
  // ImageType::SizeType halfCropSize = {5,7};
  // cropFilter->SetUpperBoundaryCropSize(halfCropSize);
  // cropFilter->SetLowerBoundaryCropSize(halfCropSize);

#ifdef ENABLE_QUICKVIEW
  QuickView viewer;
  viewer.AddRGBImage(image.GetPointer(), true, desc.str());

  std::stringstream desc2;
  desc2 << "CropImageFilter, crop size = {" << cropSize[0] << ", " << cropSize[1] << "}";
  viewer.AddRGBImage(cropFilter->GetOutput(), true, desc2.str());

  viewer.Visualize();
#endif
  return EXIT_SUCCESS;
}

void
CreateImage(ImageType::Pointer image)
{
  // Create an image with 2 connected components
  ImageType::RegionType region;
  ImageType::IndexType  start;
  start[0] = 0;
  start[1] = 0;

  ImageType::SizeType size;
  unsigned int        NumRows = 200;
  unsigned int        NumCols = 300;
  size[0] = NumRows;
  size[1] = NumCols;

  region.SetSize(size);
  region.SetIndex(start);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(itk::NumericTraits<ImageType::PixelType>::Zero);

  // Make a rectangle, centered at (100,150) with sides 160 & 240
  // This provides a 20 x 30 border around the square for the crop filter to remove
  for (unsigned int r = 20; r < 180; r++)
  {
    for (unsigned int c = 30; c < 270; c++)
    {
      ImageType::IndexType pixelIndex;
      pixelIndex[0] = r;
      pixelIndex[1] = c;

      image->SetPixel(pixelIndex, 200);
    }
  }
}
<commit_msg>DOC: updating comments to reflect actual behavior<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkCropImageFilter.h"

#include "itksys/SystemTools.hxx"

#ifdef ENABLE_QUICKVIEW
#  include "QuickView.h"
#endif

using PixelType = itk::RGBPixel<unsigned char>;
using ImageType = itk::Image<PixelType, 2>;

static void
CreateImage(ImageType::Pointer image);

int
main(int argc, char * argv[])
{
  ImageType::Pointer  image = ImageType::New();
  ImageType::SizeType cropSize;
  std::stringstream   desc;

  if (argc > 1)
  {
    using ReaderType = itk::ImageFileReader<ImageType>;
    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(argv[1]);
    if (argc > 2)
    {
      cropSize[0] = std::stoi(argv[2]);
      cropSize[1] = std::stoi(argv[3]);
    }
    reader->Update();
    image = reader->GetOutput();
    desc << itksys::SystemTools::GetFilenameName(argv[1]);
  }
  else
  {
    CreateImage(image);
    cropSize[0] = 10;
    cropSize[1] = 14;
    desc << "Synthetic image";
  }

  using CropImageFilterType = itk::CropImageFilter<ImageType, ImageType>;

  CropImageFilterType::Pointer cropFilter = CropImageFilterType::New();
  cropFilter->SetInput(image);
  // The SetBoundaryCropSize( cropSize ) method specifies the size of
  // the boundary to be cropped at both the uppper & lower ends of the
  // image eg. cropSize pixels will be removed at both upper & lower
  // extents

  cropFilter->SetBoundaryCropSize(cropSize);

  // The below two lines are equivalent to the above line:
  // cropFilter->SetUpperBoundaryCropSize(cropSize);
  // cropFilter->SetLowerBoundaryCropSize(cropSize);

#ifdef ENABLE_QUICKVIEW
  QuickView viewer;
  viewer.AddRGBImage(image.GetPointer(), true, desc.str());

  std::stringstream desc2;
  desc2 << "CropImageFilter, crop size = {" << cropSize[0] << ", " << cropSize[1] << "}";
  viewer.AddRGBImage(cropFilter->GetOutput(), true, desc2.str());

  viewer.Visualize();
#endif
  return EXIT_SUCCESS;
}

void
CreateImage(ImageType::Pointer image)
{
  // Create an image with 2 connected components
  ImageType::RegionType region;
  ImageType::IndexType  start;
  start[0] = 0;
  start[1] = 0;

  ImageType::SizeType size;
  unsigned int        NumRows = 200;
  unsigned int        NumCols = 300;
  size[0] = NumRows;
  size[1] = NumCols;

  region.SetSize(size);
  region.SetIndex(start);

  image->SetRegions(region);
  image->Allocate();
  image->FillBuffer(itk::NumericTraits<ImageType::PixelType>::Zero);

  // Make a rectangle, centered at (100,150) with sides 160 & 240
  // This provides a 20 x 30 border around the square for the crop filter to remove
  for (unsigned int r = 20; r < 180; r++)
  {
    for (unsigned int c = 30; c < 270; c++)
    {
      ImageType::IndexType pixelIndex;
      pixelIndex[0] = r;
      pixelIndex[1] = c;

      image->SetPixel(pixelIndex, 200);
    }
  }
}
<|endoftext|>