<commit_before>#include "Game.hpp"
#include "chimera/core/device/JoystickManager.hpp"
#include "chimera/core/utils.hpp"
#include "chimera/render/scene/Components.hpp"

Game::Game(Chimera::Scene& scene) : pCorpoRigido(nullptr), scene(&scene) { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Constructor Game"); }

Game::~Game() { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Destructor Game"); }

bool Game::onEvent(const SDL_Event& event) {
    using namespace Chimera;

    switch (event.type) {
        case SDL_USEREVENT: {
            switch (event.user.code) {
                case Chimera::EVENT_COLLIDE_START: {
                    uint32_t* n1 = (uint32_t*)event.user.data1;
                    uint32_t* n2 = (uint32_t*)event.user.data2;
                    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Colisao start: %d -> %d", *n1, *n2);
                } break;
                case Chimera::EVENT_COLLIDE_ON: {
                    uint32_t* n1 = (uint32_t*)event.user.data1;
                    uint32_t* n2 = (uint32_t*)event.user.data2;
                    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Colisao ON: %d -> %d", *n1, *n2);
                } break;
                case Chimera::EVENT_COLLIDE_OFF: {
                    uint32_t* n1 = (uint32_t*)event.user.data1;
                    uint32_t* n2 = (uint32_t*)event.user.data2;
                    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Colisao OFF: %d -> %d", *n1, *n2);
                } break;
                case Chimera::EVENT_NEW_FPS: {
                    uint32_t* pFps = (uint32_t*)event.user.data1;
                    fps = *pFps;
                    // glm::vec3 val1 = pCorpoRigido->getPosition();
                    // sPosicaoObj = "pos:(" + std::to_string(val1.x) + "," + std::to_string(val1.y) + "," + std::to_string(val1.z) + ")";
                } break;
                default:
                    break;
            }

        } break;
        case SDL_KEYDOWN: {
            switch (event.key.keysym.sym) {
                case SDLK_ESCAPE:
                    utilSendEvent(EVENT_FLOW_STOP, nullptr, nullptr);
                    break;
                    // case SDLK_F1:
                    //     pHUD->setOn(!pHUD->isOn());
                    // break;
                case SDLK_F10:
                    utilSendEvent(EVENT_TOGGLE_FULL_SCREEN, nullptr, nullptr);
                    break;
                case SDLK_UP:
                    pCorpoRigido->applyForce(glm::vec3(10.0, 0.0, 0.0));
                    break;
                case SDLK_DOWN:
                    pCorpoRigido->applyForce(glm::vec3(-10.0, 0.0, 0.0));
                    break;
                case SDLK_LEFT:
                    pCorpoRigido->applyForce(glm::vec3(0.0, 10.0, 0.0));
                    break;
                case SDLK_RIGHT:
                    pCorpoRigido->applyForce(glm::vec3(0.0, -10.0, 0.0));
                    break;
                case SDLK_a:
                    pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, 10.0));
                    break;
                case SDLK_s:
                    pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, -10.0));
                    break;
                default:
                    break;
            }
        } break;

        case SDL_JOYAXISMOTION:
        case SDL_JOYBUTTONDOWN:
        case SDL_JOYBUTTONUP:
        case SDL_JOYHATMOTION:
        case SDL_JOYBALLMOTION: {

            JoystickState* pJoy = JoystickManager::select(event.jball.which);

            // Captura joystick 0 se existir
            if (pJoy != nullptr) {

                pJoy->debug();

                float propulsaoPrincipal = 3.0f;

                crt.yaw = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_X, 32));
                crt.pitch = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_Y, 32));
                crt.roll = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::RIGHT_X, 32));

                double throttle = 0;
                crt.throttle = -propulsaoPrincipal * ((1 + JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_TRIGGER))) / 2);

                if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::X) == SDL_PRESSED) {
                    // glm::vec3 posicao = pEmissor->getPosSource();
                    // posicao.x = posicao.x - 0.1f;
                    // pEmissor->setPosSource( posicao );
                }

                if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::B) == SDL_PRESSED) { // ( or SDL_RELEASED)
                    // glm::vec3 posicao = pEmissor->getPosSource();
                    // posicao.x = posicao.x + 0.1f;
                    // pEmissor->setPosSource(posicao);
                }

                crt.hat = pJoy->getHat(0);
            }

        } break;

        case SDL_MOUSEBUTTONDOWN:
        case SDL_MOUSEBUTTONUP:
        case SDL_MOUSEMOTION: {
        } break;
        case SDL_WINDOWEVENT: {
            switch (event.window.event) {
                case SDL_WINDOWEVENT_ENTER:
                    utilSendEvent(EVENT_FLOW_RESUME, nullptr, nullptr); // isPaused = false;
                    break;
                case SDL_WINDOWEVENT_LEAVE:
                    utilSendEvent(EVENT_FLOW_PAUSE, nullptr, nullptr); // isPaused = true;
                    break;
            }
        } break;
    }
    return true;
}

void Game::onAttach() {

    using namespace Chimera;
    // Localiza objeto como o primario
    TransComponent& tc = scene->getRegistry()->findComponent<TransComponent>("Zoltan");
    pCorpoRigido = (Solid*)tc.trans;

    lFPS = new Label("None", -500, 280, glm::vec4(1.0, 1.0, 1.0, 1.0));
    Tile* tile = (Tile*)scene->getLayes().getState("TileText");
    tile->add(lFPS);

    glClearColor(0.f, 0.f, 0.f, 1.f); // Initialize clear color
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    glClearDepth(1.0f);
    glDepthFunc(GL_LEQUAL);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void Game::onDeatach() {}

void Game::onUpdate(const double& ts) {

    if (pCorpoRigido)
        scene->setOrigem(pCorpoRigido);

    using namespace Chimera;

    float propulsaoLRUD = 5.0f;
    float torque = 0.5f;

    if (pCorpoRigido) {
        if (crt.hat & (uint8_t)SDL_HAT_UP)
            pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, propulsaoLRUD));

        if (crt.hat & (uint8_t)SDL_HAT_DOWN)
            pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, -propulsaoLRUD));

        if (crt.hat & (uint8_t)SDL_HAT_RIGHTUP)
            pCorpoRigido->applyForce(glm::vec3(propulsaoLRUD, 0.0, 0.0));

        if (crt.hat & (uint8_t)SDL_HAT_LEFTUP)
            pCorpoRigido->applyForce(glm::vec3(-propulsaoLRUD, 0.0, 0.0));

        if ((crt.roll != 0.0) || (crt.pitch != 0.0) || (crt.yaw != 0.0) || (crt.throttle != 0.0)) {
            pCorpoRigido->applyForce(glm::vec3(0.0, crt.throttle, 0.0));
            pCorpoRigido->applyTorc(glm::vec3(-torque * crt.pitch, -torque * crt.roll, -torque * crt.yaw));
        }
    }

    lFPS->setText(std::string("FPS: ") + std::to_string(fps));
}

void Game::onRender() {}<commit_msg>Grupo2d funcional junto a texto no models3<commit_after>#include "Game.hpp"
#include "chimera/core/device/JoystickManager.hpp"
#include "chimera/core/utils.hpp"
#include "chimera/render/2d/Group.hpp"
#include "chimera/render/2d/Sprite.hpp"
#include "chimera/render/scene/Components.hpp"

Game::Game(Chimera::Scene& scene) : pCorpoRigido(nullptr), scene(&scene) { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Constructor Game"); }

Game::~Game() { SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Destructor Game"); }

bool Game::onEvent(const SDL_Event& event) {
    using namespace Chimera;

    switch (event.type) {
        case SDL_USEREVENT: {
            switch (event.user.code) {
                case Chimera::EVENT_COLLIDE_START: {
                    uint32_t* n1 = (uint32_t*)event.user.data1;
                    uint32_t* n2 = (uint32_t*)event.user.data2;
                    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Colisao start: %d -> %d", *n1, *n2);
                } break;
                case Chimera::EVENT_COLLIDE_ON: {
                    uint32_t* n1 = (uint32_t*)event.user.data1;
                    uint32_t* n2 = (uint32_t*)event.user.data2;
                    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Colisao ON: %d -> %d", *n1, *n2);
                } break;
                case Chimera::EVENT_COLLIDE_OFF: {
                    uint32_t* n1 = (uint32_t*)event.user.data1;
                    uint32_t* n2 = (uint32_t*)event.user.data2;
                    SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Colisao OFF: %d -> %d", *n1, *n2);
                } break;
                case Chimera::EVENT_NEW_FPS: {
                    uint32_t* pFps = (uint32_t*)event.user.data1;
                    fps = *pFps;
                    // glm::vec3 val1 = pCorpoRigido->getPosition();
                    // sPosicaoObj = "pos:(" + std::to_string(val1.x) + "," + std::to_string(val1.y) + "," + std::to_string(val1.z) + ")";
                } break;
                default:
                    break;
            }

        } break;
        case SDL_KEYDOWN: {
            switch (event.key.keysym.sym) {
                case SDLK_ESCAPE:
                    utilSendEvent(EVENT_FLOW_STOP, nullptr, nullptr);
                    break;
                    // case SDLK_F1:
                    //     pHUD->setOn(!pHUD->isOn());
                    // break;
                case SDLK_F10:
                    utilSendEvent(EVENT_TOGGLE_FULL_SCREEN, nullptr, nullptr);
                    break;
                case SDLK_UP:
                    pCorpoRigido->applyForce(glm::vec3(10.0, 0.0, 0.0));
                    break;
                case SDLK_DOWN:
                    pCorpoRigido->applyForce(glm::vec3(-10.0, 0.0, 0.0));
                    break;
                case SDLK_LEFT:
                    pCorpoRigido->applyForce(glm::vec3(0.0, 10.0, 0.0));
                    break;
                case SDLK_RIGHT:
                    pCorpoRigido->applyForce(glm::vec3(0.0, -10.0, 0.0));
                    break;
                case SDLK_a:
                    pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, 10.0));
                    break;
                case SDLK_s:
                    pCorpoRigido->applyTorc(glm::vec3(0.0, 0.0, -10.0));
                    break;
                default:
                    break;
            }
        } break;

        case SDL_JOYAXISMOTION:
        case SDL_JOYBUTTONDOWN:
        case SDL_JOYBUTTONUP:
        case SDL_JOYHATMOTION:
        case SDL_JOYBALLMOTION: {

            JoystickState* pJoy = JoystickManager::select(event.jball.which);

            // Captura joystick 0 se existir
            if (pJoy != nullptr) {

                pJoy->debug();

                float propulsaoPrincipal = 3.0f;

                crt.yaw = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_X, 32));
                crt.pitch = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_Y, 32));
                crt.roll = JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::RIGHT_X, 32));

                double throttle = 0;
                crt.throttle = -propulsaoPrincipal * ((1 + JoystickState::scale16(pJoy->getAxis((uint8_t)JOY_AXIX_COD::LEFT_TRIGGER))) / 2);

                if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::X) == SDL_PRESSED) {
                    // glm::vec3 posicao = pEmissor->getPosSource();
                    // posicao.x = posicao.x - 0.1f;
                    // pEmissor->setPosSource( posicao );
                }

                if (pJoy->getButtonState((uint8_t)JOY_BUTTON_COD::B) == SDL_PRESSED) { // ( or SDL_RELEASED)
                    // glm::vec3 posicao = pEmissor->getPosSource();
                    // posicao.x = posicao.x + 0.1f;
                    // pEmissor->setPosSource(posicao);
                }

                crt.hat = pJoy->getHat(0);
            }

        } break;

        case SDL_MOUSEBUTTONDOWN:
        case SDL_MOUSEBUTTONUP:
        case SDL_MOUSEMOTION: {
        } break;
        case SDL_WINDOWEVENT: {
            switch (event.window.event) {
                case SDL_WINDOWEVENT_ENTER:
                    utilSendEvent(EVENT_FLOW_RESUME, nullptr, nullptr); // isPaused = false;
                    break;
                case SDL_WINDOWEVENT_LEAVE:
                    utilSendEvent(EVENT_FLOW_PAUSE, nullptr, nullptr); // isPaused = true;
                    break;
            }
        } break;
    }
    return true;
}

