<commit_before>#include "ModuleEditorCamera.h"
#include "Engine.h"
#include "ModuleInput.h"
#include <MathGeoLib/include/Math/Quat.h>

using namespace math;

ModuleEditorCamera::ModuleEditorCamera()
{
	Frustum.SetPos(float3::zero);
	Frustum.SetFront(-float3::unitZ);
	Frustum.SetUp(float3::unitY);

	SetPlaneDistances(0.1f, 1000.0f);

	Frustum.SetPerspective(1, DegToRad(60));
	SetAspectRatio(1.3f);

	Frustum.SetKind(FrustumSpaceGL, FrustumRightHanded);
}

ModuleEditorCamera::~ModuleEditorCamera()
{
}

update_status ModuleEditorCamera::Update()
{
	float3 movement = float3::zero;

	float rotateUp = 0;
	float rotateRight = 0;

	if (App->input->GetKey(SDL_SCANCODE_UP))
		rotateUp += 1;
	if (App->input->GetKey(SDL_SCANCODE_DOWN))
		rotateUp -= 1;
	if (App->input->GetKey(SDL_SCANCODE_RIGHT))
		rotateRight += 1;
	if (App->input->GetKey(SDL_SCANCODE_LEFT))
		rotateRight -= 1;

	if (rotateRight != 0)
	{
		Quat rot = Quat::RotateAxisAngle(Frustum.Up(), DegToRad(rotateRight));

		Frustum.SetFront(rot.Mul(Frustum.Front()).Normalized());
		Frustum.SetUp(rot.Mul(Frustum.Up()).Normalized());
	}

	if (rotateUp != 0.f)
	{
		Quat rot = Quat::RotateAxisAngle(Frustum.WorldRight(), DegToRad(rotateUp));

		float3 up = rot.Mul(Frustum.Up()).Normalized();

		if (up.y > 0.f)
		{
			Frustum.SetFront(rot.Mul(Frustum.Front()).Normalized());
			Frustum.SetUp(up);
		}
	}

	if (App->input->GetKey(SDL_SCANCODE_Q))
		movement += float3::unitY;
	if (App->input->GetKey(SDL_SCANCODE_E))
		movement -= float3::unitY;
	if (App->input->GetKey(SDL_SCANCODE_W))
		movement += Frustum.Front();
	if (App->input->GetKey(SDL_SCANCODE_S))
		movement -= Frustum.Front();
	if (App->input->GetKey(SDL_SCANCODE_A))
		movement -= Frustum.WorldRight();
	if (App->input->GetKey(SDL_SCANCODE_D))
		movement += Frustum.WorldRight();

	Frustum.SetPos(Frustum.Pos() + movement);

	return UPDATE_CONTINUE;
}

void ModuleEditorCamera::SetFOV(float fov)
{
	Frustum.SetVerticalFovAndAspectRatio(fov, Frustum.AspectRatio());
}

void ModuleEditorCamera::SetAspectRatio(float ratio)
{
	Frustum.SetVerticalFovAndAspectRatio(Frustum.VerticalFov(), ratio);
}

void ModuleEditorCamera::SetPlaneDistances(float near, float far)
{
	Frustum.SetViewPlaneDistances(near, far);
}

float3 ModuleEditorCamera::Position() const
{
	return Frustum.Pos();
}

float3 ModuleEditorCamera::Orientation() const
{
	return Frustum.Front();
}

void ModuleEditorCamera::LookAt(float x, float y, float z)
{

}

float* ModuleEditorCamera::GetProjectionMatrix() const
{
	static float4x4 proj;

	proj = Frustum.ProjectionMatrix();
	proj.Transpose();

	return reinterpret_cast<float*>(proj.v);
}

float* ModuleEditorCamera::GetViewMatrix() const
{
	static float4x4 view;

	view = Frustum.ViewMatrix();

	view.Transpose();

	return reinterpret_cast<float*>(view.v);
}
<commit_msg>Improve vertical rotation speed<commit_after>#include "ModuleEditorCamera.h"
#include "Engine.h"
#include "ModuleInput.h"
#include <MathGeoLib/include/Math/Quat.h>

using namespace math;

ModuleEditorCamera::ModuleEditorCamera()
{
	Frustum.SetPos(float3::zero);
	Frustum.SetFront(-float3::unitZ);
	Frustum.SetUp(float3::unitY);

	SetPlaneDistances(0.1f, 1000.0f);

	Frustum.SetPerspective(1, DegToRad(60));
	SetAspectRatio(1.3f);

	Frustum.SetKind(FrustumSpaceGL, FrustumRightHanded);
}

ModuleEditorCamera::~ModuleEditorCamera()
{
}

update_status ModuleEditorCamera::Update()
{
	float3 movement = float3::zero;

	float rotateUp = 0;
	float rotateRight = 0;

	if (App->input->GetKey(SDL_SCANCODE_UP))
		rotateUp += 1;
	if (App->input->GetKey(SDL_SCANCODE_DOWN))
		rotateUp -= 1;
	if (App->input->GetKey(SDL_SCANCODE_RIGHT))
		rotateRight += 1;
	if (App->input->GetKey(SDL_SCANCODE_LEFT))
		rotateRight -= 1;

	if (rotateRight != 0)
	{
		Quat rot = Quat::RotateAxisAngle(Frustum.Up(), DegToRad(rotateRight));

		Frustum.SetFront(rot.Mul(Frustum.Front()).Normalized());
		Frustum.SetUp(rot.Mul(Frustum.Up()).Normalized());
	}

	if (rotateUp != 0.f)
	{
		Quat rot = Quat::RotateAxisAngle(Frustum.WorldRight(), DegToRad(rotateUp));

		Frustum.Transform(rot);
	}

	if (App->input->GetKey(SDL_SCANCODE_Q))
		movement += float3::unitY;
	if (App->input->GetKey(SDL_SCANCODE_E))
		movement -= float3::unitY;
	if (App->input->GetKey(SDL_SCANCODE_W))
		movement += Frustum.Front();
	if (App->input->GetKey(SDL_SCANCODE_S))
		movement -= Frustum.Front();
	if (App->input->GetKey(SDL_SCANCODE_A))
		movement -= Frustum.WorldRight();
	if (App->input->GetKey(SDL_SCANCODE_D))
		movement += Frustum.WorldRight();

	Frustum.SetPos(Frustum.Pos() + movement);

	return UPDATE_CONTINUE;
}

void ModuleEditorCamera::SetFOV(float fov)
{
	Frustum.SetVerticalFovAndAspectRatio(fov, Frustum.AspectRatio());
}

void ModuleEditorCamera::SetAspectRatio(float ratio)
{
	Frustum.SetVerticalFovAndAspectRatio(Frustum.VerticalFov(), ratio);
}

void ModuleEditorCamera::SetPlaneDistances(float near, float far)
{
	Frustum.SetViewPlaneDistances(near, far);
}

float3 ModuleEditorCamera::Position() const
{
	return Frustum.Pos();
}

float3 ModuleEditorCamera::Orientation() const
{
	return Frustum.Front();
}

void ModuleEditorCamera::LookAt(float x, float y, float z)
{

}

float* ModuleEditorCamera::GetProjectionMatrix() const
{
	static float4x4 proj;

	proj = Frustum.ProjectionMatrix();
	proj.Transpose();

	return reinterpret_cast<float*>(proj.v);
}

float* ModuleEditorCamera::GetViewMatrix() const
{
	static float4x4 view;

	view = Frustum.ViewMatrix();

	view.Transpose();

	return reinterpret_cast<float*>(view.v);
}
<|endoftext|>


<commit_before>#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup(){
	ofBackground(200, 200, 200);
	ofSetVerticalSync(false);
    ofSetFrameRate(90);

    ofSetDataPathRoot("../Resources/data/");

	//Connect to Port
//	myTuio.start(7001);
//	myTuio.start(7001);

//    for (int i=0; i<TUIO_NUM; i++) {
//        ofxTuioClient * tmpTuio = new ofxTuioClient();
//        Tuios.push_back(tmpTuio);
//        Tuios[i]->start(TUIO_PORT+i);
//    }

    bControl = bClicked = currentClicked = false;
    pos = currentPos = ofPoint(0,0);

    bShowGui = true;
    bEnabled = false;
    bDragDown = true;

    Width = SCREEN_W, Height = SCREEN_H;

    guiScreenNumber = screenNumber = TUIO_NUM;

    gui = new ofxUISuperCanvas("conf", 0,0,50,50);
    gui->setGlobalSliderHeight(5);
    //    gui->addTextInput("host", udpHost, 50.f);
    gui->addToggle("active", &bControl);
    gui->addToggle("mouse drag + down", &bDragDown);
//    gui->addToggle("invert", &bInvert);
//    gui->addToggle("switch XY", &bSwitchXY);
    //    gui->addNumberDialer("pix", 0.5, 10, &pixelsInLed, 1)->setDrawOutline(true);
    gui->addNumberDialer("total width", 100, 10000, &Width, 0);
    gui->addNumberDialer("total height", 100, 10000, &Height, 0);

    gui->addNumberDialer("num screns", 1, 10, &guiScreenNumber, 0);

    gui->loadSettings("GUI.xml");
    gui->autoSizeToFitWidgets();
    gui->getFontSmall()->loadFont("GUI/Helvetica.ttf", 8);

    gui->setPosition(10, 10);

    gui->disableAppDrawCallback();
    gui->setAutoUpdate(true);

    setupScreens();
}

//--------------------------------------------------------------
void testApp::setupScreens(){

    screenNumber = static_cast<unsigned int>(guiScreenNumber);
    Screens.clear();
    for (int i=0; i<screenNumber; i++){
        tuioScreen * tmpScreen = new tuioScreen(i+1,TUIO_PORT+i,Width/screenNumber, Height, ofPoint(Width/screenNumber*i, 0));
        Screens.push_back(tmpScreen);
    }

}

//--------------------------------------------------------------
void testApp::update(){

    bool wasTouched = false;

    if (Screens.size() != static_cast<size_t>(guiScreenNumber))
        setupScreens();

    for (int i=0; i<Screens.size(); i++) {
        Screens[i]->update();
        mousePosOF = Screens[i]->getTouchPos();
        if (mousePosOF != ofPoint(-1,-1)){
            pos = mousePosOF;
//            ofLog(OF_LOG_NOTICE, "SCREEN "+ofToString(i+1)+"  "+ofToString(pos));
            wasTouched = true;
            controlMouse(pos, true);
            break;
        }
    }

    if (!wasTouched)
        controlMouse(pos, false);
}

//--------------------------------------------------------------
void testApp::draw(){

	//render TUIO Cursors and Objects
//	myTuio.drawCursors();
//	myTuio.drawObjects();

    ofSetColor(255, 255,255,255);
//    ofRect(mousePosOF, 20, 20);

    float scaleX = ofGetWidth()/Width;
    float scaleY = ofGetHeight()/Height;
    for (int i=0; i<Screens.size(); i++)
        Screens[i]->draw(scaleX, scaleY);

    if (bShowGui) gui->draw();

    ofSetWindowTitle("FPS: " + ofToString((int)ofGetFrameRate()));
}