void Game::onAttach() {

    using namespace Chimera;
    // Localiza objeto como o primario
    TransComponent& tc = scene->getRegistry()->findComponent<TransComponent>("Zoltan");
    pCorpoRigido = (Solid*)tc.trans;

    lFPS = new Label("None", 0, 0, glm::vec4(1.0, 1.0, 1.0, 1.0));
    Tile* tile = (Tile*)scene->getLayes().getState("TileText");

    Group* group = new Group(glm::translate(glm::mat4(1.0f), glm::vec3(-500.0f, 270.0f, 0.0f)));
    group->add(new Sprite(0.0f, 0.0f, 200.0f, 50.0f, glm::vec4(0, 0, 1, 1)));
    group->add(lFPS);
    tile->add(group);
    // tile->add(lFPS);

    glClearColor(0.f, 0.f, 0.f, 1.f); // Initialize clear color
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    glClearDepth(1.0f);
    glDepthFunc(GL_LEQUAL);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void Game::onDeatach() {}

void Game::onUpdate(const double& ts) {

    if (pCorpoRigido)
        scene->setOrigem(pCorpoRigido);

    using namespace Chimera;

    float propulsaoLRUD = 5.0f;
    float torque = 0.5f;

    if (pCorpoRigido) {
        if (crt.hat & (uint8_t)SDL_HAT_UP)
            pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, propulsaoLRUD));

        if (crt.hat & (uint8_t)SDL_HAT_DOWN)
            pCorpoRigido->applyForce(glm::vec3(0.0, 0.0, -propulsaoLRUD));

        if (crt.hat & (uint8_t)SDL_HAT_RIGHTUP)
            pCorpoRigido->applyForce(glm::vec3(propulsaoLRUD, 0.0, 0.0));

        if (crt.hat & (uint8_t)SDL_HAT_LEFTUP)
            pCorpoRigido->applyForce(glm::vec3(-propulsaoLRUD, 0.0, 0.0));

        if ((crt.roll != 0.0) || (crt.pitch != 0.0) || (crt.yaw != 0.0) || (crt.throttle != 0.0)) {
            pCorpoRigido->applyForce(glm::vec3(0.0, crt.throttle, 0.0));
            pCorpoRigido->applyTorc(glm::vec3(-torque * crt.pitch, -torque * crt.roll, -torque * crt.yaw));
        }
    }

    lFPS->setText(std::string("FPS: ") + std::to_string(fps));
}

void Game::onRender() {}<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char *argv[])
{
    cout << "      |";
    for (int x = 1; x<=12; ++x)
    {
        cout <<setw(5)<< x <<"|";

    }
    cout << endl;

    for( int x = 0; x<=12; ++x)
    {
        cout << "-----+";
    }
    cout << endl;

    for( int y = 1; y<=12; ++y)
    {
        cout<<setw(5)<< y << "|";

        for (int x=1; x<=12; ++x)
        {
            cout<<setw(5)<<x*y << "|";
        }
        cout<< endl;

        for(int x =0; x<=12; ++x)
        {
            cout << "-----+";
        }
        cout <<endl;
    }

}
<commit_msg>fixed table.closes #35<commit_after>#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char *argv[])
{
    cout << "      |";
    for (int x = 1; x<=12; ++x)
    {
        cout <<setw(5)<< x <<"|";

    }
    cout << endl;

    for(int x = 0; x<=12; ++x)
    {
        cout << "-----+";
    }
    cout << endl;

    for(int y = 1; y<=12; ++y)
    {
        cout<<setw(5)<< y << "|";

        for (int x=1; x<=12; ++x)
        {
            cout<<setw(5)<<x*y << "|";
        }
        cout<< endl;

        for(int x =0; x<=12; ++x)
        {
            cout << "-----+";
        }
        cout <<endl;
    }

}
<|endoftext|>


<commit_before>#include "StateSpace.h"

StateSpace::StateSpace(const unsigned int _angle_max, const unsigned int _velocity_max, PriorityQueue<Action*,double> queue ):
	angle_max(_angle_max),
	velocity_max(_velocity_max),
	space(_angle_max, std::vector< PriorityQueue<Action*,double> > (_velocity_max, PriorityQueue<Action*,double> (queue)))
{}

StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)
{
	//throw if the the index is out of bounds
	if(robot_state>1)throw std::domain_error("action index exceeded");
	//return proxy object to accept second [] operator
	return SubscriptProxy1( robot_state ? space1 : space2 );
}

//searches state space by state object
PriorityQueue<Action *, double>& StateSpace::operator[](const State & state)
{
	//call the subscript operators with the members of the state object
	return (*this)[state.robot_state][state.theta][state.theta_dot];
}
<commit_msg>so many comments<commit_after>#include "StateSpace.h"

StateSpace::StateSpace(const unsigned int _angle_bins, const unsigned int _velocity_bins, PriorityQueue<Action*,double> queue ):
	angle_bins(_angle_bins),
	velocity_bins(_velocity_bins),
	space(_angle_max, std::vector< PriorityQueue<Action*,double> > (_velocity_max, PriorityQueue<Action*,double> (queue)))
{}

StateSpace::SubscriptProxy1 StateSpace::operator[](const unsigned int robot_state)
{
	//throw if the the index is out of bounds
	if(robot_state>1)throw std::domain_error("action index exceeded");
	//return proxy object to accept second [] operator
	return SubscriptProxy1( robot_state ? space1 : space2 );
}

//searches state space by state object
PriorityQueue<Action *, double>& StateSpace::operator[](const State & state)
{
	//call the subscript operators with the members of the state object
	return (*this)[state.robot_state][state.theta][state.theta_dot];
}
<|endoftext|>


<commit_before>/** \file crf_analyzer.cpp
 * Implementation of class CRF_Analyzer.
 *
 * \author Jun Jiang
 * \version 0.1
 * \date Mar 2, 2009
 */

#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>

#include "jma_analyzer.h"
#include "jma_knowledge.h"
#include "tokenizer.h"

namespace jma
{

/**
 * Whether the two MorphemeLists is the same
 * \param list1 the MorphemeList 1
 * \param list2 the MorphemeList 2
 */
inline bool isSameMorphemeList( const MorphemeList* list1, const MorphemeList* list2, bool printPOS )
{
	// if one is zero pointer, return null
	if( !list1 || !list2 )
	{
		return false;
	}

	if( list1->size() != list2->size() )
		return false;
	//compare one by one
	size_t N = list1->size();
	if( printPOS )
	{
		for( size_t i = 0; i < N; ++i )
		{
			const Morpheme& m1 = (*list1)[i];
			const Morpheme& m2 = (*list2)[i];
			if( m1.lexicon_ != m2.lexicon_ || m1.posCode_ != m2.posCode_
					|| m1.posStr_ != m2.posStr_ )
			{
				return false;
			}
		}
	}
	else
	{
		for( size_t i = 0; i < N; ++i )
		{
			if( (*list1)[i].lexicon_ != (*list2)[i].lexicon_ )
				return false;
		}
	}
	//all the elements are the same
	return true;
}

JMA_Analyzer::JMA_Analyzer()
    : knowledge_(0), tagger_(0)
{
}

JMA_Analyzer::~JMA_Analyzer()
{
}

void JMA_Analyzer::setKnowledge(Knowledge* pKnowledge)
{
    assert(pKnowledge);

    knowledge_ = dynamic_cast<JMA_Knowledge*>(pKnowledge);
    assert(knowledge_);
    tagger_ = knowledge_->getTagger();
    assert(tagger_);
    tagger_->set_lattice_level(1);
    maxPosCateOffset_ = knowledge_->getPOSCatNum() - 1;
}

int JMA_Analyzer::runWithSentence(Sentence& sentence)
{
	bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
	int N = (int)getOption(Analyzer::OPTION_TYPE_NBEST);

	//one best
	if(N <= 1)
	{
		const MeCab::Node* bosNode = tagger_->parseToNode( sentence.getString() );
		MorphemeList list;
		for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
		{
			string seg(node->surface, node->length);
			if(knowledge_->isStopWord(seg))
				continue;
			list.push_back(Morpheme());
			Morpheme& morp = list.back();
			morp.lexicon_ = seg;
			if(printPOS)
			{
				morp.posCode_ = (int)node->posid;
				morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
			}
		}
		sentence.addList(list, 1.0);
	}
	// N-best
	else
	{
		double totalScore = 0;

		if( !tagger_->parseNBestInit( sentence.getString() ) )
		{
			cerr << "[Error] Cannot parseNBestInit on the " << sentence.getString() << endl;
			return 0;
		}

		long base = 0;
		int i = 0;
		for ( ; i < N;  )
		{
			const MeCab::Node* bosNode = tagger_->nextNode();
			if( !bosNode )
				break;
			MorphemeList list;
			for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
			{
				string seg(node->surface, node->length);
				if(knowledge_->isStopWord(seg))
					continue;
				list.push_back(Morpheme());
				Morpheme& morp = list.back();
				morp.lexicon_ = seg;
				if(printPOS)
				{
					morp.posCode_ = (int)node->posid;
					morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
				}
			}

			bool isDupl = false;
			//check the current result with exits results
			for( int listOffset = sentence.getListSize() - 1 ; listOffset >= 0; --listOffset )
			{
				if( isSameMorphemeList( sentence.getMorphemeList(listOffset), &list, printPOS ) )
				{
					isDupl = true;
					break;
				}
			}
			//ignore the duplicate results
			if( isDupl )
				continue;

			long score = tagger_->nextScore();
			if( i == 0 )
				base = score > BASE_NBEST_SCORE ? score - BASE_NBEST_SCORE : 0;

			double dScore = 1.0 / (score - base );
			totalScore += dScore;
			sentence.addList( list, dScore );
			++i;
		}

		for ( int j = 0; j < i; ++j )
		{
			sentence.setScore(j, sentence.getScore(j) / totalScore );
		}
	}

	return 1;
}

const char* JMA_Analyzer::runWithString(const char* inStr)
{
	bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;

	const MeCab::Node* bosNode = tagger_->parseToNode( inStr );

	strBuf_.clear();
	if (printPOS) {
		for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
			strBuf_.append(node->surface, node->length).append(posDelimiter_).
				append(node->feature, getPOSOffset(node->feature) ).append(wordDelimiter_);
		}

	} else {
		for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
			strBuf_.append(node->surface, node->length).append(wordDelimiter_);
		}
	}

	return strBuf_.c_str();

}

int JMA_Analyzer::runWithStream(const char* inFileName, const char* outFileName)
{
	assert(inFileName);
	assert(outFileName);

	bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;

	ifstream in(inFileName);
	if(!in)
	{
		cerr<<"[Error] The input file "<<inFileName<<" not exists!"<<endl;
		return 0;
	}
    ofstream out(outFileName);
    string line;
    bool remains = !in.eof();
    while (remains) {
        getline(in, line);
        remains = !in.eof();
        if (!line.length()) {
            if( remains )
				out << endl;
            continue;
        }

        const MeCab::Node* bosNode = tagger_->parseToNode( line.c_str() );

        if (printPOS) {
			for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
				out.write(node->surface, node->length) << posDelimiter_;
				out.write(node->feature, getPOSOffset(node->feature) ) << wordDelimiter_;
			}

            if (remains)
                out << endl;
            else
                break;

        } else {
			for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
				out.write(node->surface, node->length) << wordDelimiter_;
			}

			if (remains)
				out << endl;
			else
				break;
        }
    }

    in.close();
    out.close();
    return 1;
}

void JMA_Analyzer::splitSentence(const char* paragraph, std::vector<Sentence>& sentences)
{
    if(! paragraph)
        return;

    Sentence result;
    string sentenceStr;
    CTypeTokenizer tokenizer( knowledge_->getCType() );
    tokenizer.assign(paragraph);
    for(const char* p=tokenizer.next(); p; p=tokenizer.next())
    {
        if( knowledge_->isSentenceSeparator(p) )
        {
            sentenceStr += p;

            result.setString(sentenceStr.c_str());
            sentences.push_back(result);

            sentenceStr.clear();
        }
        /*// white-space characters are also used as sentence separator,
        // but they are ignored in the sentence result
        else if(ctype_->isSpace(p))
        {
            if(! sentenceStr.empty())
            {
                result.setString(sentenceStr.c_str());
                sentences.push_back(result);

                sentenceStr.clear();
            }
        }*/
        else
        {
            sentenceStr += p;
        }
    }

    // in case the last character is not space or sentence separator
    if(! sentenceStr.empty())
    {
        result.setString(sentenceStr.c_str());
        sentences.push_back(result);

        sentenceStr.clear();
    }
}

int JMA_Analyzer::getPOSOffset(const char* feature){
	if( knowledge_->isOutputFullPOS() )
	{
		// count for the index of the fourth offset
		int offset = 0;
		int commaCount = 0;
		for( ; feature[offset]; ++offset )
		{
			if(feature[offset] == ',')
			{
				++commaCount;
				if( commaCount > maxPosCateOffset_ )
					break;
			}
		}
		return offset;
	}

	 //count for the index of the comma that after non-star pos sections
	int offset = 0;
	int commaCount = 0;
	for( ; feature[offset]; ++offset )
	{
		if(feature[offset] == ',')
		{
			++commaCount;
			if( commaCount > maxPosCateOffset_ )
				break;
		}
		else if(feature[offset] == '*')
		{
			//if offset is 0, contains nothing
			return offset ? offset - 1 : 0 ;
		}
	}

	return offset;
}

} // namespace jma
<commit_msg>check whether a word is stop word in the runWithString and runWithStream<commit_after>/** \file crf_analyzer.cpp
 * Implementation of class CRF_Analyzer.
 *
 * \author Jun Jiang
 * \version 0.1
 * \date Mar 2, 2009
 */

#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>

#include "jma_analyzer.h"
#include "jma_knowledge.h"
#include "tokenizer.h"

namespace jma
{

/**
 * Whether the two MorphemeLists is the same
 * \param list1 the MorphemeList 1
 * \param list2 the MorphemeList 2
 */
inline bool isSameMorphemeList( const MorphemeList* list1, const MorphemeList* list2, bool printPOS )
{
	// if one is zero pointer, return null
	if( !list1 || !list2 )
	{
		return false;
	}

	if( list1->size() != list2->size() )
		return false;
	//compare one by one
	size_t N = list1->size();
	if( printPOS )
	{
		for( size_t i = 0; i < N; ++i )
		{
			const Morpheme& m1 = (*list1)[i];
			const Morpheme& m2 = (*list2)[i];
			if( m1.lexicon_ != m2.lexicon_ || m1.posCode_ != m2.posCode_
					|| m1.posStr_ != m2.posStr_ )
			{
				return false;
			}
		}
	}
	else
	{
		for( size_t i = 0; i < N; ++i )
		{
			if( (*list1)[i].lexicon_ != (*list2)[i].lexicon_ )
				return false;
		}
	}
	//all the elements are the same
	return true;
}

JMA_Analyzer::JMA_Analyzer()
    : knowledge_(0), tagger_(0)
{
}

JMA_Analyzer::~JMA_Analyzer()
{
}

void JMA_Analyzer::setKnowledge(Knowledge* pKnowledge)
{
    assert(pKnowledge);

    knowledge_ = dynamic_cast<JMA_Knowledge*>(pKnowledge);
    assert(knowledge_);
    tagger_ = knowledge_->getTagger();
    assert(tagger_);
    tagger_->set_lattice_level(1);
    maxPosCateOffset_ = knowledge_->getPOSCatNum() - 1;
}

int JMA_Analyzer::runWithSentence(Sentence& sentence)
{
	bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;
	int N = (int)getOption(Analyzer::OPTION_TYPE_NBEST);

	//one best
	if(N <= 1)
	{
		const MeCab::Node* bosNode = tagger_->parseToNode( sentence.getString() );
		MorphemeList list;
		for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
		{
			string seg(node->surface, node->length);
			if(knowledge_->isStopWord(seg))
				continue;
			list.push_back(Morpheme());
			Morpheme& morp = list.back();
			morp.lexicon_ = seg;
			if(printPOS)
			{
				morp.posCode_ = (int)node->posid;
				morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
			}
		}
		sentence.addList(list, 1.0);
	}
	// N-best
	else
	{
		double totalScore = 0;

		if( !tagger_->parseNBestInit( sentence.getString() ) )
		{
			cerr << "[Error] Cannot parseNBestInit on the " << sentence.getString() << endl;
			return 0;
		}

		long base = 0;
		int i = 0;
		for ( ; i < N;  )
		{
			const MeCab::Node* bosNode = tagger_->nextNode();
			if( !bosNode )
				break;
			MorphemeList list;
			for (const MeCab::Node *node = bosNode->next; node->next; node = node->next)
			{
				string seg(node->surface, node->length);
				if(knowledge_->isStopWord(seg))
					continue;
				list.push_back(Morpheme());
				Morpheme& morp = list.back();
				morp.lexicon_ = seg;
				if(printPOS)
				{
					morp.posCode_ = (int)node->posid;
					morp.posStr_ = string(node->feature, getPOSOffset(node->feature));
				}
			}

			bool isDupl = false;
			//check the current result with exits results
			for( int listOffset = sentence.getListSize() - 1 ; listOffset >= 0; --listOffset )
			{
				if( isSameMorphemeList( sentence.getMorphemeList(listOffset), &list, printPOS ) )
				{
					isDupl = true;
					break;
				}
			}
			//ignore the duplicate results
			if( isDupl )
				continue;

			long score = tagger_->nextScore();
			if( i == 0 )
				base = score > BASE_NBEST_SCORE ? score - BASE_NBEST_SCORE : 0;

			double dScore = 1.0 / (score - base );
			totalScore += dScore;
			sentence.addList( list, dScore );
			++i;
		}

		for ( int j = 0; j < i; ++j )
		{
			sentence.setScore(j, sentence.getScore(j) / totalScore );
		}
	}

	return 1;
}

const char* JMA_Analyzer::runWithString(const char* inStr)
{
	bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;

	const MeCab::Node* bosNode = tagger_->parseToNode( inStr );

	strBuf_.clear();
	if (printPOS) {
		for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
			string seg(node->surface, node->length);
			if(knowledge_->isStopWord(seg))
				continue;

			strBuf_.append(node->surface, node->length).append(posDelimiter_).
				append(node->feature, getPOSOffset(node->feature) ).append(wordDelimiter_);
		}

	} else {
		for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
			string seg(node->surface, node->length);
			if(knowledge_->isStopWord(seg))
				continue;

			strBuf_.append(node->surface, node->length).append(wordDelimiter_);
		}
	}

	return strBuf_.c_str();

}

int JMA_Analyzer::runWithStream(const char* inFileName, const char* outFileName)
{
	assert(inFileName);
	assert(outFileName);

	bool printPOS = getOption(OPTION_TYPE_POS_TAGGING) > 0;

	ifstream in(inFileName);
	if(!in)
	{
		cerr<<"[Error] The input file "<<inFileName<<" not exists!"<<endl;
		return 0;
	}
    ofstream out(outFileName);
    string line;
    bool remains = !in.eof();
    while (remains) {
        getline(in, line);
        remains = !in.eof();
        if (!line.length()) {
            if( remains )
				out << endl;
            continue;
        }

        const MeCab::Node* bosNode = tagger_->parseToNode( line.c_str() );

        if (printPOS) {
			for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
				string seg(node->surface, node->length);
				if(knowledge_->isStopWord(seg))
					continue;

				out.write(node->surface, node->length) << posDelimiter_;
				out.write(node->feature, getPOSOffset(node->feature) ) << wordDelimiter_;
			}

            if (remains)
                out << endl;
            else
                break;

        } else {
			for (const MeCab::Node *node = bosNode->next; node->next; node = node->next){
				string seg(node->surface, node->length);
				if(knowledge_->isStopWord(seg))
					continue;

				out.write(node->surface, node->length) << wordDelimiter_;
			}

			if (remains)
				out << endl;
			else
				break;
        }
    }

    in.close();
    out.close();
    return 1;
}