void testApp::controlMouse(ofPoint pos, bool isClicked) {

    if (!bControl) return;

    CGPoint pt;
    pt.x = pos.x; pt.y = pos.y;

    if (currentClicked != isClicked) {
        currentClicked = isClicked;
        if (isClicked) {
//            //            cout << "Mouse Down!!+++++++" << endl;
            CGEventRef mouseDownEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseDown,pt,kCGMouseButtonLeft);
            CGEventPost (kCGHIDEventTap, mouseDownEv);
            CFRelease(mouseDownEv);
//            ofLog(OF_LOG_NOTICE, "DOWN");
        } else {
            //            cout << "Mouse Up!!+++++++-----------" << endl;
            CGEventRef mouseUpEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseUp,pt,kCGMouseButtonLeft);
            CGEventPost (kCGHIDEventTap, mouseUpEv );
            CFRelease(mouseUpEv);
//            ofLog(OF_LOG_NOTICE, "UP");
        }
    }

    if (currentPos != pos) {
        currentPos = pos;
        CGEventRef mouseMoveEv;
        if (currentClicked) {
            mouseMoveEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseDragged,pt,kCGMouseButtonLeft) ;
            CGEventPost (kCGHIDEventTap, mouseMoveEv);
            if (bDragDown) {
                CGEventRef mouseDownEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseDown,pt,kCGMouseButtonLeft);
                CGEventPost (kCGHIDEventTap, mouseDownEv);
                CFRelease(mouseDownEv);
            }
        }
        else {
            mouseMoveEv = CGEventCreateMouseEvent (NULL, kCGEventMouseMoved, pt, kCGMouseButtonLeft);
            CGEventPost (kCGHIDEventTap, mouseMoveEv);
        }

        CFRelease(mouseMoveEv);
    }

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){
    if (key == ' ') bControl = !bControl;

    if (key == 's') {
        gui->saveSettings("GUI.xml");
        for (int i=0; i<Screens.size(); i++) Screens[i]->save();
    }
    else if (key == 'l') {
        gui->loadSettings("GUI.xml");
        for (int i=0; i<Screens.size(); i++) Screens[i]->load();
    }

    if (key == 'g') {
        bShowGui = !bShowGui;
        for (int i=0; i<Screens.size(); i++) Screens[i]->showGui(bShowGui);
    }
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

//    mousePosOF = ofPoint(x,y);

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

void testApp::touchDown(ofTouchEventArgs & touch){
//	cout << " cursor added: " + ofToString(touch.id)+
//	" X: "+ofToString(touch.x)+
//	" Y: "+ofToString(touch.y)
//	<< endl;
//    controlMouse(ofPoint(touch.x, touch.y), true);

}

void testApp::touchUp(ofTouchEventArgs & touch){
//	ofLog(OF_LOG_VERBOSE, " cursor removed: " + ofToString(touch.id)+
//	 " X: "+ofToString(touch.x)+
//	 " Y: "+ofToString(touch.y)
//      );
//    controlMouse(ofPoint(touch.x, touch.y), false);
}

void testApp::touchMoved(ofTouchEventArgs & touch){
//	cout << " cursor updated: " + ofToString(touch.id)+
//	 " X: "+ofToString(touch.x)+
//	 " Y: "+ofToString(touch.y)
//	 << endl;

    controlMouse(ofPoint(touch.x, touch.y), true);
}

<commit_msg>fixes<commit_after>#include "testApp.h"

//--------------------------------------------------------------
void testApp::setup(){
	ofBackground(200, 200, 200);
	ofSetVerticalSync(false);
    ofSetFrameRate(90);

    ofSetDataPathRoot("../Resources/data/");

	//Connect to Port
//	myTuio.start(7001);
//	myTuio.start(7001);

//    for (int i=0; i<TUIO_NUM; i++) {
//        ofxTuioClient * tmpTuio = new ofxTuioClient();
//        Tuios.push_back(tmpTuio);
//        Tuios[i]->start(TUIO_PORT+i);
//    }

    bControl = bClicked = currentClicked = false;
    pos = currentPos = ofPoint(0,0);

    bShowGui = true;
    bEnabled = false;
    bDragDown = true;

    Width = SCREEN_W, Height = SCREEN_H;

    guiScreenNumber = screenNumber = TUIO_NUM;

    gui = new ofxUISuperCanvas("conf", 0,0,50,50);
    gui->setGlobalSliderHeight(5);
    //    gui->addTextInput("host", udpHost, 50.f);
    gui->addToggle("active", &bControl);
    gui->addToggle("mouse drag + down", &bDragDown);
//    gui->addToggle("invert", &bInvert);
//    gui->addToggle("switch XY", &bSwitchXY);
    //    gui->addNumberDialer("pix", 0.5, 10, &pixelsInLed, 1)->setDrawOutline(true);
    gui->addNumberDialer("total width", 100, 10000, &Width, 0);
    gui->addNumberDialer("total height", 100, 10000, &Height, 0);

    gui->addNumberDialer("num screns", 1, 10, &guiScreenNumber, 0);

    gui->loadSettings("GUI.xml");
    gui->autoSizeToFitWidgets();
    gui->getFontSmall()->loadFont("GUI/Helvetica.ttf", 8);

    gui->setPosition(10, 10);

    gui->disableAppDrawCallback();
    gui->setAutoUpdate(true);

    setupScreens();
}

//--------------------------------------------------------------
void testApp::setupScreens(){

    screenNumber = static_cast<unsigned int>(guiScreenNumber);
    Screens.clear();
    for (int i=0; i<screenNumber; i++){
        tuioScreen * tmpScreen = new tuioScreen(i+1,TUIO_PORT+i,Width/screenNumber, Height, ofPoint(Width/screenNumber*i, 0));
        Screens.push_back(tmpScreen);
    }

}

//--------------------------------------------------------------
void testApp::update(){

    bool wasTouched = false;

    if (Screens.size() != static_cast<size_t>(guiScreenNumber))
        setupScreens();

    for (int i=0; i<Screens.size(); i++) {
        Screens[i]->update();
        mousePosOF = Screens[i]->getTouchPos();
        if (mousePosOF != ofPoint(-1,-1)){
            pos = mousePosOF;
//            ofLog(OF_LOG_NOTICE, "SCREEN "+ofToString(i+1)+"  "+ofToString(pos));
            wasTouched = true;
            controlMouse(pos, true);
            break;
        }
    }

    if (!wasTouched)
        controlMouse(pos, false);
}

//--------------------------------------------------------------
void testApp::draw(){

	//render TUIO Cursors and Objects
//	myTuio.drawCursors();
//	myTuio.drawObjects();

    ofSetColor(255, 255,255,255);
//    ofRect(mousePosOF, 20, 20);

    float scaleX = ofGetWidth()/Width;
    float scaleY = ofGetHeight()/Height;
    for (int i=0; i<Screens.size(); i++)
        Screens[i]->draw(scaleX, scaleY);

    if (bShowGui) gui->draw();

    ofSetWindowTitle("FPS: " + ofToString((int)ofGetFrameRate()));
}

void testApp::controlMouse(ofPoint pos, bool isClicked) {

    if (!bControl) return;

    CGPoint pt;
    pt.x = pos.x; pt.y = pos.y;

    if (currentPos != pos) {
        currentPos = pos;
        CGEventRef mouseMoveEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseDragged,pt,kCGMouseButtonLeft) ;
        CGEventPost (kCGHIDEventTap, mouseMoveEv);
        CFRelease(mouseMoveEv);
    }

    if (currentClicked != isClicked) {
        currentClicked = isClicked;
        if (isClicked) {
            //            cout << "Mouse Down!!+++++++" << endl;
            CGEventRef mouseDownEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseDown,pt,kCGMouseButtonLeft);
            CGEventPost (kCGHIDEventTap, mouseDownEv);
            CFRelease(mouseDownEv);
            ofLog(OF_LOG_NOTICE, "DOWN");
        } else {
            //            cout << "Mouse Up!!+++++++-----------" << endl;
            CGEventRef mouseUpEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseUp,pt,kCGMouseButtonLeft);
            CGEventPost (kCGHIDEventTap, mouseUpEv );
            CFRelease(mouseUpEv);
//            ofLog(OF_LOG_NOTICE, "UP");
        }
    }

//    if (currentPos != pos) {
//        currentPos = pos;
//        CGEventRef mouseMoveEv;
//        if (currentClicked) {
//            mouseMoveEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseDragged,pt,kCGMouseButtonLeft) ;
//            CGEventPost (kCGHIDEventTap, mouseMoveEv);
//            if (bDragDown) {
//                CGEventRef mouseDownEv = CGEventCreateMouseEvent (NULL,kCGEventLeftMouseDown,pt,kCGMouseButtonLeft);
//                CGEventPost (kCGHIDEventTap, mouseDownEv);
//                CFRelease(mouseDownEv);
//            }
//        }
//        else {
//            mouseMoveEv = CGEventCreateMouseEvent (NULL, kCGEventMouseMoved, pt, kCGMouseButtonLeft);
//            CGEventPost (kCGHIDEventTap, mouseMoveEv);
//        }
//
//        CFRelease(mouseMoveEv);
//    }

}

//--------------------------------------------------------------
void testApp::keyPressed(int key){

}

//--------------------------------------------------------------
void testApp::keyReleased(int key){
    if (key == ' ') bControl = !bControl;

    if (key == 's') {
        gui->saveSettings("GUI.xml");
        for (int i=0; i<Screens.size(); i++) Screens[i]->save();
    }
    else if (key == 'l') {
        gui->loadSettings("GUI.xml");
        for (int i=0; i<Screens.size(); i++) Screens[i]->load();
    }

    if (key == 'g') {
        bShowGui = !bShowGui;
        for (int i=0; i<Screens.size(); i++) Screens[i]->showGui(bShowGui);
    }
}

//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){

//    mousePosOF = ofPoint(x,y);

}

//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void testApp::windowResized(int w, int h){

}

void testApp::touchDown(ofTouchEventArgs & touch){
//	cout << " cursor added: " + ofToString(touch.id)+
//	" X: "+ofToString(touch.x)+
//	" Y: "+ofToString(touch.y)
//	<< endl;
//    controlMouse(ofPoint(touch.x, touch.y), true);

}

void testApp::touchUp(ofTouchEventArgs & touch){
//	ofLog(OF_LOG_VERBOSE, " cursor removed: " + ofToString(touch.id)+
//	 " X: "+ofToString(touch.x)+
//	 " Y: "+ofToString(touch.y)
//      );
//    controlMouse(ofPoint(touch.x, touch.y), false);
}

void testApp::touchMoved(ofTouchEventArgs & touch){
//	cout << " cursor updated: " + ofToString(touch.id)+
//	 " X: "+ofToString(touch.x)+
//	 " Y: "+ofToString(touch.y)
//	 << endl;

    controlMouse(ofPoint(touch.x, touch.y), true);
}

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// CoinVault
//
// txmodel.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.

#include "txmodel.h"

#include <CoinQ/CoinQ_script.h>
#include <CoinQ/CoinQ_netsync.h>

#include <stdutils/stringutils.h>

#include <QStandardItemModel>
#include <QDateTime>
#include <QMessageBox>

#include "settings.h"
#include "coinparams.h"

#include "severitylogger.h"

using namespace CoinDB;
using namespace CoinQ::Script;
using namespace std;

TxModel::TxModel(QObject* parent)
    : QStandardItemModel(parent)
{
    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
    base58_versions[1] = getCoinParams().pay_to_script_hash_version();

    initColumns();
}

TxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)
    : QStandardItemModel(parent)
{
    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
    base58_versions[1] = getCoinParams().pay_to_script_hash_version();

    initColumns();
    setVault(vault);
    setAccount(accountName);
}

void TxModel::initColumns()
{
    QStringList columns;
    columns << tr("Time") << tr("Description") << tr("Type") << tr("Amount") << tr("Fee") << tr("Balance") << tr("Confirmations") << tr("Address") << tr("Transaction Hash");
    setHorizontalHeaderLabels(columns);
}

void TxModel::setVault(CoinDB::Vault* vault)
{
    this->vault = vault;
    accountName.clear();
    update();
}

void TxModel::setAccount(const QString& accountName)
{
    if (!vault) {
        throw std::runtime_error("Vault is not open.");
    }

    if (!vault->accountExists(accountName.toStdString())) {
        throw std::runtime_error("Account not found.");
    }

    this->accountName = accountName;
    update();
}