void JMA_Analyzer::splitSentence(const char* paragraph, std::vector<Sentence>& sentences)
{
    if(! paragraph)
        return;

    Sentence result;
    string sentenceStr;
    CTypeTokenizer tokenizer( knowledge_->getCType() );
    tokenizer.assign(paragraph);
    for(const char* p=tokenizer.next(); p; p=tokenizer.next())
    {
        if( knowledge_->isSentenceSeparator(p) )
        {
            sentenceStr += p;

            result.setString(sentenceStr.c_str());
            sentences.push_back(result);

            sentenceStr.clear();
        }
        /*// white-space characters are also used as sentence separator,
        // but they are ignored in the sentence result
        else if(ctype_->isSpace(p))
        {
            if(! sentenceStr.empty())
            {
                result.setString(sentenceStr.c_str());
                sentences.push_back(result);

                sentenceStr.clear();
            }
        }*/
        else
        {
            sentenceStr += p;
        }
    }

    // in case the last character is not space or sentence separator
    if(! sentenceStr.empty())
    {
        result.setString(sentenceStr.c_str());
        sentences.push_back(result);

        sentenceStr.clear();
    }
}

int JMA_Analyzer::getPOSOffset(const char* feature){
	if( knowledge_->isOutputFullPOS() )
	{
		// count for the index of the fourth offset
		int offset = 0;
		int commaCount = 0;
		for( ; feature[offset]; ++offset )
		{
			if(feature[offset] == ',')
			{
				++commaCount;
				if( commaCount > maxPosCateOffset_ )
					break;
			}
		}
		return offset;
	}

	 //count for the index of the comma that after non-star pos sections
	int offset = 0;
	int commaCount = 0;
	for( ; feature[offset]; ++offset )
	{
		if(feature[offset] == ',')
		{
			++commaCount;
			if( commaCount > maxPosCateOffset_ )
				break;
		}
		else if(feature[offset] == '*')
		{
			//if offset is 0, contains nothing
			return offset ? offset - 1 : 0 ;
		}
	}

	return offset;
}

} // namespace jma
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: formula.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-03-08 11:55:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_FORMULA_HXX
#define SC_FORMULA_HXX

#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif

#ifndef SC_FUNCUTL_HXX
#include "funcutl.hxx"
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"       // ScAddress
#endif

#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif

#ifndef _SV_TABPAGE_HXX //autogen
#include <vcl/tabpage.hxx>
#endif

#ifndef _SVSTDARR_STRINGS

#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>

#endif

#ifndef _SV_TABCTRL_HXX //autogen
#include <vcl/tabctrl.hxx>
#endif

#ifndef SC_PARAWIN_HXX
#include "parawin.hxx"
#endif

#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif

#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif

#ifndef SC_CELL_HXX
#include "cell.hxx"
#endif

#ifndef SC_FUNCPAGE_HXX
#include "funcpage.hxx"
#endif

#ifndef SC_STRUCTPG_HXX
#include "structpg.hxx"
#endif

class ScViewData;
class ScDocument;
class ScFuncDesc;
class ScInputHandler;
class ScDocShell;

//============================================================================

enum ScFormulaDlgMode { SC_FORMDLG_FORMULA, SC_FORMDLG_ARGS, SC_FORMDLG_EDIT };

//============================================================================

typedef ScTabViewShell* PtrTabViewShell;

//============================================================================

//============================================================================

class ScFormulaDlg : public ScAnyRefDlg
{
public:
                    ScFormulaDlg( SfxBindings* pB, SfxChildWindow* pCW,
                                    Window* pParent, ScViewData* pViewData );
                    ~ScFormulaDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pRefDoc );
    virtual BOOL    IsRefInputMode() const;
    virtual BOOL    IsDocAllowed(SfxObjectShell* pDocSh) const;
    virtual void    SetActive();
    virtual BOOL    Close();

private:

    TabControl      aTabCtrl;
    GroupBox        aGbEdit;        //! MUST be placed before aScParaWin for initializing
    ScParaWin       aScParaWin;
    FixedText       aFtHeadLine;
    FixedInfo       aFtFuncName;
    FixedInfo       aFtFuncDesc;

    FixedText       aFtEditName;
    //FixedInfo     aFtEditDesc;

    FixedText       aFtResult;
    ValWnd          aWndResult;

    FixedText       aFtFormula;
    ScEditBox       aMEFormula;

    CheckBox        aBtnMatrix;
    HelpButton      aBtnHelp;
    CancelButton    aBtnCancel;

    PushButton      aBtnBackward;
    PushButton      aBtnForward;
    OKButton        aBtnEnd;

    ScRefEdit       aEdRef;
    ScRefButton     aRefBtn;

    FixedText       aFtFormResult;
    ValWnd          aWndFormResult;

    ScRefEdit*      pTheRefEdit;
    ScRefButton*    pTheRefButton;
    ScFuncPage*     pScFuncPage;
    ScStructPage*   pScStructPage;
    ScFormulaCell*  pCell;
    ScCompiler*     pComp;
    ScTokenArray*   pScTokA;
    String          aOldFormula;
    BOOL            bStructUpdate;
    MultiLineEdit*  pMEdit;
    BOOL            bUserMatrixFlag;
    Timer           aTimer;

    const String    aTitle1;
    const String    aTitle2;
    const String    aTxtEnd;
    const String    aTxtOk;     // hinter aBtnEnd

    ULONG           nOldHelp;
    ULONG           nOldUnique;
    ULONG           nActivWinId;
    BOOL            bIsShutDown;

    Font            aFntBold;
    Font            aFntLight;
    USHORT          nEdFocus;
//    Selection       theCurSel;
    BOOL            bEditFlag;
    const ScFuncDesc*   pFuncDesc;
    USHORT          nArgs;
    String**        pArgArr;
    Selection       aFuncSel;

    static ScDocument*  pDoc;
    static ScAddress    aCursorPos;

protected:

    virtual long    PreNotify( NotifyEvent& rNEvt );
    virtual void    RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );
    virtual void    RefInputDone( BOOL bForced = FALSE );
    ULONG           FindFocusWin(Window *pWin);
    void            SetFocusWin(Window *pWin,ULONG nUniqueId);
    String          RepairFormula(const String& aFormula);
    void            SaveLRUEntry(const ScFuncDesc*  pFuncDesc);
    void            HighlightFunctionParas(const String& aFormula);

private:

    BOOL            IsInputHdl(ScInputHandler* pHdl);
    ScInputHandler* GetNextInputHandler(ScDocShell* pDocShell,PtrTabViewShell* ppViewSh=NULL);

    void            MakeTree(SvLBoxEntry* pParent,ScToken* pScToken,long Count,
                                    ScTokenArray* pScTokA,ScCompiler*   pComp);

    void            ClearAllParas();
    void            DeleteArgs();
    void            FillDialog(BOOL nFlag=TRUE);
    void            EditNextFunc( BOOL bForward, xub_StrLen nFStart=NOT_FOUND );
    void            EditThisFunc(xub_StrLen nFStart);
    void            EditFuncParas(xub_StrLen nEditPos);

    void            UpdateArgInput( USHORT nOffset, USHORT nInput );
    BOOL            CalcValue( const String& rStrExp, String& rStrResult );
    BOOL            CalcStruct( const String& rStrExp);

    void            UpdateValues();
    void            SaveArg( USHORT nEd );
    void            UpdateSelection();
    void            DoEnter( BOOL bOk );
    void            UpdateFunctionDesc();
    void            ResizeArgArr( const ScFuncDesc* pNewFunc );
    void            FillListboxes();
    void            FillControls();

    xub_StrLen      GetFunctionPos(xub_StrLen nPos);
    void            UpdateTokenArray( const String& rStrExp);

    ScRefEdit*      GetCurrRefEdit();

    DECL_LINK( ScrollHdl, ScParaWin* );
    DECL_LINK( ModifyHdl, ScParaWin* );
    DECL_LINK( FxHdl, ScParaWin* );

    DECL_LINK( MatrixHdl, CheckBox *);
    DECL_LINK( FormulaHdl, MultiLineEdit* );
    DECL_LINK( FormulaCursorHdl, ScEditBox*);
    DECL_LINK( BtnHdl, PushButton* );
    DECL_LINK( GetEdFocusHdl, ArgInput* );
    DECL_LINK( GetFxFocusHdl, ArgInput* );
    DECL_LINK( DblClkHdl, ScFuncPage* );
    DECL_LINK( FuncSelHdl, ScFuncPage*);
    DECL_LINK( StructSelHdl, ScStructPage * );
    DECL_LINK( UpdateFocusHdl, Timer*);
};

#endif // SC_CRNRDLG_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.520); FILE MERGED 2005/09/05 15:05:22 rt 1.3.520.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formula.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:26:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_FORMULA_HXX
#define SC_FORMULA_HXX

#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif

#ifndef SC_FUNCUTL_HXX
#include "funcutl.hxx"
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"       // ScAddress
#endif

#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif

#ifndef _SV_TABPAGE_HXX //autogen
#include <vcl/tabpage.hxx>
#endif

#ifndef _SVSTDARR_STRINGS

#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>

#endif

#ifndef _SV_TABCTRL_HXX //autogen
#include <vcl/tabctrl.hxx>
#endif

#ifndef SC_PARAWIN_HXX
#include "parawin.hxx"
#endif

#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif

#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif

#ifndef SC_CELL_HXX
#include "cell.hxx"
#endif

#ifndef SC_FUNCPAGE_HXX
#include "funcpage.hxx"
#endif

#ifndef SC_STRUCTPG_HXX
#include "structpg.hxx"
#endif

class ScViewData;
class ScDocument;
class ScFuncDesc;
class ScInputHandler;
class ScDocShell;

//============================================================================

enum ScFormulaDlgMode { SC_FORMDLG_FORMULA, SC_FORMDLG_ARGS, SC_FORMDLG_EDIT };

//============================================================================

typedef ScTabViewShell* PtrTabViewShell;

//============================================================================

//============================================================================

class ScFormulaDlg : public ScAnyRefDlg
{
public:
                    ScFormulaDlg( SfxBindings* pB, SfxChildWindow* pCW,
                                    Window* pParent, ScViewData* pViewData );
                    ~ScFormulaDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pRefDoc );
    virtual BOOL    IsRefInputMode() const;
    virtual BOOL    IsDocAllowed(SfxObjectShell* pDocSh) const;
    virtual void    SetActive();
    virtual BOOL    Close();