void TxModel::update()
{
    removeRows(0, rowCount());

    if (!vault || accountName.isEmpty()) return;

    std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();

    std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), "", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);
    bytes_t last_txhash;
    typedef std::pair<unsigned long, uint32_t> sorting_info_t;
    typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; // used to associate output values with rows for computing balance
    typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;
    QList<sortable_row_t> rows;
    for (auto& item: txoutviews) {
        QList<QStandardItem*> row;

        QDateTime utc;
        utc.setTime_t(item.tx_timestamp);
        QString time = utc.toLocalTime().toString();

        QString description = QString::fromStdString(item.role_label());
        if (description.isEmpty()) description = "Not available";

        // The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.
        QString type;
        QString amount;
        QString fee;
        int64_t value = 0;
        bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;
        switch (item.role_flags) {
        case TxOut::ROLE_NONE:
            type = tr("None");
            break;

        case TxOut::ROLE_SENDER:
            type = tr("Send");
            amount = "-";
            value -= item.value;
            if (item.tx_has_all_outpoints && item.tx_fee > 0) {
                if (this_txhash != last_txhash) {
                    fee = "-";
                    fee += QString::number(item.tx_fee/100000000.0, 'g', 8);
                    value -= item.tx_fee;
                    last_txhash = this_txhash;
                }
                else {
                    fee = "||";
                }
            }
            break;

        case TxOut::ROLE_RECEIVER:
            type = tr("Receive");
            amount = "+";
            value += item.value;
            break;

        default:
            type = tr("Unknown");
        }

        amount += QString::number(item.value/100000000.0, 'g', 8);

        uint32_t nConfirmations = 0;
        QString confirmations;
        if (item.tx_status >= Tx::PROPAGATED) {
            if (bestHeader && item.height) {
                nConfirmations = bestHeader->height() + 1 - item.height;
                confirmations = QString::number(nConfirmations);
            }
            else {
                confirmations = "0";
            }
        }
        else if (item.tx_status == Tx::UNSIGNED) {
            confirmations = tr("Unsigned");
        }
        else if (item.tx_status == Tx::UNSENT) {
            confirmations = tr("Unsent");
        }
        QStandardItem* confirmationsItem = new QStandardItem(confirmations);
        confirmationsItem->setData(item.tx_status, Qt::UserRole);

        QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));
        QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());

        row.append(new QStandardItem(time));
        row.append(new QStandardItem(description));
        row.append(new QStandardItem(type));
        row.append(new QStandardItem(amount));
        row.append(new QStandardItem(fee));
        row.append(new QStandardItem("")); // placeholder for balance, once sorted
        row.append(confirmationsItem);
        row.append(new QStandardItem(address));
        row.append(new QStandardItem(hash));

        rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));
    }

    qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {
        sorting_info_t a_info = a.first;
        sorting_info_t b_info = b.first;

        // if confirmation counts are equal
        if (a_info.second == b_info.second) {
            // if one value is positive and the other is negative, sort so that running balance remains positive
            if (a.second.second < 0 && b.second.second > 0) return true;
            if (a.second.second > 0 && b.second.second < 0) return false;

            // otherwise sort by descending index
            return (a_info.first > b_info.first);
        }

        // otherwise sort by ascending confirmation count
        return (a_info.second < b_info.second);
    });

    // iterate in reverse order to compute running balance
    int64_t balance = 0;
    for (int i = rows.size() - 1; i >= 0; i--) {
        balance += rows[i].second.second;
        (rows[i].second.first)[5]->setText(QString::number(balance/100000000.0, 'g', 8));
    }

    // iterate in forward order to display
    for (auto& row: rows) appendRow(row.second.first);
}

void TxModel::signTx(int row)
{
    LOGGER(trace) << "TxModel::signTx(" << row << ")" << std::endl;

    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    QStandardItem* typeItem = item(row, 6);
    int type = typeItem->data(Qt::UserRole).toInt();
    if (type != CoinDB::Tx::UNSIGNED) {
        throw std::runtime_error(tr("Transaction is already signed.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    std::vector<std::string> keychainNames;
    std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);
    if (!tx) throw std::runtime_error(tr("No new signatures were added.").toStdString());

    LOGGER(trace) << "TxModel::signTx - signature(s) added. raw tx: " << uchar_vector(tx->raw()).getHex() << std::endl;
    update();

    QString msg;
    if (keychainNames.empty())
    {
        msg = tr("No new signatures were added.");
    }
    else
    {
        msg = tr("Signatures added using keychain(s) ") + QString::fromStdString(stdutils::delimited_list(keychainNames, ", ")) + tr(".");
    }
    emit txSigned(msg);
}

void TxModel::sendTx(int row, CoinQ::Network::NetworkSync* networkSync)
{
    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    if (!networkSync || !networkSync->isConnected()) {
        throw std::runtime_error(tr("Must be connected to network to send.").toStdString());
    }

    QStandardItem* typeItem = item(row, 6);
    int type = typeItem->data(Qt::UserRole).toInt();
    if (type == CoinDB::Tx::UNSIGNED) {
        throw std::runtime_error(tr("Transaction must be fully signed before sending.").toStdString());
    }
    else if (type == CoinDB::Tx::PROPAGATED) {
        throw std::runtime_error(tr("Transaction already sent.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);
    Coin::Transaction coin_tx = tx->toCoinCore();
    networkSync->sendTx(coin_tx);

    // TODO: Check transaction has propagated before changing status to PROPAGATED
//    tx->updateStatus(CoinDB::Tx::PROPAGATED);
//    vault->insertTx(tx);

//    update();
    networkSync->getTx(txhash);
}

std::shared_ptr<Tx> TxModel::getTx(int row)
{
    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    return vault->getTx(txhash);
}

void TxModel::deleteTx(int row)
{
    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    vault->deleteTx(txhash);
    update();

    emit txDeleted();
}

QVariant TxModel::data(const QModelIndex& index, int role) const
{
    // Right-align numeric fields
    if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6) {
        return Qt::AlignRight;
    }
    else {
        return QStandardItemModel::data(index, role);
    }
}

Qt::ItemFlags TxModel::flags(const QModelIndex& /*index*/) const
{
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}

<commit_msg>Use tx_fee() method.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// CoinVault
//
// txmodel.cpp
//
// Copyright (c) 2013 Eric Lombrozo
//
// All Rights Reserved.

#include "txmodel.h"

#include <CoinQ/CoinQ_script.h>
#include <CoinQ/CoinQ_netsync.h>

#include <stdutils/stringutils.h>

#include <QStandardItemModel>
#include <QDateTime>
#include <QMessageBox>

#include "settings.h"
#include "coinparams.h"

#include "severitylogger.h"

using namespace CoinDB;
using namespace CoinQ::Script;
using namespace std;

TxModel::TxModel(QObject* parent)
    : QStandardItemModel(parent)
{
    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
    base58_versions[1] = getCoinParams().pay_to_script_hash_version();

    initColumns();
}

TxModel::TxModel(CoinDB::Vault* vault, const QString& accountName, QObject* parent)
    : QStandardItemModel(parent)
{
    base58_versions[0] = getCoinParams().pay_to_pubkey_hash_version();
    base58_versions[1] = getCoinParams().pay_to_script_hash_version();

    initColumns();
    setVault(vault);
    setAccount(accountName);
}

void TxModel::initColumns()
{
    QStringList columns;
    columns << tr("Time") << tr("Description") << tr("Type") << tr("Amount") << tr("Fee") << tr("Balance") << tr("Confirmations") << tr("Address") << tr("Transaction Hash");
    setHorizontalHeaderLabels(columns);
}

void TxModel::setVault(CoinDB::Vault* vault)
{
    this->vault = vault;
    accountName.clear();
    update();
}

void TxModel::setAccount(const QString& accountName)
{
    if (!vault) {
        throw std::runtime_error("Vault is not open.");
    }

    if (!vault->accountExists(accountName.toStdString())) {
        throw std::runtime_error("Account not found.");
    }

    this->accountName = accountName;
    update();
}

void TxModel::update()
{
    removeRows(0, rowCount());

    if (!vault || accountName.isEmpty()) return;

    std::shared_ptr<BlockHeader> bestHeader = vault->getBestBlockHeader();

    std::vector<TxOutView> txoutviews = vault->getTxOutViews(accountName.toStdString(), "", TxOut::ROLE_BOTH, TxOut::BOTH, Tx::ALL, true);
    bytes_t last_txhash;
    typedef std::pair<unsigned long, uint32_t> sorting_info_t;
    typedef std::pair<QList<QStandardItem*>, int64_t> value_row_t; // used to associate output values with rows for computing balance
    typedef std::pair<sorting_info_t, value_row_t> sortable_row_t;
    QList<sortable_row_t> rows;
    for (auto& item: txoutviews) {
        QList<QStandardItem*> row;

        QDateTime utc;
        utc.setTime_t(item.tx_timestamp);
        QString time = utc.toLocalTime().toString();

        QString description = QString::fromStdString(item.role_label());
        if (description.isEmpty()) description = "Not available";

        // The type stuff is just to test the new db schema. It's all wrong, we're not going to use TxOutViews for this.
        QString type;
        QString amount;
        QString fee;
        int64_t value = 0;
        bytes_t this_txhash = item.tx_status == Tx::UNSIGNED ? item.tx_unsigned_hash : item.tx_hash;
        switch (item.role_flags) {
        case TxOut::ROLE_NONE:
            type = tr("None");
            break;

        case TxOut::ROLE_SENDER:
            type = tr("Send");
            amount = "-";
            value -= item.value;
            if (item.tx_has_all_outpoints && item.tx_fee() > 0) {
                if (this_txhash != last_txhash) {
                    fee = "-";
                    fee += QString::number(item.tx_fee()/100000000.0, 'g', 8);
                    value -= item.tx_fee();
                    last_txhash = this_txhash;
                }
                else {
                    fee = "||";
                }
            }
            break;

        case TxOut::ROLE_RECEIVER:
            type = tr("Receive");
            amount = "+";
            value += item.value;
            break;

        default:
            type = tr("Unknown");
        }

        amount += QString::number(item.value/100000000.0, 'g', 8);

        uint32_t nConfirmations = 0;
        QString confirmations;
        if (item.tx_status >= Tx::PROPAGATED) {
            if (bestHeader && item.height) {
                nConfirmations = bestHeader->height() + 1 - item.height;
                confirmations = QString::number(nConfirmations);
            }
            else {
                confirmations = "0";
            }
        }
        else if (item.tx_status == Tx::UNSIGNED) {
            confirmations = tr("Unsigned");
        }
        else if (item.tx_status == Tx::UNSENT) {
            confirmations = tr("Unsent");
        }
        QStandardItem* confirmationsItem = new QStandardItem(confirmations);
        confirmationsItem->setData(item.tx_status, Qt::UserRole);

        QString address = QString::fromStdString(getAddressForTxOutScript(item.script, base58_versions));
        QString hash = QString::fromStdString(uchar_vector(this_txhash).getHex());

        row.append(new QStandardItem(time));
        row.append(new QStandardItem(description));
        row.append(new QStandardItem(type));
        row.append(new QStandardItem(amount));
        row.append(new QStandardItem(fee));
        row.append(new QStandardItem("")); // placeholder for balance, once sorted
        row.append(confirmationsItem);
        row.append(new QStandardItem(address));
        row.append(new QStandardItem(hash));

        rows.append(std::make_pair(std::make_pair(item.tx_id, nConfirmations), std::make_pair(row, value)));
    }

    qSort(rows.begin(), rows.end(), [](const sortable_row_t& a, const sortable_row_t& b) {
        sorting_info_t a_info = a.first;
        sorting_info_t b_info = b.first;

        // if confirmation counts are equal
        if (a_info.second == b_info.second) {
            // if one value is positive and the other is negative, sort so that running balance remains positive
            if (a.second.second < 0 && b.second.second > 0) return true;
            if (a.second.second > 0 && b.second.second < 0) return false;

            // otherwise sort by descending index
            return (a_info.first > b_info.first);
        }

        // otherwise sort by ascending confirmation count
        return (a_info.second < b_info.second);
    });

    // iterate in reverse order to compute running balance
    int64_t balance = 0;
    for (int i = rows.size() - 1; i >= 0; i--) {
        balance += rows[i].second.second;
        (rows[i].second.first)[5]->setText(QString::number(balance/100000000.0, 'g', 8));
    }

    // iterate in forward order to display
    for (auto& row: rows) appendRow(row.second.first);
}

void TxModel::signTx(int row)
{
    LOGGER(trace) << "TxModel::signTx(" << row << ")" << std::endl;

    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    QStandardItem* typeItem = item(row, 6);
    int type = typeItem->data(Qt::UserRole).toInt();
    if (type != CoinDB::Tx::UNSIGNED) {
        throw std::runtime_error(tr("Transaction is already signed.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    std::vector<std::string> keychainNames;
    std::shared_ptr<Tx> tx = vault->signTx(txhash, keychainNames, true);
    if (!tx) throw std::runtime_error(tr("No new signatures were added.").toStdString());

    LOGGER(trace) << "TxModel::signTx - signature(s) added. raw tx: " << uchar_vector(tx->raw()).getHex() << std::endl;
    update();

    QString msg;
    if (keychainNames.empty())
    {
        msg = tr("No new signatures were added.");
    }
    else
    {
        msg = tr("Signatures added using keychain(s) ") + QString::fromStdString(stdutils::delimited_list(keychainNames, ", ")) + tr(".");
    }
    emit txSigned(msg);
}

void TxModel::sendTx(int row, CoinQ::Network::NetworkSync* networkSync)
{
    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    if (!networkSync || !networkSync->isConnected()) {
        throw std::runtime_error(tr("Must be connected to network to send.").toStdString());
    }

    QStandardItem* typeItem = item(row, 6);
    int type = typeItem->data(Qt::UserRole).toInt();
    if (type == CoinDB::Tx::UNSIGNED) {
        throw std::runtime_error(tr("Transaction must be fully signed before sending.").toStdString());
    }
    else if (type == CoinDB::Tx::PROPAGATED) {
        throw std::runtime_error(tr("Transaction already sent.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    std::shared_ptr<CoinDB::Tx> tx = vault->getTx(txhash);
    Coin::Transaction coin_tx = tx->toCoinCore();
    networkSync->sendTx(coin_tx);

    // TODO: Check transaction has propagated before changing status to PROPAGATED
//    tx->updateStatus(CoinDB::Tx::PROPAGATED);
//    vault->insertTx(tx);

//    update();
    networkSync->getTx(txhash);
}

std::shared_ptr<Tx> TxModel::getTx(int row)
{
    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    return vault->getTx(txhash);
}

void TxModel::deleteTx(int row)
{
    if (row == -1 || row >= rowCount()) {
        throw std::runtime_error(tr("Invalid row.").toStdString());
    }

    QStandardItem* txHashItem = item(row, 8);
    uchar_vector txhash;
    txhash.setHex(txHashItem->text().toStdString());

    vault->deleteTx(txhash);
    update();

    emit txDeleted();
}

QVariant TxModel::data(const QModelIndex& index, int role) const
{
    // Right-align numeric fields
    if (role == Qt::TextAlignmentRole && index.column() >= 3 && index.column() <= 6) {
        return Qt::AlignRight;
    }
    else {
        return QStandardItemModel::data(index, role);
    }
}

Qt::ItemFlags TxModel::flags(const QModelIndex& /*index*/) const
{
    return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}

<|endoftext|>


<commit_before>#include <type/int.hh>

namespace type
{
    Type& Int::instance()
    {
        static Int i;

        return i;
    }

    std::ostream& Int::dump(std::ostream& o) const
    {
        o << "int";

        return o;
    }

    std::string Int::cpp_type() const
    {
        return "__repy_int*";
    }
} // namespace type
<commit_msg>[TYPE] Change cpp_type of type::Int<commit_after>#include <type/int.hh>

namespace type
{
    Type& Int::instance()
    {
        static Int i;

        return i;
    }

    std::ostream& Int::dump(std::ostream& o) const
    {
        o << "int";

        return o;
    }

    std::string Int::cpp_type() const
    {
        return "__repy_int";
    }
} // namespace type
<|endoftext|>


<commit_before>/* vim:set ts=4 sw=4 sts=4 et: */

#include <memory>
#include <igraph/cpp/graph.h>
#include <igraph/cpp/vertex.h>
#include <igraph/cpp/generators/degree_sequence.h>
#include <igraph/cpp/generators/erdos_renyi.h>
#include <netctrl/model.h>

#include "cmd_arguments.h"
#include "graph_util.h"
#include "logging.h"

using namespace igraph;
using namespace netctrl;
using namespace std;

class NetworkControllabilityApp {
private:
    /// Parsed command line arguments
    CommandLineArguments m_args;

    /// Graph being analyzed by the UI
    std::auto_ptr<Graph> m_pGraph;

    /// Controllability model being calculated on the graph
    std::auto_ptr<ControllabilityModel> m_pModel;

public:
    LOGGING_FUNCTION(debug, 2);
    LOGGING_FUNCTION(info, 1);
    LOGGING_FUNCTION(error, 0);

    /// Constructor
    NetworkControllabilityApp() : m_pGraph(0), m_pModel(0) {}

    /// Returns whether we are running in quiet mode
    bool isQuiet() {
        return m_args.verbosity < 1;
    }

    /// Returns whether we are running in verbose mode
    bool isVerbose() {
        return m_args.verbosity > 1;
    }

    /// Loads a graph from the given file
    /**
     * If the name of the file is "-", the file is assumed to be the
     * standard input.
     */
    std::auto_ptr<Graph> loadGraph(const std::string& filename) {
        std::auto_ptr<Graph> result;

        if (filename == "-") {
            result.reset(new Graph(GraphUtil::readGraph(stdin, GRAPH_FORMAT_EDGELIST)));
        } else {
            result.reset(new Graph(GraphUtil::readGraph(filename)));
            result->setAttribute("filename", filename);
        }

        return result;
    }

    /// Runs the user interface
    int run(int argc, char** argv) {
        m_args.parse(argc, argv);

        info(">> loading graph: %s", m_args.inputFile.c_str());
        m_pGraph = loadGraph(m_args.inputFile);
        info(">> graph is %s and has %ld vertices and %ld edges",
             m_pGraph->isDirected() ? "directed" : "undirected",
             (long)m_pGraph->vcount(), (long)m_pGraph->ecount());

        switch (m_args.modelType) {
            case LIU_MODEL:
                m_pModel.reset(new LiuControllabilityModel(m_pGraph.get()));
                break;
            case SWITCHBOARD_MODEL:
                m_pModel.reset(new SwitchboardControllabilityModel(m_pGraph.get()));
                break;
        }

        switch (m_args.operationMode) {
            case MODE_DRIVER_NODES:
                return runDriverNodes();

            case MODE_STATISTICS:
                return runStatistics();

            case MODE_SIGNIFICANCE:
                return runSignificance();

            default:
                return 1;
        }
    }

    /// Runs the driver node calculation mode
    int runDriverNodes() {
        info(">> calculating control paths and driver nodes");
        m_pModel->calculate();

        Vector driver_nodes = m_pModel->driverNodes();
        info(">> found %d driver node(s)", driver_nodes.size());
        for (Vector::const_iterator it = driver_nodes.begin(); it != driver_nodes.end(); it++) {
            any name(m_pGraph->vertex(*it).getAttribute("name", (long int)*it));
            if (name.type() == typeid(std::string)) {
                cout << name.as<std::string>() << '\n';
            } else {
                cout << name.as<long int>() << '\n';
            }
        }

        return 0;
    }

    /// Runs the signficance calculation mode
    int runSignificance() {
        size_t observedDriverNodeCount;
        size_t numTrials = 100, i;
        float numNodes = m_pGraph->vcount();
        Vector counts;

        info(">> calculating control paths and driver nodes");
        m_pModel->calculate();

        observedDriverNodeCount = m_pModel->driverNodes().size();
        info(">> found %d driver node(s)", observedDriverNodeCount);
        cout << "Observed\t" << observedDriverNodeCount / numNodes << '\n';

        // Testing Erdos-Renyi null model
        info(">> testing Erdos-Renyi null model");
        counts.clear();
        for (i = 0; i < numTrials; i++) {
            Graph graph = igraph::erdos_renyi_game_gnm(
                    numNodes, m_pGraph->ecount(),
                    m_pGraph->isDirected(), false);

            std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());
            pModel->setGraph(&graph);
            pModel->calculate();

            counts.push_back(pModel->driverNodes().size() / numNodes);
        }
        counts.sort();
        cout << "ER\t" << counts.sum() / counts.size() << '\n';

        // Testing configuration model
        info(">> testing configuration model");
        counts.clear();
        for (i = 0; i < numTrials; i++) {
            Graph graph = igraph::degree_sequence_game(
                    m_pGraph->degree(V(m_pGraph.get()), IGRAPH_OUT),
                    m_pGraph->degree(V(m_pGraph.get()), IGRAPH_IN),
                    IGRAPH_DEGSEQ_SIMPLE);

            std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());
            pModel->setGraph(&graph);
            pModel->calculate();

            counts.push_back(pModel->driverNodes().size() / numNodes);
        }
        counts.sort();
        cout << "Configuration\t" << counts.sum() / counts.size() << '\n';

        return 0;
    }

    /// Runs the general statistics calculation mode
    int runStatistics() {
        float n = m_pGraph->vcount();
        float m = m_pGraph->ecount();

        info(">> calculating control paths and driver nodes");
        m_pModel->calculate();

        Vector driver_nodes = m_pModel->driverNodes();
        info(">> found %d driver node(s)", driver_nodes.size());

        cout << "Fraction of driver nodes = " << driver_nodes.size() / n << '\n';

        Vector edge_classes = m_pModel->changesInDriverNodesAfterEdgeRemoval();
        if (edge_classes.size() == m && !edge_classes.empty()) {
            long int num_redundant = 0, num_ordinary = 0, num_critical = 0;
            for (long int i = 0; i < m; i++) {
                if (edge_classes[i] < 0)
                    num_redundant++;
                else if (edge_classes[i] == 0)
                    num_ordinary++;
                else
                    num_critical++;
            }
            cout << "Fraction of redundant edges = " << num_redundant / m << '\n';
            cout << "Fraction of ordinary edges = "  << num_ordinary  / m << '\n';
            cout << "Fraction of critical edges = "  << num_critical  / m << '\n';
        }

        return 0;
    }

};

int main(int argc, char** argv) {
    NetworkControllabilityApp app;

    igraph::AttributeHandler::attach();
    return app.run(argc, argv);
}

<commit_msg>compressed stats output<commit_after>/* vim:set ts=4 sw=4 sts=4 et: */

#include <memory>
#include <igraph/cpp/graph.h>
#include <igraph/cpp/vertex.h>
#include <igraph/cpp/generators/degree_sequence.h>
#include <igraph/cpp/generators/erdos_renyi.h>
#include <netctrl/model.h>

#include "cmd_arguments.h"
#include "graph_util.h"
#include "logging.h"

using namespace igraph;
using namespace netctrl;
using namespace std;

class NetworkControllabilityApp {
private:
    /// Parsed command line arguments
    CommandLineArguments m_args;

    /// Graph being analyzed by the UI
    std::auto_ptr<Graph> m_pGraph;

    /// Controllability model being calculated on the graph
    std::auto_ptr<ControllabilityModel> m_pModel;

public:
    LOGGING_FUNCTION(debug, 2);
    LOGGING_FUNCTION(info, 1);
    LOGGING_FUNCTION(error, 0);

    /// Constructor
    NetworkControllabilityApp() : m_pGraph(0), m_pModel(0) {}

    /// Returns whether we are running in quiet mode
    bool isQuiet() {
        return m_args.verbosity < 1;
    }

    /// Returns whether we are running in verbose mode
    bool isVerbose() {
        return m_args.verbosity > 1;
    }

    /// Loads a graph from the given file
    /**
     * If the name of the file is "-", the file is assumed to be the
     * standard input.
     */
    std::auto_ptr<Graph> loadGraph(const std::string& filename) {
        std::auto_ptr<Graph> result;

        if (filename == "-") {
            result.reset(new Graph(GraphUtil::readGraph(stdin, GRAPH_FORMAT_EDGELIST)));
        } else {
            result.reset(new Graph(GraphUtil::readGraph(filename)));
            result->setAttribute("filename", filename);
        }

        return result;
    }

    /// Runs the user interface
    int run(int argc, char** argv) {
        m_args.parse(argc, argv);

        info(">> loading graph: %s", m_args.inputFile.c_str());
        m_pGraph = loadGraph(m_args.inputFile);
        info(">> graph is %s and has %ld vertices and %ld edges",
             m_pGraph->isDirected() ? "directed" : "undirected",
             (long)m_pGraph->vcount(), (long)m_pGraph->ecount());

        switch (m_args.modelType) {
            case LIU_MODEL:
                m_pModel.reset(new LiuControllabilityModel(m_pGraph.get()));
                break;
            case SWITCHBOARD_MODEL:
                m_pModel.reset(new SwitchboardControllabilityModel(m_pGraph.get()));
                break;
        }

        switch (m_args.operationMode) {
            case MODE_DRIVER_NODES:
                return runDriverNodes();

            case MODE_STATISTICS:
                return runStatistics();

            case MODE_SIGNIFICANCE:
                return runSignificance();

            default:
                return 1;
        }
    }

    /// Runs the driver node calculation mode
    int runDriverNodes() {
        info(">> calculating control paths and driver nodes");
        m_pModel->calculate();

        Vector driver_nodes = m_pModel->driverNodes();
        info(">> found %d driver node(s)", driver_nodes.size());
        for (Vector::const_iterator it = driver_nodes.begin(); it != driver_nodes.end(); it++) {
            any name(m_pGraph->vertex(*it).getAttribute("name", (long int)*it));
            if (name.type() == typeid(std::string)) {
                cout << name.as<std::string>() << '\n';
            } else {
                cout << name.as<long int>() << '\n';
            }
        }

        return 0;
    }

    /// Runs the signficance calculation mode
    int runSignificance() {
        size_t observedDriverNodeCount;
        size_t numTrials = 100, i;
        float numNodes = m_pGraph->vcount();
        Vector counts;

        info(">> calculating control paths and driver nodes");
        m_pModel->calculate();

        observedDriverNodeCount = m_pModel->driverNodes().size();
        info(">> found %d driver node(s)", observedDriverNodeCount);
        cout << "Observed\t" << observedDriverNodeCount / numNodes << '\n';

        // Testing Erdos-Renyi null model
        info(">> testing Erdos-Renyi null model");
        counts.clear();
        for (i = 0; i < numTrials; i++) {
            Graph graph = igraph::erdos_renyi_game_gnm(
                    numNodes, m_pGraph->ecount(),
                    m_pGraph->isDirected(), false);

            std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());
            pModel->setGraph(&graph);
            pModel->calculate();

            counts.push_back(pModel->driverNodes().size() / numNodes);
        }
        counts.sort();
        cout << "ER\t" << counts.sum() / counts.size() << '\n';

        // Testing configuration model
        info(">> testing configuration model");
        counts.clear();
        for (i = 0; i < numTrials; i++) {
            Graph graph = igraph::degree_sequence_game(
                    m_pGraph->degree(V(m_pGraph.get()), IGRAPH_OUT),
                    m_pGraph->degree(V(m_pGraph.get()), IGRAPH_IN),
                    IGRAPH_DEGSEQ_SIMPLE);

            std::auto_ptr<ControllabilityModel> pModel(m_pModel->clone());
            pModel->setGraph(&graph);
            pModel->calculate();

            counts.push_back(pModel->driverNodes().size() / numNodes);
        }
        counts.sort();
        cout << "Configuration\t" << counts.sum() / counts.size() << '\n';

        return 0;
    }

    /// Runs the general statistics calculation mode
    int runStatistics() {
        float n = m_pGraph->vcount();
        float m = m_pGraph->ecount();
        long int num_driver;
        long int num_redundant = 0, num_ordinary = 0, num_critical = 0;

        info(">> calculating control paths and driver nodes");
        m_pModel->calculate();
        num_driver = m_pModel->driverNodes().size();

        info(">> classifying edges");
        Vector edge_classes = m_pModel->changesInDriverNodesAfterEdgeRemoval();
        if (edge_classes.size() == m && !edge_classes.empty()) {
            for (long int i = 0; i < m; i++) {
                if (edge_classes[i] < 0)
                    num_redundant++;
                else if (edge_classes[i] == 0)
                    num_ordinary++;
                else
                    num_critical++;
            }
        }

        cout << num_driver << ' ' << num_redundant << ' '
             << num_ordinary << ' ' << num_critical << '\n';
        cout << num_driver / n << ' ' << num_redundant / m << ' '
             << num_ordinary / m << ' ' << num_critical / m << '\n';

        return 0;
    }

};

int main(int argc, char** argv) {
    NetworkControllabilityApp app;

    igraph::AttributeHandler::attach();
    return app.run(argc, argv);
}

<|endoftext|>


<commit_before>#include<malloc.h>
#include<stdio.h>
#include <iostream>

using namespace std;
#define OK 0
#define ERROR 1
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量

typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码，如OK等

struct SqStack
{
     SElemType *base; // 在栈构造之前和销毁之后，base的值为NULL
     SElemType *top; // 栈顶指针
     int stacksize;  // 当前已分配的存储空间，以元素为单位

     SqStack()
	{
	// 构造一个空栈S，该栈预定义大小为STACK_INIT_SIZE
	// 请补全代码
		base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
		if(base==NULL)return;
		top=base+1;
		stacksize=STACK_INIT_SIZE;
		//printf("DDD");
		return;
	}

	Status Push(SElemType e)
	{
		// 在栈S中插入元素e为新的栈顶元素
		// 请补全代码
		if(top-base>=stacksize*4){

			base=(SElemType *) realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElemType));

			if(base==NULL){

				return ERROR;
			}
		}else{

			*top=e;
			top++;
		}

		return OK;

	}

	Status Pop(SElemType &e)
	{
		// 若栈不空，则删除S的栈顶元素，用e返回其值，并返回OK；否则返回ERROR
		// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(--top);

		return OK;
	}

	Status GetTop(SElemType &e)
	{
	// 若栈不空，则用e返回S的栈顶元素，并返回OK；否则返回ERROR
	// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(top-1);

		return OK;

	}

	int StackLength()
	{
	// 返回栈S的元素个数
	// 请补全代码

		return top-base-1;

	}

	Status StackTraverse(void fn(SElemType& e))
	{
	// 从栈顶到栈底依次输出栈中的每个元素
		SElemType *p = (SElemType *)malloc(sizeof(SElemType));
		p = top;        //请填空
		if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
		else
		{
			printf("The Stack is: ");
			p--;
			while(p-base>=1)            //请填空
			{
				printf("%d ", *p);
				p--;               //请填空
			}
		}
		printf("\n");
		return OK;
	}
}; // 顺序栈

void fun(SElemType &e){

	printf("%d",e);
}

int main()
{
    int a;
    SqStack S;
	SElemType e;

	long long n;

	cin>>n;

	while(n>0){

		S.Push(n%8);
		n/=8;
	}

	S.StackTraverse(fun);

}
<commit_msg>update uoj8585<commit_after>#include<malloc.h>
#include<stdio.h>
#include <iostream>

using namespace std;
#define OK 0
#define ERROR 1
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量

typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码，如OK等

struct SqStack
{
     SElemType *base; // 在栈构造之前和销毁之后，base的值为NULL
     SElemType *top; // 栈顶指针
     int stacksize;  // 当前已分配的存储空间，以元素为单位

     SqStack()
	{
	// 构造一个空栈S，该栈预定义大小为STACK_INIT_SIZE
	// 请补全代码
		base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
		if(base==NULL)return;
		top=base+1;
		stacksize=STACK_INIT_SIZE;
		//printf("DDD");
		return;
	}

	Status Push(SElemType e)
	{
		// 在栈S中插入元素e为新的栈顶元素
		// 请补全代码
		if(top-base>=stacksize*4){

			base=(SElemType *) realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElemType));

			if(base==NULL){

				return ERROR;
			}
		}else{

			*top=e;
			top++;
		}

		return OK;

	}

	Status Pop(SElemType &e)
	{
		// 若栈不空，则删除S的栈顶元素，用e返回其值，并返回OK；否则返回ERROR
		// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(--top);

		return OK;
	}

	Status GetTop(SElemType &e)
	{
	// 若栈不空，则用e返回S的栈顶元素，并返回OK；否则返回ERROR
	// 请补全代码
		if( top-base<=1){
			return ERROR;
		}

		e=*(top-1);

		return OK;

	}

	int StackLength()
	{
	// 返回栈S的元素个数
	// 请补全代码

		return top-base-1;

	}

	Status StackTraverse(void fn(SElemType& e))
	{
	// 从栈顶到栈底依次输出栈中的每个元素
		SElemType *p = (SElemType *)malloc(sizeof(SElemType));
		p = top;        //请填空
		if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
		else
		{

			p--;
			while(p-base>=1)            //请填空
			{
				fn(*p);
				p--;               //请填空
			}
		}
		printf("\n");
		return OK;
	}
}; // 顺序栈

void fun(SElemType &e){

	printf("%d",e);
}

int main()
{
    int a;
    SqStack S;
	SElemType e;

	long long n;

	cin>>n;

	while(n>0){

		S.Push(n%8);
		n/=8;
	}

	S.StackTraverse(fun);

}
<|endoftext|>


<commit_before>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * version.cpp
 * - Compiler version number
 */
#include <version.hpp>
#include <sstream>

#define VERSION_MAJOR   0
#define VERSION_MINOR   8
#define VERSION_PATCH   1

#ifdef _WIN32
# define VERSION_GIT_ISDIRTY    1
# define VERSION_GIT_FULLHASH   "unknown"
# define VERSION_GIT_SHORTHASH   "msvc"
# define VERSION_BUILDTIME  "unknown"
# define VERSION_GIT_BRANCH "unknown"
#endif

unsigned int giVersion_Major = VERSION_MAJOR;
unsigned int giVersion_Minor = VERSION_MINOR;
unsigned int giVersion_Patch = VERSION_PATCH;
bool gbVersion_GitDirty = VERSION_GIT_ISDIRTY;
const char* gsVersion_GitHash = VERSION_GIT_FULLHASH;
const char* gsVersion_GitShortHash = VERSION_GIT_SHORTHASH;
const char* gsVersion_BuildTime = VERSION_BUILDTIME;

::std::string Version_GetString()
{
    ::std::stringstream ss;
    ss << "v" << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << " " << VERSION_GIT_BRANCH << ":" << VERSION_GIT_SHORTHASH;
    return ss.str();
}
<commit_msg>Version - Bump to 0.9<commit_after>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * version.cpp
 * - Compiler version number
 */
#include <version.hpp>
#include <sstream>

#define VERSION_MAJOR   0
#define VERSION_MINOR   9
#define VERSION_PATCH   0

#ifdef _WIN32
# define VERSION_GIT_ISDIRTY    1
# define VERSION_GIT_FULLHASH   "unknown"
# define VERSION_GIT_SHORTHASH   "msvc"
# define VERSION_BUILDTIME  "unknown"
# define VERSION_GIT_BRANCH "unknown"
#endif

unsigned int giVersion_Major = VERSION_MAJOR;
unsigned int giVersion_Minor = VERSION_MINOR;
unsigned int giVersion_Patch = VERSION_PATCH;
bool gbVersion_GitDirty = VERSION_GIT_ISDIRTY;
const char* gsVersion_GitHash = VERSION_GIT_FULLHASH;
const char* gsVersion_GitShortHash = VERSION_GIT_SHORTHASH;
const char* gsVersion_BuildTime = VERSION_BUILDTIME;

::std::string Version_GetString()
{
    ::std::stringstream ss;
    ss << "v" << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << " " << VERSION_GIT_BRANCH << ":" << VERSION_GIT_SHORTHASH;
    return ss.str();
}
<|endoftext|>


<commit_before>#include <windows.h>
#include <math.h>
#include <list>

const float PI = 3.141592653589793238;
const LPCTSTR lpszClass = L"cxdodge";
const int WIDTH = 320, HEIGHT = 240;

LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam);

inline void DrawPointEllipse(HDC hdc, int x, int y, int radius)
{
	Ellipse(hdc, x - radius, y - radius, x + radius, y + radius);
}
template <typename T>
inline T pow2(const T &x) { return x*x; }

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInst, LPSTR lpCmdParam, int nCmdShow)
{
	WNDCLASS wc;
	HWND hWnd;
	MSG msg;

	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hbrBackground = NULL;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hInstance = hInstance;
	wc.lpfnWndProc = WndProc;
	wc.lpszClassName = lpszClass;
	wc.lpszMenuName = NULL;
	wc.style = CS_HREDRAW | CS_VREDRAW;
	RegisterClass(&wc);

	hWnd = CreateWindow(lpszClass, lpszClass,
		WS_BORDER | WS_OVERLAPPED | WS_SYSMENU,
		CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT,
		NULL, (HMENU)NULL, hInstance, NULL);
	if (hWnd != NULL)
	{
		ShowWindow(hWnd, nCmdShow);

		while (GetMessage(&msg, NULL, 0, 0))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

		return msg.wParam;
	}
	else
	{
		return -1;
	}
}

struct Bullet
{
	float x, y;
	float dx, dy;
};

HBITMAP hBitmap = NULL;
HBRUSH hbrBullet, hbrPlayer;

bool bLose = false;
std::list<Bullet> bullets;
POINT player;

const int DRAW_RADIUS = 3;
const int HIT_RADIUS = 1;

const int PLAYER_SPEED = 1;
const int BULLET_SPEED = 1;

const int CREATION_GAP = 75;

const int MOVE_TIMER_ID = 1;
const int MOVE_TIMER_FREQ = 13;
const int CREATION_TIMER_ID = 2;
const int CREATION_TIMER_FREQ = 675;

LRESULT OnCreate(HWND hWnd, WPARAM wParam, LPARAM lParam);
LRESULT OnPaint(HWND hWnd, WPARAM wParam, LPARAM lParam);
LRESULT OnTimer(HWND hWnd, WPARAM wParam, LPARAM lParam);
LRESULT OnDestroy(HWND hWnd, WPARAM wParam, LPARAM lParam);

void CreateBullet(const RECT &rt, int x, int y);
bool CheckLose();

LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
#define ONMSG(msg, fn) case msg: return fn(hWnd, wParam, lParam)
	switch (iMsg)
	{
		ONMSG(WM_CREATE, OnCreate);
		ONMSG(WM_PAINT, OnPaint);
		ONMSG(WM_TIMER, OnTimer);
		ONMSG(WM_DESTROY, OnDestroy);
	}
#undef ONMSG
	return DefWindowProc(hWnd, iMsg, wParam, lParam);
}