private:

    TabControl      aTabCtrl;
    GroupBox        aGbEdit;        //! MUST be placed before aScParaWin for initializing
    ScParaWin       aScParaWin;
    FixedText       aFtHeadLine;
    FixedInfo       aFtFuncName;
    FixedInfo       aFtFuncDesc;

    FixedText       aFtEditName;
    //FixedInfo     aFtEditDesc;

    FixedText       aFtResult;
    ValWnd          aWndResult;

    FixedText       aFtFormula;
    ScEditBox       aMEFormula;

    CheckBox        aBtnMatrix;
    HelpButton      aBtnHelp;
    CancelButton    aBtnCancel;

    PushButton      aBtnBackward;
    PushButton      aBtnForward;
    OKButton        aBtnEnd;

    ScRefEdit       aEdRef;
    ScRefButton     aRefBtn;

    FixedText       aFtFormResult;
    ValWnd          aWndFormResult;

    ScRefEdit*      pTheRefEdit;
    ScRefButton*    pTheRefButton;
    ScFuncPage*     pScFuncPage;
    ScStructPage*   pScStructPage;
    ScFormulaCell*  pCell;
    ScCompiler*     pComp;
    ScTokenArray*   pScTokA;
    String          aOldFormula;
    BOOL            bStructUpdate;
    MultiLineEdit*  pMEdit;
    BOOL            bUserMatrixFlag;
    Timer           aTimer;

    const String    aTitle1;
    const String    aTitle2;
    const String    aTxtEnd;
    const String    aTxtOk;     // hinter aBtnEnd

    ULONG           nOldHelp;
    ULONG           nOldUnique;
    ULONG           nActivWinId;
    BOOL            bIsShutDown;

    Font            aFntBold;
    Font            aFntLight;
    USHORT          nEdFocus;
//    Selection       theCurSel;
    BOOL            bEditFlag;
    const ScFuncDesc*   pFuncDesc;
    USHORT          nArgs;
    String**        pArgArr;
    Selection       aFuncSel;

    static ScDocument*  pDoc;
    static ScAddress    aCursorPos;

protected:

    virtual long    PreNotify( NotifyEvent& rNEvt );
    virtual void    RefInputStart( ScRefEdit* pEdit, ScRefButton* pButton = NULL );
    virtual void    RefInputDone( BOOL bForced = FALSE );
    ULONG           FindFocusWin(Window *pWin);
    void            SetFocusWin(Window *pWin,ULONG nUniqueId);
    String          RepairFormula(const String& aFormula);
    void            SaveLRUEntry(const ScFuncDesc*  pFuncDesc);
    void            HighlightFunctionParas(const String& aFormula);

private:

    BOOL            IsInputHdl(ScInputHandler* pHdl);
    ScInputHandler* GetNextInputHandler(ScDocShell* pDocShell,PtrTabViewShell* ppViewSh=NULL);

    void            MakeTree(SvLBoxEntry* pParent,ScToken* pScToken,long Count,
                                    ScTokenArray* pScTokA,ScCompiler*   pComp);

    void            ClearAllParas();
    void            DeleteArgs();
    void            FillDialog(BOOL nFlag=TRUE);
    void            EditNextFunc( BOOL bForward, xub_StrLen nFStart=NOT_FOUND );
    void            EditThisFunc(xub_StrLen nFStart);
    void            EditFuncParas(xub_StrLen nEditPos);

    void            UpdateArgInput( USHORT nOffset, USHORT nInput );
    BOOL            CalcValue( const String& rStrExp, String& rStrResult );
    BOOL            CalcStruct( const String& rStrExp);

    void            UpdateValues();
    void            SaveArg( USHORT nEd );
    void            UpdateSelection();
    void            DoEnter( BOOL bOk );
    void            UpdateFunctionDesc();
    void            ResizeArgArr( const ScFuncDesc* pNewFunc );
    void            FillListboxes();
    void            FillControls();

    xub_StrLen      GetFunctionPos(xub_StrLen nPos);
    void            UpdateTokenArray( const String& rStrExp);

    ScRefEdit*      GetCurrRefEdit();

    DECL_LINK( ScrollHdl, ScParaWin* );
    DECL_LINK( ModifyHdl, ScParaWin* );
    DECL_LINK( FxHdl, ScParaWin* );

    DECL_LINK( MatrixHdl, CheckBox *);
    DECL_LINK( FormulaHdl, MultiLineEdit* );
    DECL_LINK( FormulaCursorHdl, ScEditBox*);
    DECL_LINK( BtnHdl, PushButton* );
    DECL_LINK( GetEdFocusHdl, ArgInput* );
    DECL_LINK( GetFxFocusHdl, ArgInput* );
    DECL_LINK( DblClkHdl, ScFuncPage* );
    DECL_LINK( FuncSelHdl, ScFuncPage*);
    DECL_LINK( StructSelHdl, ScStructPage * );
    DECL_LINK( UpdateFocusHdl, Timer*);
};

#endif // SC_CRNRDLG_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: gridwin.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-08 15:44:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_GRIDWIN_HXX
#define SC_GRIDWIN_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

// nur auf dem MAC Auto-Filter per Popup
#ifdef MAC
#define AUTOFILTER_POPUP
#else
#undef AUTOFILTER_POPUP
#endif

#ifndef SC_VIEWUTIL_HXX
#include "viewutil.hxx"
#endif

#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef SC_CBUTTON_HXX
#include "cbutton.hxx"
#endif

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

struct ScTableInfo;
class ScViewSelectionEngine;
class ScPivot;
class ScDPObject;
class ScOutputData;
class ScFilterListBox;
class AutoFilterPopup;
class SdrObject;
class SdrEditView;
class ScNoteMarker;
class FloatingWindow;
class SdrHdlList;
class ScTransferObj;
struct SpellCallbackInfo;

        //  Maus-Status (nMouseStatus)

#define SC_GM_NONE          0
#define SC_GM_TABDOWN       1
#define SC_GM_DBLDOWN       2
#define SC_GM_FILTER        3
#define SC_GM_IGNORE        4
#define SC_GM_WATERUNDO     5
#define SC_GM_URLDOWN       6

        //  Page-Drag-Modus

#define SC_PD_NONE          0
#define SC_PD_RANGE_L       1
#define SC_PD_RANGE_R       2
#define SC_PD_RANGE_T       4
#define SC_PD_RANGE_B       8
#define SC_PD_RANGE_TL      (SC_PD_RANGE_T|SC_PD_RANGE_L)
#define SC_PD_RANGE_TR      (SC_PD_RANGE_T|SC_PD_RANGE_R)
#define SC_PD_RANGE_BL      (SC_PD_RANGE_B|SC_PD_RANGE_L)
#define SC_PD_RANGE_BR      (SC_PD_RANGE_B|SC_PD_RANGE_R)
#define SC_PD_BREAK_H       16
#define SC_PD_BREAK_V       32

class ScHideTextCursor
{
private:
    ScViewData* pViewData;
    ScSplitPos  eWhich;

public:
            ScHideTextCursor( ScViewData* pData, ScSplitPos eW );
            ~ScHideTextCursor();
};

class ScGridWindow : public Window, public DropTargetHelper, public DragSourceHelper
{
    //  ScFilterListBox wird immer fuer Auswahlliste benutzt
    friend class ScFilterListBox;
#ifdef AUTOFILTER_POPUP
    friend class AutoFilterPopup;
#endif

private:
    ScViewData*             pViewData;
    ScSplitPos              eWhich;
    ScHSplitPos             eHWhich;
    ScVSplitPos             eVWhich;

    ScNoteMarker*           pNoteMarker;

    ScFilterListBox*        pFilterBox;
    FloatingWindow*         pFilterFloat;

    USHORT                  nCursorHideCount;

    BOOL                    bMarking;

    USHORT                  nButtonDown;
    BOOL                    bEEMouse;               // Edit-Engine hat Maus
    BYTE                    nMouseStatus;
    BYTE                    nNestedButtonState;     // track nested button up/down calls

    BOOL                    bPivotMouse;            // Pivot-D&D (alte Pivottabellen)
    ScPivot*                pDragPivot;
    BOOL                    bPivotColField;
    SCCOL                   nPivotCol;
    SCCOL                   nPivotField;

    BOOL                    bDPMouse;               // DataPilot-D&D (neue Pivottabellen)
    long                    nDPField;
    ScDPObject*             pDragDPObj; //! name?

    BOOL                    bRFMouse;               // RangeFinder-Drag
    BOOL                    bRFSize;
    USHORT                  nRFIndex;
    SCsCOL                  nRFAddX;
    SCsROW                  nRFAddY;

    USHORT                  nPagebreakMouse;        // Pagebreak-Modus Drag
    SCCOLROW                nPagebreakBreak;
    SCCOLROW                nPagebreakPrev;
    ScRange                 aPagebreakSource;
    ScRange                 aPagebreakDrag;
    BOOL                    bPagebreakDrawn;

    BYTE                    nPageScript;

    long                    nLastClickX;
    long                    nLastClickY;

    BOOL                    bDragRect;
    SCCOL                   nDragStartX;
    SCROW                   nDragStartY;
    SCCOL                   nDragEndX;
    SCROW                   nDragEndY;

    USHORT                  nCurrentPointer;

    BOOL                    bIsInScroll;
    BOOL                    bIsInPaint;

    ScDDComboBoxButton      aComboButton;

    Point                   aCurMousePos;

    USHORT                  nPaintCount;
    Rectangle               aRepaintPixel;
    BOOL                    bNeedsRepaint;

    BOOL                    bAutoMarkVisible;
    ScAddress               aAutoMarkPos;

    BOOL                    bListValButton;
    ScAddress               aListValPos;

    Rectangle               aInvertRect;

    DECL_LINK( PopupModeEndHdl, FloatingWindow* );
    DECL_LINK( PopupSpellingHdl, SpellCallbackInfo* );

    BOOL            TestMouse( const MouseEvent& rMEvt, BOOL bAction );

    BOOL            DoPageFieldSelection( SCCOL nCol, SCROW nRow );
    void            DoPushButton( SCCOL nCol, SCROW nRow, const MouseEvent& rMEvt );
    void            PivotMouseMove( const MouseEvent& rMEvt );
    void            PivotMouseButtonUp( const MouseEvent& rMEvt );
    BOOL            PivotTestMouse( const MouseEvent& rMEvt, BOOL bMove );
    void            DoPivotDrop( BOOL bDelete, BOOL bToCols, SCSIZE nDestPos );

    void            DPMouseMove( const MouseEvent& rMEvt );
    void            DPMouseButtonUp( const MouseEvent& rMEvt );
    void            DPTestMouse( const MouseEvent& rMEvt, BOOL bMove );

    void            RFMouseMove( const MouseEvent& rMEvt, BOOL bUp );

    void            PagebreakMove( const MouseEvent& rMEvt, BOOL bUp );

    void            UpdateDragRect( BOOL bShowRange, const Rectangle& rPosRect );