LRESULT OnCreate(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	HBITMAP hOldBit;
	HDC hdc, hMemDC;
	RECT rt;

	hdc = GetDC(hWnd);
	hMemDC = CreateCompatibleDC(hdc);
	hBitmap = CreateCompatibleBitmap(hdc, WIDTH, HEIGHT);
	hOldBit = (HBITMAP)SelectObject(hMemDC, hBitmap);
	GetClientRect(hWnd, &rt);
	FillRect(hMemDC, &rt, (HBRUSH)GetStockObject(BLACK_BRUSH));
	SelectObject(hMemDC, hOldBit);
	DeleteDC(hMemDC);
	ReleaseDC(hWnd, hdc);

	hbrBullet = CreateSolidBrush(RGB(255, 255, 255));
	hbrPlayer = CreateSolidBrush(RGB(0, 255, 52));

	SetTimer(hWnd, MOVE_TIMER_ID, MOVE_TIMER_FREQ, NULL);
	SetTimer(hWnd, CREATION_TIMER_ID, CREATION_TIMER_FREQ, NULL);

	player.x = rt.right / 2;
	player.y = rt.bottom / 2;

	return 0;
}

LRESULT OnPaint(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	BeginPaint(hWnd, &ps);

	if (hBitmap != NULL)
	{
		HBITMAP hOldBit;
		HDC hdc, hMemDC;
		RECT rt;

		hdc = GetDC(hWnd);
		hMemDC = CreateCompatibleDC(hdc);
		hBitmap = CreateCompatibleBitmap(hdc, WIDTH, HEIGHT);
		hOldBit = (HBITMAP)SelectObject(hMemDC, hBitmap);

		GetClientRect(hWnd, &rt);
		FillRect(hMemDC, &rt, (HBRUSH)GetStockObject(BLACK_BRUSH));

		HPEN hOldPen = (HPEN)SelectObject(hMemDC, GetStockObject(NULL_PEN));
		HBRUSH hOldBrush = (HBRUSH)SelectObject(hMemDC, hbrPlayer);
		DrawPointEllipse(hMemDC, player.x, player.y, DRAW_RADIUS);

		SelectObject(hMemDC, hbrBullet);
		for (const Bullet &b : bullets)
			DrawPointEllipse(hMemDC, (int)b.x, (int)b.y, DRAW_RADIUS);

		SelectObject(hMemDC, hOldBrush);
		SelectObject(hMemDC, hOldPen);

		BitBlt(hdc, 0, 0, WIDTH, HEIGHT, hMemDC, 0, 0, SRCCOPY);
		SelectObject(hMemDC, hOldBit);
		DeleteDC(hMemDC);
		ReleaseDC(hWnd, hdc);
	}

	EndPaint(hWnd, &ps);
	return 0;
}

LRESULT OnTimer(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	if (bLose)
		return 0;

	RECT rt;
	int x, y;

	switch (wParam)
	{
		case MOVE_TIMER_ID:
			if (GetAsyncKeyState(VK_LEFT) < 0)
				player.x -= PLAYER_SPEED;
			if (GetAsyncKeyState(VK_UP) < 0)
				player.y -= PLAYER_SPEED;
			if (GetAsyncKeyState(VK_RIGHT) < 0)
				player.x += PLAYER_SPEED;
			if (GetAsyncKeyState(VK_DOWN) < 0)
				player.y += PLAYER_SPEED;

			for (Bullet &b : bullets)
			{
				b.x += b.dx;
				b.y += b.dy;
			}

			bLose = CheckLose();
			InvalidateRect(hWnd, NULL, FALSE);
			break;
		case CREATION_TIMER_ID:
			GetClientRect(hWnd, &rt);
			for (x = 0; x < rt.right; x += CREATION_GAP)
			{
				CreateBullet(rt, x, 0);
			}
			for (y = x - rt.right; y < rt.bottom; y += CREATION_GAP)
			{
				CreateBullet(rt, rt.right, y);
			}
			for (x = rt.right - (y - rt.bottom); x >= 0; x -= CREATION_GAP)
			{
				CreateBullet(rt, x, rt.bottom);
			}
			for (y = rt.right - (-x); y >= 0; y -= CREATION_GAP)
			{
				CreateBullet(rt, 0, y);
			}

			bLose = CheckLose();
			InvalidateRect(hWnd, NULL, FALSE);
			break;
	}
	return 0;
}

// x = a cost
// y = b sint
void CreateBullet(const RECT &rt, int x, int y)
{
	Bullet b;
	b.x = x;
	b.y = y;

	float d_x = player.x - x;
	float d_y = player.y - y;
	float d_length = sqrt(pow2(d_x) + pow2(d_y));

	//float a = (float)rt.bottom / rt.right;
	//float d_y0 = d_y / a;
	//float theta = fmod(atan2(d_y0, d_x), PI / 2);
	float speed = BULLET_SPEED/* * pow2(tan(-fabs(theta - PI / 4)))*/;

	b.dx = d_x / d_length * speed;
	b.dy = d_y / d_length * speed;

	bullets.push_back(b);
}

bool CheckLose()
{
	for (Bullet &b : bullets)
	{
		if (pow2((int)b.x - player.x) + pow2((int)b.y - player.y) <= pow2(HIT_RADIUS))
		{
			return true;
		}
	}
	return false;
}

LRESULT OnDestroy(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	KillTimer(hWnd, MOVE_TIMER_ID);
	KillTimer(hWnd, CREATION_TIMER_ID);

	DeleteObject(hBitmap);
	hBitmap = NULL;

	PostQuitMessage(0);
	return 0;
}
<commit_msg>working..<commit_after>#include <windows.h>
#include <math.h>
#include <list>

const float PI = 3.141592653589793238;
const LPCTSTR lpszClass = L"cxdodge";
const int WIDTH = 320, HEIGHT = 240;

LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam);

inline void DrawPointEllipse(HDC hdc, int x, int y, int radius)
{
	Ellipse(hdc, x - radius, y - radius, x + radius, y + radius);
}
template <typename T>
inline T pow2(const T &x) { return x*x; }

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInst, LPSTR lpCmdParam, int nCmdShow)
{
	WNDCLASS wc;
	HWND hWnd;
	MSG msg;

	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hbrBackground = NULL;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hInstance = hInstance;
	wc.lpfnWndProc = WndProc;
	wc.lpszClassName = lpszClass;
	wc.lpszMenuName = NULL;
	wc.style = CS_HREDRAW | CS_VREDRAW;
	RegisterClass(&wc);

	hWnd = CreateWindow(lpszClass, lpszClass,
		WS_BORDER | WS_OVERLAPPED | WS_SYSMENU,
		CW_USEDEFAULT, CW_USEDEFAULT, WIDTH, HEIGHT,
		NULL, (HMENU)NULL, hInstance, NULL);
	if (hWnd != NULL)
	{
		ShowWindow(hWnd, nCmdShow);

		while (GetMessage(&msg, NULL, 0, 0))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

		return msg.wParam;
	}
	else
	{
		return -1;
	}
}

struct Bullet
{
	float x, y;
	float dx, dy;
};

HBITMAP hBitmap = NULL;
HBRUSH hbrBullet, hbrPlayer;

DWORD StartTick;
bool bLose;
std::list<Bullet> bullets;
POINT player;

const int DRAW_RADIUS = 3;
const int HIT_RADIUS = 1;

const int PLAYER_SPEED = 1;
const int BULLET_SPEED = 1;

const int CREATION_GAP = 75;

const int MOVE_TIMER_ID = 1;
const int MOVE_TIMER_FREQ = 13;
const int CREATION_TIMER_ID = 2;
const int CREATION_TIMER_FREQ = 675;

LRESULT OnCreate(HWND hWnd, WPARAM wParam, LPARAM lParam);
LRESULT OnPaint(HWND hWnd, WPARAM wParam, LPARAM lParam);
LRESULT OnTimer(HWND hWnd, WPARAM wParam, LPARAM lParam);
LRESULT OnDestroy(HWND hWnd, WPARAM wParam, LPARAM lParam);

void Reset(const RECT &rt);
void CreateBullet(const RECT &rt, int x, int y);
bool CheckLose();

LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
#define ONMSG(msg, fn) case msg: return fn(hWnd, wParam, lParam)
	switch (iMsg)
	{
		ONMSG(WM_CREATE, OnCreate);
		ONMSG(WM_PAINT, OnPaint);
		ONMSG(WM_TIMER, OnTimer);
		ONMSG(WM_DESTROY, OnDestroy);
	}
#undef ONMSG
	return DefWindowProc(hWnd, iMsg, wParam, lParam);
}

LRESULT OnCreate(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	HBITMAP hOldBit;
	HDC hdc, hMemDC;
	RECT rt;

	hdc = GetDC(hWnd);
	hMemDC = CreateCompatibleDC(hdc);
	hBitmap = CreateCompatibleBitmap(hdc, WIDTH, HEIGHT);
	hOldBit = (HBITMAP)SelectObject(hMemDC, hBitmap);
	GetClientRect(hWnd, &rt);
	FillRect(hMemDC, &rt, (HBRUSH)GetStockObject(BLACK_BRUSH));
	SelectObject(hMemDC, hOldBit);
	DeleteDC(hMemDC);
	ReleaseDC(hWnd, hdc);

	hbrBullet = CreateSolidBrush(RGB(255, 255, 255));
	hbrPlayer = CreateSolidBrush(RGB(0, 255, 255));

	SetTimer(hWnd, MOVE_TIMER_ID, MOVE_TIMER_FREQ, NULL);
	SetTimer(hWnd, CREATION_TIMER_ID, CREATION_TIMER_FREQ, NULL);

	Reset(rt);

	return 0;
}

void Reset(const RECT &rt)
{
	StartTick = GetTickCount();
	bLose = false;
	player.x = rt.right / 2;
	player.y = rt.bottom / 2;
}

LRESULT OnPaint(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	BeginPaint(hWnd, &ps);

	if (hBitmap != NULL)
	{
		HBITMAP hOldBit;
		HDC hdc, hMemDC;
		RECT rt;

		hdc = GetDC(hWnd);
		hMemDC = CreateCompatibleDC(hdc);
		hBitmap = CreateCompatibleBitmap(hdc, WIDTH, HEIGHT);
		hOldBit = (HBITMAP)SelectObject(hMemDC, hBitmap);

		GetClientRect(hWnd, &rt);
		FillRect(hMemDC, &rt, (HBRUSH)GetStockObject(BLACK_BRUSH));

		HPEN hOldPen = (HPEN)SelectObject(hMemDC, GetStockObject(NULL_PEN));
		HBRUSH hOldBrush = (HBRUSH)SelectObject(hMemDC, hbrPlayer);
		DrawPointEllipse(hMemDC, player.x, player.y, DRAW_RADIUS);

		SelectObject(hMemDC, hbrBullet);
		for (const Bullet &b : bullets)
			DrawPointEllipse(hMemDC, (int)b.x, (int)b.y, DRAW_RADIUS);

		SelectObject(hMemDC, hOldBrush);
		SelectObject(hMemDC, hOldPen);

		SetTextColor(hMemDC, RGB(0, 255, 52));
		TCHAR str[256];
		DWORD time = GetTickCount() - StartTick;
		wsprintf(str, L"%d.%03d sec", time / 1000, time % 1000);
		if (bLose)
		{
			lstrcat(str, L" - click for restart");
		}
		TextOut(hMemDC, 0, 0, str, lstrlen(str));

		BitBlt(hdc, 0, 0, WIDTH, HEIGHT, hMemDC, 0, 0, SRCCOPY);
		SelectObject(hMemDC, hOldBit);
		DeleteDC(hMemDC);
		ReleaseDC(hWnd, hdc);
	}

	EndPaint(hWnd, &ps);
	return 0;
}