    BOOL            IsAutoFilterActive( SCCOL nCol, SCROW nRow, SCTAB nTab );
    void            ExecFilter( ULONG nSel, SCCOL nCol, SCROW nRow,
                                const String& aValue );
    void            FilterSelect( ULONG nSel );

    void            ExecDataSelect( SCCOL nCol, SCROW nRow, const String& rStr );

    void            ExecPageFieldSelect( SCCOL nCol, SCROW nRow, BOOL bHasSelection, const String& rStr );

    BOOL            HasScenarioButton( const Point& rPosPixel, ScRange& rScenRange );

    BOOL            DropScroll( const Point& rMousePos );

    sal_Int8        AcceptPrivateDrop( const AcceptDropEvent& rEvt );
    sal_Int8        ExecutePrivateDrop( const ExecuteDropEvent& rEvt );
    sal_Int8        DropTransferObj( ScTransferObj* pTransObj, SCCOL nDestPosX, SCROW nDestPosY,
                                    const Point& rLogicPos, sal_Int8 nDndAction );

    void            HandleMouseButtonDown( const MouseEvent& rMEvt );

    BOOL            DrawMouseButtonDown(const MouseEvent& rMEvt);
    BOOL            DrawMouseButtonUp(const MouseEvent& rMEvt);
    BOOL            DrawMouseMove(const MouseEvent& rMEvt);
    BOOL            DrawKeyInput(const KeyEvent& rKEvt);
    BOOL            DrawCommand(const CommandEvent& rCEvt);
    BOOL            DrawHasMarkedObj();
    void            DrawEndAction();
    void            DrawMarkDropObj( SdrObject* pObj );
    SdrObject*      GetEditObject();
    BOOL            IsMyModel(SdrEditView* pSdrView);
    void            DrawStartTimer();

    void            DrawRedraw( ScOutputData& rOutputData, const Rectangle& rDrawingRect,
                                        ScUpdateMode eMode, ULONG nLayer );
    void            DrawSdrGrid( const Rectangle& rDrawingRect );
    BOOL            DrawBeforeScroll();
    void            DrawAfterScroll(BOOL bVal);
    void            OutlinerViewPaint( const Rectangle& rRect );
    void            DrawMarks();
    BOOL            NeedDrawMarks();
    void            DrawComboButton( const Point&   rCellPos,
                                     long           nCellSizeX,
                                     long           nCellSizeY,
                                     BOOL           bArrowState,
                                     BOOL           bBtnIn  = FALSE );
    Rectangle       GetListValButtonRect( const ScAddress& rButtonPos );

    void            DrawPagePreview( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );

    BOOL            GetEditUrl( const Point& rPos,
                                String* pName=0, String* pUrl=0, String* pTarget=0 );
    BOOL            GetEditUrlOrError( BOOL bSpellErr, const Point& rPos,
                                String* pName=0, String* pUrl=0, String* pTarget=0 );

    BOOL            HitRangeFinder( const Point& rMouse, BOOL& rCorner, USHORT* pIndex = NULL,
                                        SCsCOL* pAddX = NULL, SCsROW* pAddY = NULL );

    USHORT          HitPageBreak( const Point& rMouse, ScRange* pSource = NULL,
                                    SCCOLROW* pBreak = NULL, SCCOLROW* pPrev = NULL );

#ifdef AUTOFILTER_POPUP
    void            DoAutoFilterPopup( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
#endif

    void            PasteSelection( const Point& rPosPixel );

    void            SelectForContextMenu( const Point& rPosPixel );

protected:
    virtual void    Resize( const Size& rSize );
    virtual void    Paint( const Rectangle& rRect );
    virtual void    KeyInput(const KeyEvent& rKEvt);
    virtual void    GetFocus();
    virtual void    LoseFocus();

    virtual void    RequestHelp( const HelpEvent& rEvt );
    virtual void    Command( const CommandEvent& rCEvt );

    virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
    virtual void    StartDrag( sal_Int8 nAction, const Point& rPosPixel );

public:
    ScGridWindow( Window* pParent, ScViewData* pData, ScSplitPos eWhichPos );
    ~ScGridWindow();

    virtual void    DataChanged( const DataChangedEvent& rDCEvt );

    virtual void    MouseButtonDown( const MouseEvent& rMEvt );
    virtual void    MouseButtonUp( const MouseEvent& rMEvt );
    virtual void    MouseMove( const MouseEvent& rMEvt );
    virtual long    PreNotify( NotifyEvent& rNEvt );
    virtual void    Tracking( const TrackingEvent& rTEvt );

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

    void            FakeButtonUp();

    Point           GetMousePosPixel() const;
    void            UpdateStatusPosSize();

    void            ClickExtern();

    void            SetPointer( const Pointer& rPointer );

    void            MoveMouseStatus( ScGridWindow &rDestWin );

    void            ScrollPixel( long nDifX, long nDifY );
    void            UpdateEditViewPos();

    void            UpdateFormulas();

    void            DoAutoFilterMenue( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
    void            DoScenarioMenue( const ScRange& rScenRange );
    void            DoPageFieldMenue( SCCOL nCol, SCROW nRow );

    BOOL            HasPageFieldData( SCCOL nCol, SCROW nRow ) const;

    void            DrawButtons( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                                    ScTableInfo& rTabInfo );

    void            Draw( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                        ScUpdateMode eMode = SC_UPDATE_ALL );

    void            InvertSimple( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                                    BOOL bTestMerge = FALSE, BOOL bRepeat = FALSE );

    void            DrawDragRect( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                                    BOOL bMarkDrop = TRUE );

    void            DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,
                                    SCCOL nRefEndX, SCROW nRefEndY,
                                    const Color& rColor, BOOL bHandle );

    void            CreateAnchorHandle(SdrHdlList& rHdl, const ScAddress& rAddress);

    void            HideCursor();
    void            ShowCursor();
    void            DrawCursor();
    void            DrawAutoFillMark();
    void            UpdateAutoFillMark(BOOL bMarked, const ScRange& rMarkRange);

    void            UpdateListValPos( BOOL bVisible, const ScAddress& rPos );

    BOOL            ShowNoteMarker( SCsCOL nPosX, SCsROW nPosY, BOOL bKeyboard );
    void            HideNoteMarker();

    MapMode         GetDrawMapMode( BOOL bForce = FALSE );

    void            ContinueDrag();

    void            StopMarking();
    void            UpdateInputContext();

    void            CheckInverted()     { if (nPaintCount) bNeedsRepaint = TRUE; }

    void            DoInvertRect( const Rectangle& rPixel );

    void            CheckNeedsRepaint();
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.20.128); FILE MERGED 2005/09/05 15:05:27 rt 1.20.128.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gridwin.hxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:30:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_GRIDWIN_HXX
#define SC_GRIDWIN_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

// nur auf dem MAC Auto-Filter per Popup
#ifdef MAC
#define AUTOFILTER_POPUP
#else
#undef AUTOFILTER_POPUP
#endif

#ifndef SC_VIEWUTIL_HXX
#include "viewutil.hxx"
#endif

#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef SC_CBUTTON_HXX
#include "cbutton.hxx"
#endif

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

struct ScTableInfo;
class ScViewSelectionEngine;
class ScPivot;
class ScDPObject;
class ScOutputData;
class ScFilterListBox;
class AutoFilterPopup;
class SdrObject;
class SdrEditView;
class ScNoteMarker;
class FloatingWindow;
class SdrHdlList;
class ScTransferObj;
struct SpellCallbackInfo;

        //  Maus-Status (nMouseStatus)

#define SC_GM_NONE          0
#define SC_GM_TABDOWN       1
#define SC_GM_DBLDOWN       2
#define SC_GM_FILTER        3
#define SC_GM_IGNORE        4
#define SC_GM_WATERUNDO     5
#define SC_GM_URLDOWN       6

        //  Page-Drag-Modus

#define SC_PD_NONE          0
#define SC_PD_RANGE_L       1
#define SC_PD_RANGE_R       2
#define SC_PD_RANGE_T       4
#define SC_PD_RANGE_B       8
#define SC_PD_RANGE_TL      (SC_PD_RANGE_T|SC_PD_RANGE_L)
#define SC_PD_RANGE_TR      (SC_PD_RANGE_T|SC_PD_RANGE_R)
#define SC_PD_RANGE_BL      (SC_PD_RANGE_B|SC_PD_RANGE_L)
#define SC_PD_RANGE_BR      (SC_PD_RANGE_B|SC_PD_RANGE_R)
#define SC_PD_BREAK_H       16
#define SC_PD_BREAK_V       32

class ScHideTextCursor
{
private:
    ScViewData* pViewData;
    ScSplitPos  eWhich;

public:
            ScHideTextCursor( ScViewData* pData, ScSplitPos eW );
            ~ScHideTextCursor();
};

class ScGridWindow : public Window, public DropTargetHelper, public DragSourceHelper
{
    //  ScFilterListBox wird immer fuer Auswahlliste benutzt
    friend class ScFilterListBox;
#ifdef AUTOFILTER_POPUP
    friend class AutoFilterPopup;
#endif

private:
    ScViewData*             pViewData;
    ScSplitPos              eWhich;
    ScHSplitPos             eHWhich;
    ScVSplitPos             eVWhich;

    ScNoteMarker*           pNoteMarker;

    ScFilterListBox*        pFilterBox;
    FloatingWindow*         pFilterFloat;

    USHORT                  nCursorHideCount;

    BOOL                    bMarking;

    USHORT                  nButtonDown;
    BOOL                    bEEMouse;               // Edit-Engine hat Maus
    BYTE                    nMouseStatus;
    BYTE                    nNestedButtonState;     // track nested button up/down calls

    BOOL                    bPivotMouse;            // Pivot-D&D (alte Pivottabellen)
    ScPivot*                pDragPivot;
    BOOL                    bPivotColField;
    SCCOL                   nPivotCol;
    SCCOL                   nPivotField;

    BOOL                    bDPMouse;               // DataPilot-D&D (neue Pivottabellen)
    long                    nDPField;
    ScDPObject*             pDragDPObj; //! name?

    BOOL                    bRFMouse;               // RangeFinder-Drag
    BOOL                    bRFSize;
    USHORT                  nRFIndex;
    SCsCOL                  nRFAddX;
    SCsROW                  nRFAddY;

    USHORT                  nPagebreakMouse;        // Pagebreak-Modus Drag
    SCCOLROW                nPagebreakBreak;
    SCCOLROW                nPagebreakPrev;
    ScRange                 aPagebreakSource;
    ScRange                 aPagebreakDrag;
    BOOL                    bPagebreakDrawn;

    BYTE                    nPageScript;

    long                    nLastClickX;
    long                    nLastClickY;

    BOOL                    bDragRect;
    SCCOL                   nDragStartX;
    SCROW                   nDragStartY;
    SCCOL                   nDragEndX;
    SCROW                   nDragEndY;