LRESULT OnTimer(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	if (bLose)
		return 0;

	RECT rt;
	int x, y;

	switch (wParam)
	{
		case MOVE_TIMER_ID:
			if (GetAsyncKeyState(VK_LEFT) < 0)
				player.x -= PLAYER_SPEED;
			if (GetAsyncKeyState(VK_UP) < 0)
				player.y -= PLAYER_SPEED;
			if (GetAsyncKeyState(VK_RIGHT) < 0)
				player.x += PLAYER_SPEED;
			if (GetAsyncKeyState(VK_DOWN) < 0)
				player.y += PLAYER_SPEED;

			for (Bullet &b : bullets)
			{
				b.x += b.dx;
				b.y += b.dy;
			}

			bLose = CheckLose();
			InvalidateRect(hWnd, NULL, FALSE);
			break;
		case CREATION_TIMER_ID:
			GetClientRect(hWnd, &rt);
			for (x = 0; x < rt.right; x += CREATION_GAP)
			{
				CreateBullet(rt, x, 0);
			}
			for (y = x - rt.right; y < rt.bottom; y += CREATION_GAP)
			{
				CreateBullet(rt, rt.right, y);
			}
			for (x = rt.right - (y - rt.bottom); x >= 0; x -= CREATION_GAP)
			{
				CreateBullet(rt, x, rt.bottom);
			}
			for (y = rt.right - (-x); y >= 0; y -= CREATION_GAP)
			{
				CreateBullet(rt, 0, y);
			}

			bLose = CheckLose();
			InvalidateRect(hWnd, NULL, FALSE);
			break;
	}
	return 0;
}

// x = a cost
// y = b sint
void CreateBullet(const RECT &rt, int x, int y)
{
	Bullet b;
	b.x = x;
	b.y = y;

	float d_x = player.x - x;
	float d_y = player.y - y;
	float d_length = sqrt(pow2(d_x) + pow2(d_y));

	//float a = (float)rt.bottom / rt.right;
	//float d_y0 = d_y / a;
	//float theta = fmod(atan2(d_y0, d_x), PI / 2);
	float speed = BULLET_SPEED/* * pow2(tan(-fabs(theta - PI / 4)))*/;

	b.dx = d_x / d_length * speed;
	b.dy = d_y / d_length * speed;

	bullets.push_back(b);
}

bool CheckLose()
{
	for (Bullet &b : bullets)
	{
		if (pow2((int)b.x - player.x) + pow2((int)b.y - player.y) <= pow2(HIT_RADIUS))
		{
			return true;
		}
	}
	return false;
}

LRESULT OnDestroy(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
	KillTimer(hWnd, MOVE_TIMER_ID);
	KillTimer(hWnd, CREATION_TIMER_ID);

	DeleteObject(hBitmap);
	hBitmap = NULL;

	PostQuitMessage(0);
	return 0;
}
<|endoftext|>


<commit_before>/*
   Copyright 2015 Rachael Harding

   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

   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 "global.h"
#include "ycsb.h"
#include "tpcc.h"
#include "thread.h"
#include "worker_thread.h"
#include "calvin_thread.h"
#include "abort_thread.h"
#include "io_thread.h"
#include "log_thread.h"
#include "manager.h"
#include "math.h"
#include "query.h"
#include "occ.h"
#include "transport.h"
#include "msg_queue.h"
#include "ycsb_query.h"
#include "sequencer.h"
#include "logger.h"
#include "sim_manager.h"
#include "abort_queue.h"
#include "work_queue.h"
#include "maat.h"
#include "client_query.h"

void * f(void *);
void * g(void *);
void * worker(void *);
void * nn_worker(void *);
void * log_worker(void *);
void * send_worker(void *);
void * abort_worker(void *);
void * calvin_lock_worker(void * id);
void * calvin_seq_worker(void * id);
void * calvin_worker(void * id);
void network_test();
void network_test_recv();
void * run_thread(void *);

WorkerThread * worker_thds;
InputThread * input_thds;
OutputThread * output_thds;
AbortThread * abort_thds;
LogThread * log_thds;
#if CC_ALG == CALVIN
CalvinLockThread * calvin_lock_thds;
CalvinSequencerThread * calvin_seq_thds;
#endif

// defined in parser.cpp
void parser(int argc, char * argv[]);

int main(int argc, char* argv[])
{
	// 0. initialize global data structure
	parser(argc, argv);
#if SEED != 0
  uint64_t seed = SEED + g_node_id;
#else
	uint64_t seed = get_sys_clock();
#endif
	srand(seed);
	printf("Random seed: %ld\n",seed);

#if ISOLATION_LEVEL == READ_COMMITTED
  assert(CC_ALG == NO_WAIT);
#endif

	int64_t starttime;
	int64_t endtime;
  starttime = get_server_clock();
  printf("Initializing stats... ");
  fflush(stdout);
	stats.init(g_total_thread_cnt);
  printf("Done\n");
  printf("Initializing global manager... ");
  fflush(stdout);
	glob_manager.init();
  printf("Done\n");
  printf("Initializing transport manager... ");
  fflush(stdout);
	tport_man.init();
  printf("Done\n");
  fflush(stdout);
	Workload * m_wl;
	switch (WORKLOAD) {
		case YCSB :
			m_wl = new YCSBWorkload; break;
		case TPCC :
			m_wl = new TPCCWorkload; break;
		default:
			assert(false);
	}
	m_wl->init();
	printf("Workload initialized!\n");
  fflush(stdout);
  printf("Initializing simulation... ");
  fflush(stdout);
  simulation = new SimManager;
  simulation->init();
  printf("Done\n");
#if NETWORK_TEST
	tport_man.init(g_node_id,m_wl);
	sleep(3);
	if(g_node_id == 0)
		network_test();
	else if(g_node_id == 1)
		network_test_recv();

	return 0;
#endif

  printf("Initializing work queue... ");
  fflush(stdout);
  work_queue.init();
  printf("Done\n");
  printf("Initializing abort queue... ");
  fflush(stdout);
  abort_queue.init();
  printf("Done\n");
  printf("Initializing message queue... ");
  fflush(stdout);
  msg_queue.init();
  printf("Done\n");
  printf("Initializing transaction manager pool... ");
  fflush(stdout);
  txn_man_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing transaction pool... ");
  fflush(stdout);
  txn_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing row pool... ");
  fflush(stdout);
  row_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing access pool... ");
  fflush(stdout);
  access_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing txn node table pool... ");
  fflush(stdout);
  txn_table_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing query pool... ");
  fflush(stdout);
  qry_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing msg pool... ");
  fflush(stdout);
  msg_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing transaction table... ");
  fflush(stdout);
  txn_table.init();
  printf("Done\n");
#if CC_ALG == CALVIN
  printf("Initializing sequencer... ");
  fflush(stdout);
  seq_man.init(m_wl);
  printf("Done\n");
#endif
#if CC_ALG == MAAT
  printf("Initializing Time Table... ");
  fflush(stdout);
  time_table.init();
  printf("Done\n");
  printf("Initializing MaaT manager... ");
  fflush(stdout);
	maat_man.init();
  printf("Done\n");
#endif
#if LOGGING
  printf("Initializing logger... ");
  fflush(stdout);
  logger.init("logfile.log");
  printf("Done\n");
#endif

#if SERVER_GENERATE_QUERIES
  printf("Initializing client query queue... ");
  fflush(stdout);
  client_query_queue.init(m_wl);
  printf("Done\n");
  fflush(stdout);
#endif

	// 2. spawn multiple threads
	uint64_t thd_cnt = g_thread_cnt;
	uint64_t wthd_cnt = thd_cnt;
	uint64_t rthd_cnt = g_rem_thread_cnt;
	uint64_t sthd_cnt = g_send_thread_cnt;
  uint64_t all_thd_cnt = thd_cnt + rthd_cnt + sthd_cnt + 1;
#if LOGGING
  all_thd_cnt += 1; // logger thread
#endif
#if CC_ALG == CALVIN
  all_thd_cnt += 2; // sequencer + scheduler thread
#endif
  assert(all_thd_cnt == g_this_total_thread_cnt);
  /*
#if CC_ALG == CALVIN
  assert(thd_cnt >= 3);
  wthd_cnt -= 2;
#endif
*/

	pthread_t * p_thds =
		(pthread_t *) malloc(sizeof(pthread_t) * (all_thd_cnt));
	pthread_attr_t attr;
	pthread_attr_init(&attr);

  worker_thds = new WorkerThread[wthd_cnt];
  input_thds = new InputThread[rthd_cnt];
  output_thds = new OutputThread[sthd_cnt];
  abort_thds = new AbortThread[1];
  log_thds = new LogThread[1];
#if CC_ALG == CALVIN
  calvin_lock_thds = new CalvinLockThread[1];
  calvin_seq_thds = new CalvinSequencerThread[1];
#endif
	// query_queue should be the last one to be initialized!!!
	// because it collects txn latency
	//if (WORKLOAD != TEST) {
	//	query_queue.init(m_wl);
	//}
#if CC_ALG == OCC
  printf("Initializing occ lock manager... ");
	occ_man.init();
  printf("Done\n");
#endif

  /*
  printf("Initializing threads... ");
  fflush(stdout);
	for (uint32_t i = 0; i < all_thd_cnt; i++)
		m_thds[i].init(i, g_node_id, m_wl);
  printf("Done\n");
  fflush(stdout);
  */

  endtime = get_server_clock();
  printf("Initialization Time = %ld\n", endtime - starttime);
  fflush(stdout);
	warmup_done = true;
	pthread_barrier_init( &warmup_bar, NULL, all_thd_cnt);

#if SET_AFFINITY
	uint64_t cpu_cnt = 0;
  cpu_set_t cpus;
#endif
	// spawn and run txns again.
	starttime = get_server_clock();

  uint64_t id = 0;
	for (uint64_t i = 0; i < wthd_cnt; i++) {
#if SET_AFFINITY
		CPU_ZERO(&cpus);
    CPU_SET(cpu_cnt, &cpus);
    pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
		cpu_cnt++;
#endif
    assert(id >= 0 && id < wthd_cnt);
    worker_thds[i].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], &attr, run_thread, (void *)&worker_thds[i]);
  }
	for (uint64_t j = 0; j < rthd_cnt ; j++) {
    assert(id >= wthd_cnt && id < wthd_cnt + rthd_cnt);
    input_thds[j].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], NULL, run_thread, (void *)&input_thds[j]);
  }

	for (uint64_t j = 0; j < sthd_cnt; j++) {
    assert(id >= wthd_cnt + rthd_cnt && id < wthd_cnt + rthd_cnt + sthd_cnt);
    output_thds[j].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], NULL, run_thread, (void *)&output_thds[j]);
  }
#if LOGGING
    log_thds[0].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], NULL, run_thread, (void *)&log_thds[0]);
#endif

  abort_thds[0].init(id,g_node_id,m_wl);
  pthread_create(&p_thds[id++], NULL, run_thread, (void *)&abort_thds[0]);

#if CC_ALG == CALVIN
  calvin_lock_thds[0].init(id,g_node_id,m_wl);
  pthread_create(&p_thds[id++], &attr, run_thread, (void *)&calvin_lock_thds[0]);
  calvin_seq_thds[0].init(id,g_node_id,m_wl);
  pthread_create(&p_thds[id++], &attr, run_thread, (void *)&calvin_seq_thds[0]);
#endif

	for (uint64_t i = 0; i < all_thd_cnt ; i++)
		pthread_join(p_thds[i], NULL);

	endtime = get_server_clock();

  printf("PASS! SimTime = %f\n", (float)(endtime - starttime) / BILLION);
  if (STATS_ENABLE)
    stats.print(false);
  //malloc_stats_print(NULL, NULL, NULL);
  printf("\n");
  fflush(stdout);
  // Free things
	//tport_man.shutdown();

  /*
  txn_table.delete_all();
  txn_pool.free_all();
  access_pool.free_all();
  txn_table_pool.free_all();
  msg_pool.free_all();
  qry_pool.free_all();
  */
	return 0;
}

/*
void * worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run();
	return NULL;
}

void * nn_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_remote();
	return NULL;
}

void * log_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_logger();
	return NULL;
}
void * abort_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_abort();
	return NULL;
}

void * send_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_send();
	return NULL;
}

void * calvin_seq_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_calvin_seq();
	return NULL;
}

void * calvin_lock_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_calvin_lock();
	return NULL;
}

void * calvin_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_calvin();
	return NULL;
}
*/