    USHORT                  nCurrentPointer;

    BOOL                    bIsInScroll;
    BOOL                    bIsInPaint;

    ScDDComboBoxButton      aComboButton;

    Point                   aCurMousePos;

    USHORT                  nPaintCount;
    Rectangle               aRepaintPixel;
    BOOL                    bNeedsRepaint;

    BOOL                    bAutoMarkVisible;
    ScAddress               aAutoMarkPos;

    BOOL                    bListValButton;
    ScAddress               aListValPos;

    Rectangle               aInvertRect;

    DECL_LINK( PopupModeEndHdl, FloatingWindow* );
    DECL_LINK( PopupSpellingHdl, SpellCallbackInfo* );

    BOOL            TestMouse( const MouseEvent& rMEvt, BOOL bAction );

    BOOL            DoPageFieldSelection( SCCOL nCol, SCROW nRow );
    void            DoPushButton( SCCOL nCol, SCROW nRow, const MouseEvent& rMEvt );
    void            PivotMouseMove( const MouseEvent& rMEvt );
    void            PivotMouseButtonUp( const MouseEvent& rMEvt );
    BOOL            PivotTestMouse( const MouseEvent& rMEvt, BOOL bMove );
    void            DoPivotDrop( BOOL bDelete, BOOL bToCols, SCSIZE nDestPos );

    void            DPMouseMove( const MouseEvent& rMEvt );
    void            DPMouseButtonUp( const MouseEvent& rMEvt );
    void            DPTestMouse( const MouseEvent& rMEvt, BOOL bMove );

    void            RFMouseMove( const MouseEvent& rMEvt, BOOL bUp );

    void            PagebreakMove( const MouseEvent& rMEvt, BOOL bUp );

    void            UpdateDragRect( BOOL bShowRange, const Rectangle& rPosRect );

    BOOL            IsAutoFilterActive( SCCOL nCol, SCROW nRow, SCTAB nTab );
    void            ExecFilter( ULONG nSel, SCCOL nCol, SCROW nRow,
                                const String& aValue );
    void            FilterSelect( ULONG nSel );

    void            ExecDataSelect( SCCOL nCol, SCROW nRow, const String& rStr );

    void            ExecPageFieldSelect( SCCOL nCol, SCROW nRow, BOOL bHasSelection, const String& rStr );

    BOOL            HasScenarioButton( const Point& rPosPixel, ScRange& rScenRange );

    BOOL            DropScroll( const Point& rMousePos );

    sal_Int8        AcceptPrivateDrop( const AcceptDropEvent& rEvt );
    sal_Int8        ExecutePrivateDrop( const ExecuteDropEvent& rEvt );
    sal_Int8        DropTransferObj( ScTransferObj* pTransObj, SCCOL nDestPosX, SCROW nDestPosY,
                                    const Point& rLogicPos, sal_Int8 nDndAction );

    void            HandleMouseButtonDown( const MouseEvent& rMEvt );

    BOOL            DrawMouseButtonDown(const MouseEvent& rMEvt);
    BOOL            DrawMouseButtonUp(const MouseEvent& rMEvt);
    BOOL            DrawMouseMove(const MouseEvent& rMEvt);
    BOOL            DrawKeyInput(const KeyEvent& rKEvt);
    BOOL            DrawCommand(const CommandEvent& rCEvt);
    BOOL            DrawHasMarkedObj();
    void            DrawEndAction();
    void            DrawMarkDropObj( SdrObject* pObj );
    SdrObject*      GetEditObject();
    BOOL            IsMyModel(SdrEditView* pSdrView);
    void            DrawStartTimer();

    void            DrawRedraw( ScOutputData& rOutputData, const Rectangle& rDrawingRect,
                                        ScUpdateMode eMode, ULONG nLayer );
    void            DrawSdrGrid( const Rectangle& rDrawingRect );
    BOOL            DrawBeforeScroll();
    void            DrawAfterScroll(BOOL bVal);
    void            OutlinerViewPaint( const Rectangle& rRect );
    void            DrawMarks();
    BOOL            NeedDrawMarks();
    void            DrawComboButton( const Point&   rCellPos,
                                     long           nCellSizeX,
                                     long           nCellSizeY,
                                     BOOL           bArrowState,
                                     BOOL           bBtnIn  = FALSE );
    Rectangle       GetListValButtonRect( const ScAddress& rButtonPos );

    void            DrawPagePreview( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2 );

    BOOL            GetEditUrl( const Point& rPos,
                                String* pName=0, String* pUrl=0, String* pTarget=0 );
    BOOL            GetEditUrlOrError( BOOL bSpellErr, const Point& rPos,
                                String* pName=0, String* pUrl=0, String* pTarget=0 );

    BOOL            HitRangeFinder( const Point& rMouse, BOOL& rCorner, USHORT* pIndex = NULL,
                                        SCsCOL* pAddX = NULL, SCsROW* pAddY = NULL );

    USHORT          HitPageBreak( const Point& rMouse, ScRange* pSource = NULL,
                                    SCCOLROW* pBreak = NULL, SCCOLROW* pPrev = NULL );

#ifdef AUTOFILTER_POPUP
    void            DoAutoFilterPopup( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
#endif

    void            PasteSelection( const Point& rPosPixel );

    void            SelectForContextMenu( const Point& rPosPixel );

protected:
    virtual void    Resize( const Size& rSize );
    virtual void    Paint( const Rectangle& rRect );
    virtual void    KeyInput(const KeyEvent& rKEvt);
    virtual void    GetFocus();
    virtual void    LoseFocus();

    virtual void    RequestHelp( const HelpEvent& rEvt );
    virtual void    Command( const CommandEvent& rCEvt );

    virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );
    virtual void    StartDrag( sal_Int8 nAction, const Point& rPosPixel );

public:
    ScGridWindow( Window* pParent, ScViewData* pData, ScSplitPos eWhichPos );
    ~ScGridWindow();

    virtual void    DataChanged( const DataChangedEvent& rDCEvt );

    virtual void    MouseButtonDown( const MouseEvent& rMEvt );
    virtual void    MouseButtonUp( const MouseEvent& rMEvt );
    virtual void    MouseMove( const MouseEvent& rMEvt );
    virtual long    PreNotify( NotifyEvent& rNEvt );
    virtual void    Tracking( const TrackingEvent& rTEvt );

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

    void            FakeButtonUp();

    Point           GetMousePosPixel() const;
    void            UpdateStatusPosSize();

    void            ClickExtern();

    void            SetPointer( const Pointer& rPointer );

    void            MoveMouseStatus( ScGridWindow &rDestWin );

    void            ScrollPixel( long nDifX, long nDifY );
    void            UpdateEditViewPos();

    void            UpdateFormulas();

    void            DoAutoFilterMenue( SCCOL nCol, SCROW nRow, BOOL bDataSelect );
    void            DoScenarioMenue( const ScRange& rScenRange );
    void            DoPageFieldMenue( SCCOL nCol, SCROW nRow );

    BOOL            HasPageFieldData( SCCOL nCol, SCROW nRow ) const;

    void            DrawButtons( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                                    ScTableInfo& rTabInfo );

    void            Draw( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                        ScUpdateMode eMode = SC_UPDATE_ALL );

    void            InvertSimple( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                                    BOOL bTestMerge = FALSE, BOOL bRepeat = FALSE );

    void            DrawDragRect( SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,
                                    BOOL bMarkDrop = TRUE );

    void            DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY,
                                    SCCOL nRefEndX, SCROW nRefEndY,
                                    const Color& rColor, BOOL bHandle );

    void            CreateAnchorHandle(SdrHdlList& rHdl, const ScAddress& rAddress);

    void            HideCursor();
    void            ShowCursor();
    void            DrawCursor();
    void            DrawAutoFillMark();
    void            UpdateAutoFillMark(BOOL bMarked, const ScRange& rMarkRange);

    void            UpdateListValPos( BOOL bVisible, const ScAddress& rPos );

    BOOL            ShowNoteMarker( SCsCOL nPosX, SCsROW nPosY, BOOL bKeyboard );
    void            HideNoteMarker();

    MapMode         GetDrawMapMode( BOOL bForce = FALSE );

    void            ContinueDrag();

    void            StopMarking();
    void            UpdateInputContext();

    void            CheckInverted()     { if (nPaintCount) bNeedsRepaint = TRUE; }

    void            DoInvertRect( const Rectangle& rPixel );

    void            CheckNeedsRepaint();
};

#endif

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// Test running a file in the same directory `cling CurrentDir.C`.
// More info in CIFactory.cpp ("<<< cling interactive line includer >>>")

// RUN: cp "%s" "%T/CurrentDir.C" && cd %T && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s
// Test testCurrentDir

extern "C" {
  int printf(const char*, ...);
  char* getcwd(char *buf, std::size_t size);
}

void CurrentDir() {
  printf("Script ran\n"); // CHECK: Script ran
}
//expected-no-diagnostics
<commit_msg>Revert "Simplify; make Windows compatible (cannot delete cwd)."<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// Test runing a file in the same directory `cling CurrentDir.C`
// More info in CIFactory.cpp createCIImpl (line ~850)

// RUN: cd %S && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s
// RUN: mkdir %T/Remove && cd %T/Remove && rm -rf %T/Remove && %cling -DTEST_CWDRETURN %s -Xclang -verify 2>&1 | FileCheck --check-prefix CHECK --check-prefix CHECKcwd %s
// Test testCurrentDir

extern "C" {
  int printf(const char*, ...);
  char* getcwd(char *buf, std::size_t size);
}

#ifdef TEST_CWDRETURN
  // Make sure include still works
  #include <string.h>
  #include <vector>
#endif

void CurrentDir() {
 #ifdef TEST_CWDRETURN
    char thisDir[1024];
    const char *rslt = getcwd(thisDir, sizeof(thisDir));
    // Make sure cling reported the error
    // CHECKcwd: Could not get current working directory: {{.*}}

    if (rslt)
      printf("Working directory exists\n");
    // CHECK-NOT: Working directory exists
 #endif

  printf("Script ran\n");
  // CHECK: Script ran
}

//expected-no-diagnostics
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "GenCF1.h"

CGenCF1::CGenCF1()
{
	t_cnt = 10000;
	t_allocated = 10;
	Init();
}

CGenCF1::~CGenCF1()
{
}

void CGenCF1::Generate()
{
	for (int i = 0; i < t_cnt; i++) {
		if (i >= t_allocated) ResizeVectors(t_allocated * 2);
		//TCHAR st[100];
		//_stprintf_s(st, _T("%d"), rand2());
		//TRACE(st);
		if ((i > 0) && (len[i-1][0] > 1) && (coff[i-1][0] < len[i-1][0]-1)) {
			note[i][0] = note[i - 1][0];
			len[i][0] = len[i - 1][0];
			coff[i][0] = coff[i - 1][0] + 1;
			poff[i][0] = poff[i - 1][0] + 1;
		}
		else {
			note[i][0] = 60 + 12 * rand2() / RAND_MAX;
			unsigned int test = RAND_MAX;
			len[i][0] = 8 * rand2() / RAND_MAX;
			coff[i][0] = 0;
			if (i > 0) poff[i][0] = coff[i - 1][0] + 1;
			else poff[i][0] = 0;
		}
		//if (i < t_cnt-1) noff[i][0] = 1;
		//else noff[i][0] = 0;
		att[i][0] = 100;
		tempo[i][0] = 100;
		pause[i][0] = 0;
		t_generated = i+1;
		if (ng_min > note[i][0]) ng_min = note[i][0];
		if (ng_max < note[i][0]) ng_max = note[i][0];
		//CString* st = new CString;
		//st->Format("Note generated %d", note[i][0]);
		//::PostMessage(m_hWnd, WM_DEBUG_MSG, 0, (LPARAM)st);
		if (i % t_send == 0) t_sent = t_generated;
		//Sleep(1);
		if (need_exit) return;
	}
	t_sent = t_generated;
}
<commit_msg>Added noff calculation<commit_after>#include "stdafx.h"
#include "GenCF1.h"

CGenCF1::CGenCF1()
{
	t_cnt = 10000;
	t_allocated = 10;
	Init();
}

CGenCF1::~CGenCF1()
{
}

void CGenCF1::Generate()
{
	for (int i = 0; i < t_cnt; i++) {
		if (i >= t_allocated) ResizeVectors(t_allocated * 2);
		//TCHAR st[100];
		//_stprintf_s(st, _T("%d"), rand2());
		//TRACE(st);
		if ((i > 0) && (len[i-1][0] > 1) && (coff[i-1][0] < len[i-1][0]-1)) {
			note[i][0] = note[i - 1][0];
			len[i][0] = len[i - 1][0];
			coff[i][0] = coff[i - 1][0] + 1;
			poff[i][0] = poff[i - 1][0] + 1;
		}
		else {
			note[i][0] = 60 + 12 * rand2() / RAND_MAX;
			len[i][0] = max(1, 8 * rand2() / RAND_MAX);
			coff[i][0] = 0;
			if (i > 0) poff[i][0] = coff[i - 1][0] + 1;
			else poff[i][0] = 0;
			if (i > 0) {
				for (int x = i - 1; x >= i-len[i-1][0]; x--) {
					noff[x][0] = i - x;
				}
			}
		}
		//if (i < t_cnt-1) noff[i][0] = 1;
		//else noff[i][0] = 0;
		att[i][0] = 100;
		tempo[i][0] = 100;
		pause[i][0] = 0;
		t_generated = i+1;
		if (ng_min > note[i][0]) ng_min = note[i][0];
		if (ng_max < note[i][0]) ng_max = note[i][0];
		//CString* st = new CString;
		//st->Format("Note generated %d", note[i][0]);
		//::PostMessage(m_hWnd, WM_DEBUG_MSG, 0, (LPARAM)st);
		if (i % t_send == 0) t_sent = t_generated;
		//Sleep(1);
		if (need_exit) return;
	}
	t_sent = t_generated;
}
<|endoftext|>


<commit_before>#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageFileWriter.h"

#include "itkMersenneTwisterRandomVariateGenerator.h"

#include "../itkMatrixMath.h"

template< int dimensionT >
int Test( void )
{
  double epsilon = 0.000001;

  itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer rndGen
    = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
  rndGen->Initialize( 1 );

  int returnStatus = EXIT_SUCCESS;

  for( unsigned int count=0; count<1000; count++ )
    {
    vnl_vector<float> v1(dimensionT);
    for( unsigned int d=0; d<dimensionT; d++ )
      {
      v1[d] = rndGen->GetVariateWithOpenRange();
      }
    vnl_vector<float> v2(dimensionT);
    if( dimensionT == 3 )
      {
      v2 = itk::GetOrthogonalVector( v1 );
      if( dot_product( v1, v2 ) > epsilon )
        {
        std::cerr << count << " : ";
        std::cerr << "FAILURE: GetOrthogonalVector: DotProduct = "
                  << v1 << " .* " << v2 << " = "
                  << dot_product( v1, v2 ) << std::endl;
        returnStatus = EXIT_FAILURE;
        }

      vnl_vector<float> v3 = itk::GetCrossVector( v1, v2 );
      if( dot_product( v1, v3 ) > epsilon ||
          dot_product( v2, v3 ) > epsilon )
        {
        std::cerr << count << " : ";
        std::cerr << "FAILURE: GetCrossVector: DotProduct = "
          << dot_product( v1, v3 ) << " and "
          << dot_product( v2, v3 ) << std::endl;
        returnStatus = EXIT_FAILURE;
        }
      }
    else
      {
      for( unsigned int d=0; d<dimensionT; d++ )
        {
        v2[d] = rndGen->GetVariateWithOpenRange();
        }
      }

    v2 = v2.normalize();
    vnl_vector<float> v4 = itk::ComputeLineStep( v1, 0.5, v2 );
    if( vnl_math_abs( itk::ComputeEuclideanDistanceVector( v1, v4 ) - 0.5 )
        > epsilon )
      {
      std::cerr << count << " : ";
      std::cerr << "FAILURE: ComputeLineStep = "
        << v1 << " + 0.5 * " << v2 << " != " << v4 << std::endl;
      std::cerr << "FAILURE: ComputeEuclidenDistanceVector = "
        << itk::ComputeEuclideanDistanceVector( v1, v4 ) << std::endl;
      returnStatus = EXIT_FAILURE;
      }

    vnl_matrix<float> m1(dimensionT, dimensionT);
    for( unsigned int r=0; r<dimensionT; r++ )
      {
      for( unsigned int c=r; c<dimensionT; c++ )
        {
        m1(r,c) = rndGen->GetVariateWithOpenRange();
        m1(r,c) = m1(c,r);
        }
      }

    vnl_matrix<float> eVects(dimensionT, dimensionT);
    vnl_vector<float> eVals(dimensionT);
    itk::Eigen( m1, eVects, eVals, true );
    for( unsigned int d=0; d<dimensionT; d++ )
      {
      v1 = m1 * eVects.get_column(d);
      if( vnl_math_abs( v1.magnitude() - eVals[d] ) > epsilon )
        {
        std::cerr << count << " : ";
        std::cerr << "FAILURE: Eigen : "
          << " v1 * M1 = " << v1
          << " and v1 norm = " << v1.magnitude()
          << " != " << eVals[d]
          << std::endl;
        returnStatus = EXIT_FAILURE;
        }
      }
    }

  return returnStatus;
}

int itkMatrixMathTest(int itkNotUsed(argc), char * itkNotUsed(argv)[])
{

  if( Test<2>() == EXIT_FAILURE ||
      Test<3>() == EXIT_FAILURE ||
      Test<4>() == EXIT_FAILURE )
    {
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}

<commit_msg>STYLE: Missing header text<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

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 "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageFileWriter.h"

#include "itkMersenneTwisterRandomVariateGenerator.h"

#include "../itkMatrixMath.h"

template< int dimensionT >
int Test( void )
{
  double epsilon = 0.000001;

  itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer rndGen
    = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();
  rndGen->Initialize( 1 );

  int returnStatus = EXIT_SUCCESS;

  for( unsigned int count=0; count<1000; count++ )
    {
    vnl_vector<float> v1(dimensionT);
    for( unsigned int d=0; d<dimensionT; d++ )
      {
      v1[d] = rndGen->GetVariateWithOpenRange();
      }
    vnl_vector<float> v2(dimensionT);
    if( dimensionT == 3 )
      {
      v2 = itk::GetOrthogonalVector( v1 );
      if( dot_product( v1, v2 ) > epsilon )
        {
        std::cerr << count << " : ";
        std::cerr << "FAILURE: GetOrthogonalVector: DotProduct = "
                  << v1 << " .* " << v2 << " = "
                  << dot_product( v1, v2 ) << std::endl;
        returnStatus = EXIT_FAILURE;
        }

      vnl_vector<float> v3 = itk::GetCrossVector( v1, v2 );
      if( dot_product( v1, v3 ) > epsilon ||
          dot_product( v2, v3 ) > epsilon )
        {
        std::cerr << count << " : ";
        std::cerr << "FAILURE: GetCrossVector: DotProduct = "
          << dot_product( v1, v3 ) << " and "
          << dot_product( v2, v3 ) << std::endl;
        returnStatus = EXIT_FAILURE;
        }
      }
    else
      {
      for( unsigned int d=0; d<dimensionT; d++ )
        {
        v2[d] = rndGen->GetVariateWithOpenRange();
        }
      }

    v2 = v2.normalize();
    vnl_vector<float> v4 = itk::ComputeLineStep( v1, 0.5, v2 );
    if( vnl_math_abs( itk::ComputeEuclideanDistanceVector( v1, v4 ) - 0.5 )
        > epsilon )
      {
      std::cerr << count << " : ";
      std::cerr << "FAILURE: ComputeLineStep = "
        << v1 << " + 0.5 * " << v2 << " != " << v4 << std::endl;
      std::cerr << "FAILURE: ComputeEuclidenDistanceVector = "
        << itk::ComputeEuclideanDistanceVector( v1, v4 ) << std::endl;
      returnStatus = EXIT_FAILURE;
      }

    vnl_matrix<float> m1(dimensionT, dimensionT);
    for( unsigned int r=0; r<dimensionT; r++ )
      {
      for( unsigned int c=r; c<dimensionT; c++ )
        {
        m1(r,c) = rndGen->GetVariateWithOpenRange();
        m1(r,c) = m1(c,r);
        }
      }

    vnl_matrix<float> eVects(dimensionT, dimensionT);
    vnl_vector<float> eVals(dimensionT);
    itk::Eigen( m1, eVects, eVals, true );
    for( unsigned int d=0; d<dimensionT; d++ )
      {
      v1 = m1 * eVects.get_column(d);
      if( vnl_math_abs( v1.magnitude() - eVals[d] ) > epsilon )
        {
        std::cerr << count << " : ";
        std::cerr << "FAILURE: Eigen : "
          << " v1 * M1 = " << v1
          << " and v1 norm = " << v1.magnitude()
          << " != " << eVals[d]
          << std::endl;
        returnStatus = EXIT_FAILURE;
        }
      }
    }

  return returnStatus;
}

int itkMatrixMathTest(int itkNotUsed(argc), char * itkNotUsed(argv)[])
{

  if( Test<2>() == EXIT_FAILURE ||
      Test<3>() == EXIT_FAILURE ||
      Test<4>() == EXIT_FAILURE )
    {
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}

<|endoftext|>