void * run_thread(void * id) {
  Thread * thd = (Thread *) id;
	thd->run();
	return NULL;
}

void network_test() {

      /*
	ts_t start;
	ts_t end;
	ts_t time;
	int bytes;
  float total = 0;
	for (int i = 0; i < 4; ++i) {
		time = 0;
		int num_bytes = (int) pow(10,i);
		printf("Network Bytes: %d\nns: ", num_bytes);
		for(int j = 0;j < 1000; j++) {
			start = get_sys_clock();
			tport_man.simple_send_msg(num_bytes);
			while((bytes = tport_man.simple_recv_msg()) == 0) {}
			end = get_sys_clock();
			assert(bytes == num_bytes);
			time = end-start;
      total += time;
			//printf("%lu\n",time);
		}
		printf("Avg(s): %f\n",total/BILLION/1000);
    fflush(stdout);
		//time = time/1000;
		//printf("Network Bytes: %d, s: %f\n",i,time/BILLION);
		//printf("Network Bytes: %d, ns: %.3f\n",i,time);

	}
      */

}

void network_test_recv() {
  /*
	int bytes;
	while(1) {
		if( (bytes = tport_man.simple_recv_msg()) > 0)
			tport_man.simple_send_msg(bytes);
	}
  */
}
<commit_msg>Allow other locking CC algos to be used in lower isolation levels<commit_after>/*
   Copyright 2015 Rachael Harding

   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

   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 "global.h"
#include "ycsb.h"
#include "tpcc.h"
#include "thread.h"
#include "worker_thread.h"
#include "calvin_thread.h"
#include "abort_thread.h"
#include "io_thread.h"
#include "log_thread.h"
#include "manager.h"
#include "math.h"
#include "query.h"
#include "occ.h"
#include "transport.h"
#include "msg_queue.h"
#include "ycsb_query.h"
#include "sequencer.h"
#include "logger.h"
#include "sim_manager.h"
#include "abort_queue.h"
#include "work_queue.h"
#include "maat.h"
#include "client_query.h"

void * f(void *);
void * g(void *);
void * worker(void *);
void * nn_worker(void *);
void * log_worker(void *);
void * send_worker(void *);
void * abort_worker(void *);
void * calvin_lock_worker(void * id);
void * calvin_seq_worker(void * id);
void * calvin_worker(void * id);
void network_test();
void network_test_recv();
void * run_thread(void *);

WorkerThread * worker_thds;
InputThread * input_thds;
OutputThread * output_thds;
AbortThread * abort_thds;
LogThread * log_thds;
#if CC_ALG == CALVIN
CalvinLockThread * calvin_lock_thds;
CalvinSequencerThread * calvin_seq_thds;
#endif

// defined in parser.cpp
void parser(int argc, char * argv[]);

int main(int argc, char* argv[])
{
	// 0. initialize global data structure
	parser(argc, argv);
#if SEED != 0
  uint64_t seed = SEED + g_node_id;
#else
	uint64_t seed = get_sys_clock();
#endif
	srand(seed);
	printf("Random seed: %ld\n",seed);

	int64_t starttime;
	int64_t endtime;
  starttime = get_server_clock();
  printf("Initializing stats... ");
  fflush(stdout);
	stats.init(g_total_thread_cnt);
  printf("Done\n");
  printf("Initializing global manager... ");
  fflush(stdout);
	glob_manager.init();
  printf("Done\n");
  printf("Initializing transport manager... ");
  fflush(stdout);
	tport_man.init();
  printf("Done\n");
  fflush(stdout);
	Workload * m_wl;
	switch (WORKLOAD) {
		case YCSB :
			m_wl = new YCSBWorkload; break;
		case TPCC :
			m_wl = new TPCCWorkload; break;
		default:
			assert(false);
	}
	m_wl->init();
	printf("Workload initialized!\n");
  fflush(stdout);
  printf("Initializing simulation... ");
  fflush(stdout);
  simulation = new SimManager;
  simulation->init();
  printf("Done\n");
#if NETWORK_TEST
	tport_man.init(g_node_id,m_wl);
	sleep(3);
	if(g_node_id == 0)
		network_test();
	else if(g_node_id == 1)
		network_test_recv();

	return 0;
#endif

  printf("Initializing work queue... ");
  fflush(stdout);
  work_queue.init();
  printf("Done\n");
  printf("Initializing abort queue... ");
  fflush(stdout);
  abort_queue.init();
  printf("Done\n");
  printf("Initializing message queue... ");
  fflush(stdout);
  msg_queue.init();
  printf("Done\n");
  printf("Initializing transaction manager pool... ");
  fflush(stdout);
  txn_man_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing transaction pool... ");
  fflush(stdout);
  txn_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing row pool... ");
  fflush(stdout);
  row_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing access pool... ");
  fflush(stdout);
  access_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing txn node table pool... ");
  fflush(stdout);
  txn_table_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing query pool... ");
  fflush(stdout);
  qry_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing msg pool... ");
  fflush(stdout);
  msg_pool.init(m_wl,0);
  printf("Done\n");
  printf("Initializing transaction table... ");
  fflush(stdout);
  txn_table.init();
  printf("Done\n");
#if CC_ALG == CALVIN
  printf("Initializing sequencer... ");
  fflush(stdout);
  seq_man.init(m_wl);
  printf("Done\n");
#endif
#if CC_ALG == MAAT
  printf("Initializing Time Table... ");
  fflush(stdout);
  time_table.init();
  printf("Done\n");
  printf("Initializing MaaT manager... ");
  fflush(stdout);
	maat_man.init();
  printf("Done\n");
#endif
#if LOGGING
  printf("Initializing logger... ");
  fflush(stdout);
  logger.init("logfile.log");
  printf("Done\n");
#endif

#if SERVER_GENERATE_QUERIES
  printf("Initializing client query queue... ");
  fflush(stdout);
  client_query_queue.init(m_wl);
  printf("Done\n");
  fflush(stdout);
#endif

	// 2. spawn multiple threads
	uint64_t thd_cnt = g_thread_cnt;
	uint64_t wthd_cnt = thd_cnt;
	uint64_t rthd_cnt = g_rem_thread_cnt;
	uint64_t sthd_cnt = g_send_thread_cnt;
  uint64_t all_thd_cnt = thd_cnt + rthd_cnt + sthd_cnt + 1;
#if LOGGING
  all_thd_cnt += 1; // logger thread
#endif
#if CC_ALG == CALVIN
  all_thd_cnt += 2; // sequencer + scheduler thread
#endif
  assert(all_thd_cnt == g_this_total_thread_cnt);
  /*
#if CC_ALG == CALVIN
  assert(thd_cnt >= 3);
  wthd_cnt -= 2;
#endif
*/

	pthread_t * p_thds =
		(pthread_t *) malloc(sizeof(pthread_t) * (all_thd_cnt));
	pthread_attr_t attr;
	pthread_attr_init(&attr);

  worker_thds = new WorkerThread[wthd_cnt];
  input_thds = new InputThread[rthd_cnt];
  output_thds = new OutputThread[sthd_cnt];
  abort_thds = new AbortThread[1];
  log_thds = new LogThread[1];
#if CC_ALG == CALVIN
  calvin_lock_thds = new CalvinLockThread[1];
  calvin_seq_thds = new CalvinSequencerThread[1];
#endif
	// query_queue should be the last one to be initialized!!!
	// because it collects txn latency
	//if (WORKLOAD != TEST) {
	//	query_queue.init(m_wl);
	//}
#if CC_ALG == OCC
  printf("Initializing occ lock manager... ");
	occ_man.init();
  printf("Done\n");
#endif

  /*
  printf("Initializing threads... ");
  fflush(stdout);
	for (uint32_t i = 0; i < all_thd_cnt; i++)
		m_thds[i].init(i, g_node_id, m_wl);
  printf("Done\n");
  fflush(stdout);
  */

  endtime = get_server_clock();
  printf("Initialization Time = %ld\n", endtime - starttime);
  fflush(stdout);
	warmup_done = true;
	pthread_barrier_init( &warmup_bar, NULL, all_thd_cnt);

#if SET_AFFINITY
	uint64_t cpu_cnt = 0;
  cpu_set_t cpus;
#endif
	// spawn and run txns again.
	starttime = get_server_clock();

  uint64_t id = 0;
	for (uint64_t i = 0; i < wthd_cnt; i++) {
#if SET_AFFINITY
		CPU_ZERO(&cpus);
    CPU_SET(cpu_cnt, &cpus);
    pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
		cpu_cnt++;
#endif
    assert(id >= 0 && id < wthd_cnt);
    worker_thds[i].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], &attr, run_thread, (void *)&worker_thds[i]);
  }
	for (uint64_t j = 0; j < rthd_cnt ; j++) {
    assert(id >= wthd_cnt && id < wthd_cnt + rthd_cnt);
    input_thds[j].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], NULL, run_thread, (void *)&input_thds[j]);
  }

	for (uint64_t j = 0; j < sthd_cnt; j++) {
    assert(id >= wthd_cnt + rthd_cnt && id < wthd_cnt + rthd_cnt + sthd_cnt);
    output_thds[j].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], NULL, run_thread, (void *)&output_thds[j]);
  }
#if LOGGING
    log_thds[0].init(id,g_node_id,m_wl);
		pthread_create(&p_thds[id++], NULL, run_thread, (void *)&log_thds[0]);
#endif

  abort_thds[0].init(id,g_node_id,m_wl);
  pthread_create(&p_thds[id++], NULL, run_thread, (void *)&abort_thds[0]);

#if CC_ALG == CALVIN
  calvin_lock_thds[0].init(id,g_node_id,m_wl);
  pthread_create(&p_thds[id++], &attr, run_thread, (void *)&calvin_lock_thds[0]);
  calvin_seq_thds[0].init(id,g_node_id,m_wl);
  pthread_create(&p_thds[id++], &attr, run_thread, (void *)&calvin_seq_thds[0]);
#endif

	for (uint64_t i = 0; i < all_thd_cnt ; i++)
		pthread_join(p_thds[i], NULL);

	endtime = get_server_clock();

  printf("PASS! SimTime = %f\n", (float)(endtime - starttime) / BILLION);
  if (STATS_ENABLE)
    stats.print(false);
  //malloc_stats_print(NULL, NULL, NULL);
  printf("\n");
  fflush(stdout);
  // Free things
	//tport_man.shutdown();

  /*
  txn_table.delete_all();
  txn_pool.free_all();
  access_pool.free_all();
  txn_table_pool.free_all();
  msg_pool.free_all();
  qry_pool.free_all();
  */
	return 0;
}

/*
void * worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run();
	return NULL;
}

void * nn_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_remote();
	return NULL;
}

void * log_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_logger();
	return NULL;
}
void * abort_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_abort();
	return NULL;
}

void * send_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_send();
	return NULL;
}

void * calvin_seq_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_calvin_seq();
	return NULL;
}

void * calvin_lock_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_calvin_lock();
	return NULL;
}

void * calvin_worker(void * id) {
	uint64_t tid = (uint64_t)id;
	m_thds[tid].run_calvin();
	return NULL;
}
*/

void * run_thread(void * id) {
  Thread * thd = (Thread *) id;
	thd->run();
	return NULL;
}

void network_test() {

      /*
	ts_t start;
	ts_t end;
	ts_t time;
	int bytes;
  float total = 0;
	for (int i = 0; i < 4; ++i) {
		time = 0;
		int num_bytes = (int) pow(10,i);
		printf("Network Bytes: %d\nns: ", num_bytes);
		for(int j = 0;j < 1000; j++) {
			start = get_sys_clock();
			tport_man.simple_send_msg(num_bytes);
			while((bytes = tport_man.simple_recv_msg()) == 0) {}
			end = get_sys_clock();
			assert(bytes == num_bytes);
			time = end-start;
      total += time;
			//printf("%lu\n",time);
		}
		printf("Avg(s): %f\n",total/BILLION/1000);
    fflush(stdout);
		//time = time/1000;
		//printf("Network Bytes: %d, s: %f\n",i,time/BILLION);
		//printf("Network Bytes: %d, ns: %.3f\n",i,time);

	}
      */

}

void network_test_recv() {
  /*
	int bytes;
	while(1) {
		if( (bytes = tport_man.simple_recv_msg()) > 0)
			tport_man.simple_send_msg(bytes);
	}
  */
}
<|endoftext|>