<commit_before>#include "utils.hpp"
#include <cmath>

namespace utils{

    // Função Soma
    double add(double v1, double v2) {

        return (v1 + v2);
    }

    // Função Subtração
    double sub(double v1, double v2) {

        return (v1 - v2);
    }

    // Função Multiplicação
    double mult(double v1, double v2) {

        return (v1 * v2);
    }

    // Função Divisão
    double div(double v1, double v2) {

        if (v2 == 0) {
            return 0;   //Padrão
        }
        else {
            return (v1 / v2);
        }
    }

    // Função Potência
    double pow(double v1, double v2) {

        if ((v1 == 0)&&(v2 == 0)) {
            return 0;   //Padrão - Equivalente matemático a 0/0
        }
        else {
            return pow(v1, v2);
        }
    }

    // Função Exponencial (e^v)
    double exp(double v) {

        return (exp(v));
    }

    // Função Raiz Quadrada
    double sqrt(double v) {

        if (v < 0) {
            return 0;
        }
        else {
            return (sqrt(v));
        }
    }

    // Função Logaritmo Neperiano
    double ln(double v) {

        if (v > 0) {
            return (log(v));
        }
        else {
            return 0;
        }
    }

    // Converter radianos em graus para poder utilizar as funções trigonométricas
    double rad_to_degrees(double v) {

        double V = ((v*180)/(M_PI));
        while (V > 360) V -= 360;
        while (V < -360) V += 360;
        if (V < 0) V = 360-V;
        return V;
    }

    // Função Seno
    double sin(double v) {

        return (sin(rad_to_degrees(v)));
    }

    // Função Cosseno
    double cos(double v) {

        return (cos(rad_to_degrees(v)));
    }

    // Função Tangente
    double tan(double v) {

        double V = rad_to_degrees(v);
        if ((V == 90)||(V == 270)) {
            return 0;
        }
        else {
            return (tan(V));
        }
    }

    double func1_solver(int F_id, double v) {

        switch (F_id) {
            case LN:
                return ln(v);
            case EXP:
                return exp(v);
            case SQRT:
                return sqrt(v);
            case SIN:
                return sin(v);
            case COS:
                return cos(v);
            case TAN:
                return tan(v);
        }
    }

    double func2_solver(int F_id, double v1, double v2) {

        switch (F_id) {
            case ADD:
                return add(v1, v2);
            case SUB:
                return sub(v1, v2);
            case MULT:
                return mult(v1, v2);
            case DIV:
                return div(v1, v2);
            case POW:
                return pow(v1, v2);
        }
    }
}<commit_msg>1.1.1 Renomeamento<commit_after>#include "utils.hpp"

#include <cmath>
#include <iostream>

namespace utils{

    // Função Soma
    double uAdd(double v1, double v2) {

        return (v1 + v2);
    }

    // Função Subtração
    double uSub(double v1, double v2) {

        return (v1 - v2);
    }

    // Função Multiplicação
    double uMult(double v1, double v2) {

        return (v1 * v2);
    }

    // Função Divisão
    double uDiv(double v1, double v2) {

        if (v2 == 0) {
            return 0;   //Padrão
        }
        else {
            return (v1 / v2);
        }
    }

    // Função Potência
    double uPow(double v1, double v2) {

        if ((v1 == 0)&&(v2 == 0)) {
            return 0;   //Padrão - Equivalente matemático a 0/0
        }
        else {
            return pow(v1, v2);
        }
    }

    // Função Exponencial (e^v)
    double uExp(double v) {

        return (exp(v));
    }

    // Função Raiz Quadrada
    double uSqrt(double v) {

        if (v < 0) {
            return 0;
        }
        else {
            return (sqrt(v));
        }
    }

    // Função Logaritmo Neperiano
    double uLn(double v) {

        if (v > 0) {
            return (log(v));
        }
        else {
            return 0;
        }
    }

    // Converter radianos em graus para poder utilizar as funções trigonométricas
    double rad_to_degrees(double v) {

        double V = ((v*180)/(M_PI));
        while (V > 360) V -= 360;
        while (V < -360) V += 360;
        if (V < 0) V = 360-V;
        return V;
    }

    // Função Seno
    double uSin(double v) {

        return (sin(rad_to_degrees(v)));
    }

    // Função Cosseno
    double uCos(double v) {

        return (cos(rad_to_degrees(v)));
    }

    // Função Tangente
    double uTan(double v) {

        double V = rad_to_degrees(v);
        if ((V == 90)||(V == 270)) {
            return 0;
        }
        else {
            return (tan(V));
        }
    }

    double func1_solver(int F_id, double v) {

        switch (F_id) {
            case LN:
                return uLn(v);
                break;
            case EXP:
                return uExp(v);
                break;
            case SQRT:
                return uSqrt(v);
                break;
            case SIN:
                return uSin(v);
                break;
            case COS:
                return uCos(v);
                break;
            case TAN:
                return tan(v);
                break;
            default:
                std::cout << "ERRO FUNC1 SOLVER" << std::endl;
        }
    }

    double func2_solver(int F_id, double v1, double v2) {

        switch (F_id) {
            case ADD:
                return uAdd(v1, v2);
                break;
            case SUB:
                return uSub(v1, v2);
                break;
            case MULT:
                return uMult(v1, v2);
                break;
            case DIV:
                return uDiv(v1, v2);
                break;
            case POW:
                return uPow(v1, v2);
                break;
            default:
                std::cout << "ERRO FUNC2 SOLVER" << std::endl;
        }
    }
}
<|endoftext|>


<commit_before>#include "List.hpp"

#include "../App.hpp"

using namespace morda;

namespace{

class StaticProvider : public List::ItemsProvider{
	std::vector<std::unique_ptr<stob::Node>> widgets;
public:

	size_t count() const NOEXCEPT override{
		return this->widgets.size();
	}

	std::shared_ptr<Widget> getWidget(size_t index)override{
		TRACE(<< "StaticProvider::getWidget(): index = " << index << std::endl)
		return morda::App::Inst().inflater.Inflate(*(this->widgets[index]));
	}

	void recycle(size_t index, std::shared_ptr<Widget> w)override{
		TRACE(<< "StaticProvider::recycle(): index = " << index << std::endl)
	}

	void add(std::unique_ptr<stob::Node> w){
		this->widgets.push_back(std::move(w));
	}
};

}

List::List(bool isVertical, const stob::Node* chain):
		Widget(chain),
		isVertical(isVertical)
{
	if(!chain){
		return;
	}

	const stob::Node* n = chain->ThisOrNextNonProperty().node();

	if(!n){
		return;
	}

	std::shared_ptr<StaticProvider> p = ting::New<StaticProvider>();

	for(; n; n = n->NextNonProperty().node()){
		p->add(n->Clone());
	}

	this->setItemsProvider(std::move(p));
}

void List::OnResize() {
	this->numTailItems = 0;//means that it needs to be recomputed

	this->updateChildrenList();
}

void List::setItemsProvider(std::shared_ptr<ItemsProvider> provider){
	if(this->provider){
		this->provider->list = nullptr;
	}
	this->provider = std::move(provider);
	if(this->provider){
		this->provider->list = this;
	}
	this->notifyDataSetChanged();
}

real List::scrollFactor()const NOEXCEPT{
	if(!this->provider || this->provider->count() == 0){
		return 0;
	}
	return real(this->posIndex) / real(this->provider->count() - this->visibleCount());
}

void List::setScrollPosAsFactor(real factor){
	if(!this->provider || this->provider->count() == 0){
		return;
	}

	if(this->numTailItems == 0){
		this->updateTailItemsInfo();
	}

	this->posIndex = size_t(factor * real(this->provider->count() - this->numTailItems));

//	TRACE(<< "List::setScrollPosAsFactor(): this->posIndex = " << this->posIndex << std::endl)

	if(this->provider->count() != this->numTailItems){
		real intFactor = real(this->posIndex) / real(this->provider->count() - this->numTailItems);

		if(this->Children().size() != 0){
			real d;
			if(this->isVertical){
				d = this->Children().front()->Rect().d.y;
			}else{
				d = this->Children().front()->Rect().d.x;
			}

			this->posOffset = ting::math::Round(d * (factor - intFactor) * real(this->provider->count() - this->numTailItems) + factor * this->firstTailItemOffset);
		}else{
			this->posOffset = 0;
		}
	}else{
		ASSERT(this->posIndex == 0)
		this->posOffset = ting::math::Round(factor * this->firstTailItemOffset);
	}

	this->updateChildrenList();
}

bool List::arrangeWidget(std::shared_ptr<Widget>& w, real& pos, bool added, size_t index, T_ChildrenList::const_iterator insertBefore){
	auto& lp = this->GetLayoutParamsAs<LayoutParams>(*w);

	Vec2r dim = this->dimForWidget(*w, lp);

	w->Resize(dim);

	if(this->isVertical){
		pos -= w->Rect().d.y;
		w->MoveTo(Vec2r(0, pos));

		if(pos < this->Rect().d.y){
			if(!added){
				this->Add(w, insertBefore);
			}
			if(this->addedIndex > index){
				this->addedIndex = index;
			}
		}else{
			if(added){
				auto widget = this->Remove(*w);
				if(this->provider){
					this->provider->recycle(index, widget);
				}
				++this->addedIndex;
			}
			++this->posIndex;
			this->posOffset -= w->Rect().d.y;
		}

		if(w->Rect().p.y <= 0){
			return true;
		}
	}else{
		w->MoveTo(Vec2r(pos, 0));
		pos += w->Rect().d.x;

		if(pos > 0){
			if(!added){
				this->Add(w, insertBefore);
			}
			if(this->addedIndex > index){
				this->addedIndex = index;
			}
		}else{
			if(added){
				auto widget = this->Remove(*w);
				if(this->provider){
					this->provider->recycle(index, widget);
				}
				++this->addedIndex;
			}
			++this->posIndex;
			this->posOffset -= w->Rect().d.x;
		}

		if(w->Rect().Right() >= this->Rect().d.x){
			return true;
		}
	}
	return false;
}

void List::updateChildrenList(){
	if(!this->provider){
		this->posIndex = 0;
		this->posOffset = 0;

		this->removeAll();
		this->addedIndex = size_t(-1);
		return;
	}

	if(this->numTailItems == 0){
		this->updateTailItemsInfo();
	}

	real pos;

	if(this->isVertical){
		pos = this->Rect().d.y + this->posOffset;
	}else{
		pos = -this->posOffset;
	}

	TRACE(<< "List::updateChildrenList(): this->addedIndex = " << this->addedIndex << " this->posIndex = " << this->posIndex << std::endl)

	//remove widgets from top
	for(; this->Children().size() != 0 && this->addedIndex < this->posIndex; ++this->addedIndex){
		auto w = (*this->Children().begin())->RemoveFromParent();
		if(this->provider){
			this->provider->recycle(this->addedIndex, w);
		}
	}

	auto iter = this->Children().begin();
	size_t iterIndex = this->addedIndex;
	size_t iterEndIndex = iterIndex + this->Children().size();
	size_t index = this->posIndex;
	for(; index < this->provider->count();){
		std::shared_ptr<Widget> w;
		bool isAdded;
		if(iterIndex <= index && index < iterEndIndex && iter != this->Children().end()){
			w = *iter;
			++iter;
			++iterIndex;
			isAdded = true;
		}else{
			w = this->provider->getWidget(index);
			isAdded = false;
		}

		if(this->arrangeWidget(w, pos, isAdded, index, iter)){
			++index;
			break;
		}
		++index;
	}

	//remove rest
	if(iterIndex < iterEndIndex){
		size_t oldIterIndex = iterIndex;
		for(;;){
			auto i = iter;
			++i;
			++iterIndex;
			if(i == this->Children().end()){
				break;
			}
			auto w = this->Remove(i);
			if(this->provider){
				this->provider->recycle(iterIndex, w);
			}
		}
		auto w = this->Remove(iter);
		if(this->provider){
			this->provider->recycle(oldIterIndex, w);
		}
	}

}

void List::updateTailItemsInfo(){
	this->numTailItems = 0;

	if(!this->provider || this->provider->count() == 0){
		return;
	}

	real dim;

	if(this->isVertical){
		dim = this->Rect().d.y;
	}else{
		dim = this->Rect().d.x;
	}

	ASSERT(this->provider)
	ASSERT(this->provider->count() > 0)

	for(size_t i = this->provider->count(); i != 0 && dim > 0; --i){
		++this->numTailItems;

		auto w = this->provider->getWidget(i - 1);

		auto& lp = this->GetLayoutParamsAs<LayoutParams>(*w);

		Vec2r d = this->dimForWidget(*w, lp);

		if(this->isVertical){
			dim -= d.y;
		}else{
			dim -= d.x;
		}
	}

	if(dim > 0){
		this->firstTailItemOffset = -1;
	}else{
		this->firstTailItemOffset = -dim;
	}
}
<commit_msg>stuff<commit_after>#include "List.hpp"

#include "../App.hpp"

using namespace morda;

namespace{

class StaticProvider : public List::ItemsProvider{
	std::vector<std::unique_ptr<stob::Node>> widgets;
public:

	size_t count() const NOEXCEPT override{
		return this->widgets.size();
	}

	std::shared_ptr<Widget> getWidget(size_t index)override{
		TRACE(<< "StaticProvider::getWidget(): index = " << index << std::endl)
		return morda::App::Inst().inflater.Inflate(*(this->widgets[index]));
	}

	void recycle(size_t index, std::shared_ptr<Widget> w)override{
		TRACE(<< "StaticProvider::recycle(): index = " << index << std::endl)
	}

	void add(std::unique_ptr<stob::Node> w){
		this->widgets.push_back(std::move(w));
	}
};

}

List::List(bool isVertical, const stob::Node* chain):
		Widget(chain),
		isVertical(isVertical)
{
	if(!chain){
		return;
	}

	const stob::Node* n = chain->ThisOrNextNonProperty().node();

	if(!n){
		return;
	}

	std::shared_ptr<StaticProvider> p = ting::New<StaticProvider>();

	for(; n; n = n->NextNonProperty().node()){
		p->add(n->Clone());
	}

	this->setItemsProvider(std::move(p));
}

void List::OnResize() {
	this->numTailItems = 0;//means that it needs to be recomputed

	this->updateChildrenList();
}

void List::setItemsProvider(std::shared_ptr<ItemsProvider> provider){
	if(this->provider){
		this->provider->list = nullptr;
	}
	this->provider = std::move(provider);
	if(this->provider){
		this->provider->list = this;
	}
	this->notifyDataSetChanged();
}

real List::scrollFactor()const NOEXCEPT{
	if(!this->provider || this->provider->count() == 0){
		return 0;
	}
	return real(this->posIndex) / real(this->provider->count() - this->visibleCount());
}

void List::setScrollPosAsFactor(real factor){
	if(!this->provider || this->provider->count() == 0){
		return;
	}

	if(this->numTailItems == 0){
		this->updateTailItemsInfo();
	}

	this->posIndex = size_t(factor * real(this->provider->count() - this->numTailItems));

//	TRACE(<< "List::setScrollPosAsFactor(): this->posIndex = " << this->posIndex << std::endl)

	if(this->provider->count() != this->numTailItems){
		real intFactor = real(this->posIndex) / real(this->provider->count() - this->numTailItems);

		if(this->Children().size() != 0){
			real d;
			if(this->isVertical){
				d = this->Children().front()->Rect().d.y;
			}else{
				d = this->Children().front()->Rect().d.x;
			}

			this->posOffset = ting::math::Round(d * (factor - intFactor) * real(this->provider->count() - this->numTailItems) + factor * this->firstTailItemOffset);
		}else{
			this->posOffset = 0;
		}
	}else{
		ASSERT(this->posIndex == 0)
		this->posOffset = ting::math::Round(factor * this->firstTailItemOffset);
	}

	this->updateChildrenList();
}

bool List::arrangeWidget(std::shared_ptr<Widget>& w, real& pos, bool added, size_t index, T_ChildrenList::const_iterator insertBefore){
	auto& lp = this->GetLayoutParamsAs<LayoutParams>(*w);

	Vec2r dim = this->dimForWidget(*w, lp);

	w->Resize(dim);

	if(this->isVertical){
		pos -= w->Rect().d.y;
		w->MoveTo(Vec2r(0, pos));

		if(pos < this->Rect().d.y){
			if(!added){
				this->Add(w, insertBefore);
			}
			if(this->addedIndex > index){
				this->addedIndex = index;
			}
		}else{
			++this->posIndex;
			this->posOffset -= w->Rect().d.y;
			if(added){
				auto widget = this->Remove(*w);
				if(this->provider){
					this->provider->recycle(index, widget);
				}
				++this->addedIndex;
			}else{
				if(this->provider){
					this->provider->recycle(index, w);
				}
			}
		}

		if(w->Rect().p.y <= 0){
			return true;
		}
	}else{
		w->MoveTo(Vec2r(pos, 0));
		pos += w->Rect().d.x;

		if(pos > 0){
			if(!added){
				this->Add(w, insertBefore);
			}
			if(this->addedIndex > index){
				this->addedIndex = index;
			}
		}else{
			++this->posIndex;
			this->posOffset -= w->Rect().d.x;
			if(added){
				auto widget = this->Remove(*w);
				if(this->provider){
					this->provider->recycle(index, widget);
				}
				++this->addedIndex;
			}else{
				if(this->provider){
					this->provider->recycle(index, w);
				}
			}
		}

		if(w->Rect().Right() >= this->Rect().d.x){
			return true;
		}
	}
	return false;
}

void List::updateChildrenList(){
	if(!this->provider){
		this->posIndex = 0;
		this->posOffset = 0;

		this->removeAll();
		this->addedIndex = size_t(-1);
		return;
	}

	if(this->numTailItems == 0){
		this->updateTailItemsInfo();
	}

	real pos;

	if(this->isVertical){
		pos = this->Rect().d.y + this->posOffset;
	}else{
		pos = -this->posOffset;
	}

	TRACE(<< "List::updateChildrenList(): this->addedIndex = " << this->addedIndex << " this->posIndex = " << this->posIndex << std::endl)

	//remove widgets from top
	for(; this->Children().size() != 0 && this->addedIndex < this->posIndex; ++this->addedIndex){
		auto w = (*this->Children().begin())->RemoveFromParent();
		if(this->provider){
			this->provider->recycle(this->addedIndex, w);
		}
	}

	auto iter = this->Children().begin();
	size_t iterIndex = this->addedIndex;
	size_t iterEndIndex = iterIndex + this->Children().size();
	size_t index = this->posIndex;
	for(; index < this->provider->count();){
		std::shared_ptr<Widget> w;
		bool isAdded;
		if(iterIndex <= index && index < iterEndIndex && iter != this->Children().end()){
			w = *iter;
			++iter;
			++iterIndex;
			isAdded = true;
		}else{
			w = this->provider->getWidget(index);
			isAdded = false;
		}

		if(this->arrangeWidget(w, pos, isAdded, index, iter)){
			++index;
			break;
		}
		++index;
	}

	//remove rest
	if(iterIndex < iterEndIndex){
		size_t oldIterIndex = iterIndex;
		for(;;){
			auto i = iter;
			++i;
			++iterIndex;
			if(i == this->Children().end()){
				break;
			}
			auto w = this->Remove(i);
			if(this->provider){
				this->provider->recycle(iterIndex, w);
			}
		}
		auto w = this->Remove(iter);
		if(this->provider){
			this->provider->recycle(oldIterIndex, w);
		}
	}

}

void List::updateTailItemsInfo(){
	this->numTailItems = 0;

	if(!this->provider || this->provider->count() == 0){
		return;
	}

	real dim;

	if(this->isVertical){
		dim = this->Rect().d.y;
	}else{
		dim = this->Rect().d.x;
	}

	ASSERT(this->provider)
	ASSERT(this->provider->count() > 0)

	for(size_t i = this->provider->count(); i != 0 && dim > 0; --i){
		++this->numTailItems;

		auto w = this->provider->getWidget(i - 1);

		auto& lp = this->GetLayoutParamsAs<LayoutParams>(*w);

		Vec2r d = this->dimForWidget(*w, lp);

		if(this->isVertical){
			dim -= d.y;
		}else{
			dim -= d.x;
		}
	}

	if(dim > 0){
		this->firstTailItemOffset = -1;
	}else{
		this->firstTailItemOffset = -dim;
	}
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//mitk includes
#include "mitkTestingMacros.h"
#include "mitkUnstructuredGrid.h"

//vtk includes
#include "vtkUnstructuredGrid.h"

/**
 *Unit test for the UnstructuredGrd class
 */

int mitkUnstructuredGridTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("UnstructuredGrid")

  // let's create an object of our class
  mitk::UnstructuredGrid::Pointer testObject = mitk::UnstructuredGrid::New();
  MITK_TEST_CONDITION_REQUIRED(testObject.IsNotNull(),"Testing instantiation")
  MITK_TEST_CONDITION_REQUIRED( testObject->VerifyRequestedRegion(), "Requested region verification after initialization!");

  //create a clone object
  mitk::UnstructuredGrid::Pointer cloneObject = testObject->Clone();
  MITK_TEST_CONDITION_REQUIRED(cloneObject.IsNotNull(),"Testing instantiation of clone")
  MITK_TEST_CONDITION_REQUIRED( cloneObject->VerifyRequestedRegion(), "Requested region verification after initialization of clone!");

    // set some grid data to the class
  vtkUnstructuredGrid* grid = vtkUnstructuredGrid::New();
  testObject->SetVtkUnstructuredGrid(grid);
  MITK_TEST_CONDITION_REQUIRED(testObject->GetVtkUnstructuredGrid()== grid, "Testing Set/Get vtkUnstructuredGrid");

  // specify a region and set it to the test object
  mitk::UnstructuredGrid::RegionType* ugRegion = new mitk::UnstructuredGrid::RegionType;
  mitk::UnstructuredGrid::RegionType::SizeType size;
  size[0] = 100;
  size[1] = 100;
  size[2] = 100;
  size[3] = 100;
  size[4] = 100;

  mitk::UnstructuredGrid::RegionType::IndexType index;
  index[0] = 0;
  index[1] = 0;
  index[2] = 0;

  ugRegion->SetSize(size);
  ugRegion->SetIndex(index);
  testObject->SetRequestedRegion(ugRegion);
  testObject->UpdateOutputInformation();
  MITK_TEST_CONDITION_REQUIRED(testObject->GetRequestedRegion().GetSize() == ugRegion->GetSize(), "Testing Set/Get of Requested Region by RegionType1!");
  MITK_TEST_CONDITION_REQUIRED(testObject->GetRequestedRegion().GetIndex() == ugRegion->GetIndex(), "Testing Set/Get of Requested Region by RegionType2!");
  // VerifyRequested Region should be false due to the chosen size parameter!
  MITK_TEST_CONDITION_REQUIRED(!testObject->VerifyRequestedRegion(), "Requested Region verification!");

  mitk::UnstructuredGrid::Pointer copyObject = mitk::UnstructuredGrid::New();
  copyObject->CopyInformation(testObject);
  copyObject->SetRequestedRegion(testObject);
  MITK_TEST_CONDITION_REQUIRED(copyObject->GetLargestPossibleRegion() == testObject->GetLargestPossibleRegion(), "Testing generation of copy object");
  MITK_TEST_CONDITION_REQUIRED(copyObject->GetRequestedRegion().GetSize() == ugRegion->GetSize(), "Testing SetRequestedRegion by DataObject1");
  MITK_TEST_CONDITION_REQUIRED(copyObject->GetRequestedRegion().GetIndex() == ugRegion->GetIndex(), "Testing SetRequestedRegion by DataObject2");

  cloneObject = testObject->Clone();
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetRequestedRegion() == testObject->GetRequestedRegion(), "Testing region cloning!");
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetVtkUnstructuredGrid()== grid, "Testing Get/Set-VtkUnstructuredGrid cloning");
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetRequestedRegion().GetSize() == ugRegion->GetSize(), "Testing Set/Get of Requested Region by RegionType1 in clone!");
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetRequestedRegion().GetIndex() == ugRegion->GetIndex(), "Testing Set/Get of Requested Region by RegionType2 in clone!");
  // VerifyRequested Region should be false due to the chosen size parameter!
  MITK_TEST_CONDITION_REQUIRED(!cloneObject->VerifyRequestedRegion(), "Requested Region verification!");

  // test this at the very end otherwise several other test cases need to be adapted!!
  testObject->SetRequestedRegionToLargestPossibleRegion();
  MITK_TEST_CONDITION_REQUIRED(testObject->GetRequestedRegion().GetSize() == testObject->GetLargestPossibleRegion().GetSize(), "Testing Set/Get LargestPossibleRegion!");

  // always end with this!
  MITK_TEST_END()
}

<commit_msg>COMP: Avoid uninitialized usage warnings.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//mitk includes
#include "mitkTestingMacros.h"
#include "mitkUnstructuredGrid.h"

//vtk includes
#include "vtkUnstructuredGrid.h"

/**
 *Unit test for the UnstructuredGrd class
 */

int mitkUnstructuredGridTest(int /* argc */, char* /*argv*/[])
{
  // always start with this!
  MITK_TEST_BEGIN("UnstructuredGrid")

  // let's create an object of our class
  mitk::UnstructuredGrid::Pointer testObject = mitk::UnstructuredGrid::New();
  MITK_TEST_CONDITION_REQUIRED(testObject.IsNotNull(),"Testing instantiation")
  MITK_TEST_CONDITION_REQUIRED( testObject->VerifyRequestedRegion(), "Requested region verification after initialization!");

  //create a clone object
  mitk::UnstructuredGrid::Pointer cloneObject = testObject->Clone();
  MITK_TEST_CONDITION_REQUIRED(cloneObject.IsNotNull(),"Testing instantiation of clone")
  MITK_TEST_CONDITION_REQUIRED( cloneObject->VerifyRequestedRegion(), "Requested region verification after initialization of clone!");

    // set some grid data to the class
  vtkUnstructuredGrid* grid = vtkUnstructuredGrid::New();
  testObject->SetVtkUnstructuredGrid(grid);
  MITK_TEST_CONDITION_REQUIRED(testObject->GetVtkUnstructuredGrid()== grid, "Testing Set/Get vtkUnstructuredGrid");

  // specify a region and set it to the test object
  mitk::UnstructuredGrid::RegionType* ugRegion = new mitk::UnstructuredGrid::RegionType;
  mitk::UnstructuredGrid::RegionType::SizeType size;
  size.Fill(100);

  mitk::UnstructuredGrid::RegionType::IndexType index;
  index.Fill(0);

  ugRegion->SetSize(size);
  ugRegion->SetIndex(index);
  testObject->SetRequestedRegion(ugRegion);
  testObject->UpdateOutputInformation();
  MITK_TEST_CONDITION_REQUIRED(testObject->GetRequestedRegion().GetSize() == ugRegion->GetSize(), "Testing Set/Get of Requested Region by RegionType1!");
  MITK_TEST_CONDITION_REQUIRED(testObject->GetRequestedRegion().GetIndex() == ugRegion->GetIndex(), "Testing Set/Get of Requested Region by RegionType2!");
  // VerifyRequested Region should be false due to the chosen size parameter!
  MITK_TEST_CONDITION_REQUIRED(!testObject->VerifyRequestedRegion(), "Requested Region verification!");

  mitk::UnstructuredGrid::Pointer copyObject = mitk::UnstructuredGrid::New();
  copyObject->CopyInformation(testObject);
  copyObject->SetRequestedRegion(testObject);
  MITK_TEST_CONDITION_REQUIRED(copyObject->GetLargestPossibleRegion() == testObject->GetLargestPossibleRegion(), "Testing generation of copy object");
  MITK_TEST_CONDITION_REQUIRED(copyObject->GetRequestedRegion().GetSize() == ugRegion->GetSize(), "Testing SetRequestedRegion by DataObject1");
  MITK_TEST_CONDITION_REQUIRED(copyObject->GetRequestedRegion().GetIndex() == ugRegion->GetIndex(), "Testing SetRequestedRegion by DataObject2");

  cloneObject = testObject->Clone();
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetRequestedRegion() == testObject->GetRequestedRegion(), "Testing region cloning!");
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetVtkUnstructuredGrid()== grid, "Testing Get/Set-VtkUnstructuredGrid cloning");
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetRequestedRegion().GetSize() == ugRegion->GetSize(), "Testing Set/Get of Requested Region by RegionType1 in clone!");
  MITK_TEST_CONDITION_REQUIRED(cloneObject->GetRequestedRegion().GetIndex() == ugRegion->GetIndex(), "Testing Set/Get of Requested Region by RegionType2 in clone!");
  // VerifyRequested Region should be false due to the chosen size parameter!
  MITK_TEST_CONDITION_REQUIRED(!cloneObject->VerifyRequestedRegion(), "Requested Region verification!");

  // test this at the very end otherwise several other test cases need to be adapted!!
  testObject->SetRequestedRegionToLargestPossibleRegion();
  MITK_TEST_CONDITION_REQUIRED(testObject->GetRequestedRegion().GetSize() == testObject->GetLargestPossibleRegion().GetSize(), "Testing Set/Get LargestPossibleRegion!");

  // always end with this!
  MITK_TEST_END()
}

<|endoftext|>


<commit_before>#include "session.h"

#include <iostream>
#include <fstream>
#include <tuple>

#include <cassert>

#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/Dynamic/Parser.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Lex/Lexer.h"

using namespace clang;
using namespace tooling;
using namespace ast_matchers;

using namespace CppQuery;

namespace {

class ResourceDirSetter : public ArgumentsAdjuster {
public:
  ResourceDirSetter(const std::string &s) : resourceDir(s) {}

  CommandLineArguments Adjust(const CommandLineArguments &args) {
    CommandLineArguments adjustedArgs(args);
    adjustedArgs.push_back("-resource-dir=" + resourceDir);
    return adjustedArgs;
  }

private:
  std::string resourceDir;
};

class ASTBuilderAction : public ToolAction {
public:
  ASTBuilderAction(std::vector<ASTUnit *> &ASTlist,
                   const std::function<bool(const std::string &)> &onTUbegin,
                   const std::function<bool(const std::string &)> &onTUend)
      : ASTlist(ASTlist), onTUbegin(onTUbegin), onTUend(onTUend) {
    errorNum = 0;
  }

  bool runInvocation(CompilerInvocation *invocation, FileManager *files,
                     DiagnosticConsumer *diagConsumer) {
    llvm::StringRef file = invocation->getFrontendOpts().Inputs[0].getFile();

    if (!onTUbegin(getAbsolutePath(file)))
      return true;

    TextDiagnosticBuffer diag;
    ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation(
        invocation, CompilerInstance::createDiagnostics(
                        &invocation->getDiagnosticOpts(), &diag, false));

    if (!AST)
      return false;

    if (onTUend(AST->getMainFileName().str())) {
      ASTlist.push_back(AST);
      SourceManager &srcMgr = AST->getSourceManager();
      for (TextDiagnosticBuffer::DiagList::const_iterator it = diag.err_begin();
           it != diag.err_end(); ++it) {
        errors.push_back(
            srcMgr.getFilename(it->first).str() + " line: " +
            std::to_string(srcMgr.getSpellingLineNumber(it->first)) + ": " +
            it->second + "\n");
      }
    } else {
      AST->setUnsafeToFree(false);
      delete AST;
    }

    return true;
  }

  std::vector<std::string>::const_iterator errBegin() { return errors.begin(); }
  std::vector<std::string>::const_iterator errEnd() { return errors.end(); }

private:
  unsigned errorNum;
  std::vector<std::string> errors;
  std::vector<ASTUnit *> &ASTlist;
  const std::function<bool(const std::string &)> &onTUbegin;
  const std::function<bool(const std::string &)> &onTUend;
};
}

bool CppQuery::operator<(const Match &lhs, const Match &rhs) {
  return std::tie(lhs.fileName, lhs.id, lhs.startLine, lhs.startCol,
                  lhs.endLine,
                  lhs.endCol) < std::tie(rhs.fileName, rhs.id, rhs.startLine,
                                         rhs.startCol, rhs.endLine, rhs.endCol);
}

std::ostream &CppQuery::operator<<(std::ostream &s, const Match &m) {
  s << m.fileName << "(" << m.id << "):" << m.startLine << "," << m.startCol
    << ":" << m.endLine << "," << m.endCol << std::endl;
  return s;
}

Session::Session(const std::string &databasePath,
                 const std::string &resourceDir) {
  std::string error;
  compilationDatabase = std::unique_ptr<JSONCompilationDatabase>(
      JSONCompilationDatabase::loadFromFile(databasePath, error));

  if (!error.empty())
    throw DatabaseError(error);

  files = compilationDatabase->getAllFiles();
  tool = std::unique_ptr<clang::tooling::ClangTool>(
      new ClangTool(*compilationDatabase, files));

  tool->appendArgumentsAdjuster(new ResourceDirSetter(resourceDir));
}

Session::~Session() {
  for (auto AST : ASTlist) {
    AST->setUnsafeToFree(false);
    delete AST;
  }
  tool->clearArgumentsAdjusters();
}

void
Session::parseFiles(const std::function<bool(const std::string &)> &onTUbegin,
                    const std::function<bool(const std::string &)> &onTUend) {
  ASTBuilderAction action(ASTlist, onTUbegin, onTUend);

  if (tool->run(&action) || action.errBegin() != action.errEnd()) {
    std::string errors;
    for (auto it = action.errBegin(); it != action.errEnd(); ++it) {
      errors += *it;
    }
    throw ParseError(errors);
  }
}

namespace {

struct CollectBoundNodes : MatchFinder::MatchCallback {
  std::vector<BoundNodes> &bindings;

  CollectBoundNodes(std::vector<BoundNodes> &bindings) : bindings(bindings) {}

  void run(const MatchFinder::MatchResult &result) {
    bindings.push_back(result.Nodes);
  }
};
}

void Session::runQuery(const std::string &query) {
  if (query.find(".bind") == std::string::npos)
    throw QueryError("There is no such node that was bound to an ID.");

  if (ASTlist.empty())
    throw QueryError("There is no file that was succesfully parsed.");

  dynamic::Diagnostics diag;
  llvm::Optional<dynamic::DynTypedMatcher> matcher =
      dynamic::Parser::parseMatcherExpression(query, &diag);

  if (!matcher)
    throw QueryError(diag.toString());

  foundMatches.clear();
  Match m;

  for (auto ast : ASTlist) {
    SourceManager &srcMgr = ast->getSourceManager();

    MatchFinder finder;
    std::vector<BoundNodes> boundNodes;
    CollectBoundNodes collector(boundNodes);

    if (!finder.addDynamicMatcher(*matcher, &collector))
      throw QueryError("Invalid top level matcher.");

    finder.matchAST(ast->getASTContext());

    for (auto nodes : boundNodes) {
      for (auto idToNode : nodes.getMap()) {
        SourceRange range = idToNode.second.getSourceRange();

        if (!range.isValid())
          continue;

        SourceLocation start = range.getBegin();

        if (srcMgr.isInSystemHeader(start) ||
            srcMgr.isInExternCSystemHeader(start))
          continue;

        // Get the last character of the last token
        SourceLocation end = Lexer::getLocForEndOfToken(range.getEnd(), 1,
                                                        srcMgr, LangOptions());

        llvm::StringRef fileName = srcMgr.getFilename(start);

        if (fileName.empty())
          continue;

        m.fileName = fileName.str();
        m.id = idToNode.first;
        m.startCol = srcMgr.getSpellingColumnNumber(start);
        m.startLine = srcMgr.getSpellingLineNumber(start);
        m.endCol = srcMgr.getSpellingColumnNumber(end);
        m.endLine = srcMgr.getSpellingLineNumber(end);

        foundMatches.insert(std::move(m));
      }
    }
  }
}

const std::set<Match> &Session::getMatches() const { return foundMatches; }

bool Session::exportMatches(const std::string &fileName) {
  std::ofstream output(fileName);

  if (!output)
    return false;

  for (const Match &m : foundMatches) {
    output << m;
  }

  return true;
}
<commit_msg>Do not store invalid source ranges.<commit_after>#include "session.h"

#include <iostream>
#include <fstream>
#include <tuple>

#include <cassert>

#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/Dynamic/Parser.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Lex/Lexer.h"

using namespace clang;
using namespace tooling;
using namespace ast_matchers;

using namespace CppQuery;

namespace {

class ResourceDirSetter : public ArgumentsAdjuster {
public:
  ResourceDirSetter(const std::string &s) : resourceDir(s) {}

  CommandLineArguments Adjust(const CommandLineArguments &args) {
    CommandLineArguments adjustedArgs(args);
    adjustedArgs.push_back("-resource-dir=" + resourceDir);
    return adjustedArgs;
  }

private:
  std::string resourceDir;
};

class ASTBuilderAction : public ToolAction {
public:
  ASTBuilderAction(std::vector<ASTUnit *> &ASTlist,
                   const std::function<bool(const std::string &)> &onTUbegin,
                   const std::function<bool(const std::string &)> &onTUend)
      : ASTlist(ASTlist), onTUbegin(onTUbegin), onTUend(onTUend) {
    errorNum = 0;
  }

  bool runInvocation(CompilerInvocation *invocation, FileManager *files,
                     DiagnosticConsumer *diagConsumer) {
    llvm::StringRef file = invocation->getFrontendOpts().Inputs[0].getFile();

    if (!onTUbegin(getAbsolutePath(file)))
      return true;

    TextDiagnosticBuffer diag;
    ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation(
        invocation, CompilerInstance::createDiagnostics(
                        &invocation->getDiagnosticOpts(), &diag, false));

    if (!AST)
      return false;

    if (onTUend(AST->getMainFileName().str())) {
      ASTlist.push_back(AST);
      SourceManager &srcMgr = AST->getSourceManager();
      for (TextDiagnosticBuffer::DiagList::const_iterator it = diag.err_begin();
           it != diag.err_end(); ++it) {
        errors.push_back(
            srcMgr.getFilename(it->first).str() + " line: " +
            std::to_string(srcMgr.getSpellingLineNumber(it->first)) + ": " +
            it->second + "\n");
      }
    } else {
      AST->setUnsafeToFree(false);
      delete AST;
    }

    return true;
  }

  std::vector<std::string>::const_iterator errBegin() { return errors.begin(); }
  std::vector<std::string>::const_iterator errEnd() { return errors.end(); }

private:
  unsigned errorNum;
  std::vector<std::string> errors;
  std::vector<ASTUnit *> &ASTlist;
  const std::function<bool(const std::string &)> &onTUbegin;
  const std::function<bool(const std::string &)> &onTUend;
};
}

bool CppQuery::operator<(const Match &lhs, const Match &rhs) {
  return std::tie(lhs.fileName, lhs.id, lhs.startLine, lhs.startCol,
                  lhs.endLine,
                  lhs.endCol) < std::tie(rhs.fileName, rhs.id, rhs.startLine,
                                         rhs.startCol, rhs.endLine, rhs.endCol);
}

std::ostream &CppQuery::operator<<(std::ostream &s, const Match &m) {
  s << m.fileName << "(" << m.id << "):" << m.startLine << "," << m.startCol
    << ":" << m.endLine << "," << m.endCol << std::endl;
  return s;
}

Session::Session(const std::string &databasePath,
                 const std::string &resourceDir) {
  std::string error;
  compilationDatabase = std::unique_ptr<JSONCompilationDatabase>(
      JSONCompilationDatabase::loadFromFile(databasePath, error));

  if (!error.empty())
    throw DatabaseError(error);

  files = compilationDatabase->getAllFiles();
  tool = std::unique_ptr<clang::tooling::ClangTool>(
      new ClangTool(*compilationDatabase, files));

  tool->appendArgumentsAdjuster(new ResourceDirSetter(resourceDir));
}

Session::~Session() {
  for (auto AST : ASTlist) {
    AST->setUnsafeToFree(false);
    delete AST;
  }
  tool->clearArgumentsAdjusters();
}

void
Session::parseFiles(const std::function<bool(const std::string &)> &onTUbegin,
                    const std::function<bool(const std::string &)> &onTUend) {
  ASTBuilderAction action(ASTlist, onTUbegin, onTUend);

  if (tool->run(&action) || action.errBegin() != action.errEnd()) {
    std::string errors;
    for (auto it = action.errBegin(); it != action.errEnd(); ++it) {
      errors += *it;
    }
    throw ParseError(errors);
  }
}

namespace {

struct CollectBoundNodes : MatchFinder::MatchCallback {
  std::vector<BoundNodes> &bindings;

  CollectBoundNodes(std::vector<BoundNodes> &bindings) : bindings(bindings) {}

  void run(const MatchFinder::MatchResult &result) {
    bindings.push_back(result.Nodes);
  }
};
}

void Session::runQuery(const std::string &query) {
  if (query.find(".bind") == std::string::npos)
    throw QueryError("There is no such node that was bound to an ID.");

  if (ASTlist.empty())
    throw QueryError("There is no file that was succesfully parsed.");

  dynamic::Diagnostics diag;
  llvm::Optional<dynamic::DynTypedMatcher> matcher =
      dynamic::Parser::parseMatcherExpression(query, &diag);

  if (!matcher)
    throw QueryError(diag.toString());

  foundMatches.clear();
  Match m;

  for (auto ast : ASTlist) {
    SourceManager &srcMgr = ast->getSourceManager();

    MatchFinder finder;
    std::vector<BoundNodes> boundNodes;
    CollectBoundNodes collector(boundNodes);

    if (!finder.addDynamicMatcher(*matcher, &collector))
      throw QueryError("Invalid top level matcher.");

    finder.matchAST(ast->getASTContext());

    for (auto nodes : boundNodes) {
      for (auto idToNode : nodes.getMap()) {
        SourceRange range = idToNode.second.getSourceRange();

        if (!range.isValid())
          continue;

        SourceLocation start = range.getBegin();

        if (srcMgr.isInSystemHeader(start) ||
            srcMgr.isInExternCSystemHeader(start))
          continue;

        // Get the last character of the last token
        SourceLocation end = Lexer::getLocForEndOfToken(range.getEnd(), 1,
                                                        srcMgr, LangOptions());

        llvm::StringRef fileName = srcMgr.getFilename(start);

        if (fileName.empty())
          continue;

        m.fileName = getAbsolutePath(fileName);
        m.id = idToNode.first;
        m.startCol = srcMgr.getSpellingColumnNumber(start);
        m.startLine = srcMgr.getSpellingLineNumber(start);
        m.endCol = srcMgr.getSpellingColumnNumber(end);
        m.endLine = srcMgr.getSpellingLineNumber(end);

        if (std::tie(m.startLine, m.startCol) > std::tie(m.endLine, m.endCol))
          continue;

        foundMatches.insert(std::move(m));
      }
    }
  }
}

const std::set<Match> &Session::getMatches() const { return foundMatches; }

bool Session::exportMatches(const std::string &fileName) {
  std::ofstream output(fileName);

  if (!output)
    return false;

  for (const Match &m : foundMatches) {
    output << m;
  }

  return true;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_eff_config.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_fbc_eff_config.H
/// @brief Set fabric system-wide effective config attributes (FAPI2)
///
/// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
/// *HWP Team: Nest
/// *HWP Level: 2
/// *HWP Consumed by: HB
///

#ifndef _P9_FBC_EFF_CONFIG_H_
#define _P9_FBC_EFF_CONFIG_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------

/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_fbc_eff_config_FP_t)();

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------

extern "C"
{

///
/// @brief Set fabric system-wide effective configuration attributes
///
/// @return fapi2:ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
    fapi2::ReturnCode p9_fbc_eff_config();

} // extern "C"

#endif // _P9_FBC_EFF_CONFIG_H_
<commit_msg>L3 update -- p9_fbc_eff_config<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_fbc_eff_config.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_fbc_eff_config.H
/// @brief Set fabric system-wide effective config attributes (FAPI2)
///
/// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
/// *HWP Team: Nest
/// *HWP Level: 3
/// *HWP Consumed by: HB
///

#ifndef _P9_FBC_EFF_CONFIG_H_
#define _P9_FBC_EFF_CONFIG_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------

/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_fbc_eff_config_FP_t)();

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------

extern "C"
{

///
/// @brief Set fabric system-wide effective configuration attributes
///
/// @return fapi2:ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
    fapi2::ReturnCode p9_fbc_eff_config();

} // extern "C"

#endif // _P9_FBC_EFF_CONFIG_H_
<|endoftext|>


<commit_before>/*
The MIT License(MIT)

Copyright (c) 2016-2018 Oleg Linkin <maledictusdemagog@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "utils.h"

#include <tuple>

#include <QList>
#include <QRegularExpression>
#include <QtDebug>

namespace Mnemosy
{
namespace Utils
{
void SetImagesWidth(QString& text, bool& hasArg)
{
    QRegularExpression imgRxp("\\",
            QRegularExpression::CaseInsensitiveOption);
    QList<QPair<QString, QString>> matched;
    QRegularExpressionMatchIterator matchIt = imgRxp.globalMatch(text);
    while (matchIt.hasNext())
    {
        QRegularExpressionMatch match = matchIt.next();
        const auto& imgTag = match.captured(0);
        if (!imgTag.contains("l-stat.livejournal.net"))
        {
            matched << QPair<QString, QString>(imgTag, match.captured(2));
        }
    }

    for (const auto& t : matched)
    {
        text.replace (t.first,
                ""));
        if (!hasArg)
        {
            hasArg = true;
        }
    }
}

void MoveFirstImageToTheTop(QString& text)
{
    QRegularExpression imgRxp("(\\)",
            QRegularExpression::CaseInsensitiveOption);
    QRegularExpressionMatch match = imgRxp.match(text);
    if (match.hasMatch())
    {
        QString matched = match.captured(0);
        text.remove(match.capturedStart(0), match.capturedLength(0));
        text.push_front(matched);
    }
}

void RemoveStyleTag(QString& text)
{
    QRegularExpression styleRxp ("style=\"(.+?)\"",
            QRegularExpression::CaseInsensitiveOption);
    text.remove(styleRxp);
}

void FixUntaggedUrls(QString& text)
{
    auto pattern = "(?<!='|\")((http:\\/\\/|ftp:\\/\\/|https:\\/\\/|www\.)([\\w\u0410-\u044f_-]+(?:(?:\\.[\\w\u0410-\u044f_-]+)+))([\\w\u0410-\u044f.,@?^=%&:\\/~+#-]*[\\w\u0410-\u044f@?^=%&\\/~+#-])?)";
    QRegularExpression untaggedUrlRxp(pattern, QRegularExpression::CaseInsensitiveOption);
    text.replace(untaggedUrlRxp, "\\1");
}

void TryToFillEventFields(LJEvent& event)
{
    if (!event.GetPosterID() && !event.GetPosterPicUrl().isEmpty())
    {
        QString url = event.GetPosterPicUrl().toString();
        event.SetPosterID(url.mid(url.lastIndexOf("/") + 1)
                .toLongLong());
    }

    if (event.GetPosterName().isEmpty())
    {
        QString url = event.GetUrl().toString();
        QString name = url.mid(7, url.indexOf(".") - 7);
        name.replace('-', "_");
        event.SetPosterName(name);
    }
}

QString AccessToString(Access acc)
{
    switch (acc)
    {
    case APrivate:
        return "private";
    case APublic:
        return "public";
    case ACustom:
    default:
        return "usemask";
    }
}

QString AdultContentToString(AdultContent ac)
{
    switch (ac)
    {
    case ACAdultsFrom14:
        return "concepts";
    case ACAdultsFrom18:
        return "explicit";
    case ACWithoutAdultContent:
    default:
        return "none";
    }
}

QString ScreeningToString(CommentsManagement cm)
{
    switch (cm)
    {
    case CMShowFriendsComments:
        return "F";
    case CMScreenComments:
        return "A";
    case CMScreenAnonymouseComments:
        return "R";
    case CMScreenNotFromFriendsWithLinks:
        return "L";
    case CMShowComments:
    default:
        return "N";
    }
}
}
} // namespace Mnemosy

<commit_msg>Fix url parser<commit_after>/*
The MIT License(MIT)

Copyright (c) 2016-2018 Oleg Linkin <maledictusdemagog@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "utils.h"

#include <tuple>

#include <QList>
#include <QRegularExpression>
#include <QtDebug>

namespace Mnemosy
{
namespace Utils
{
void SetImagesWidth(QString& text, bool& hasArg)
{
    QRegularExpression imgRxp("\\",
            QRegularExpression::CaseInsensitiveOption);
    QList<QPair<QString, QString>> matched;
    QRegularExpressionMatchIterator matchIt = imgRxp.globalMatch(text);
    while (matchIt.hasNext())
    {
        QRegularExpressionMatch match = matchIt.next();
        const auto& imgTag = match.captured(0);
        if (!imgTag.contains("l-stat.livejournal.net"))
        {
            matched << QPair<QString, QString>(imgTag, match.captured(2));
        }
    }

    for (const auto& t : matched)
    {
        text.replace (t.first,
                ""));
        if (!hasArg)
        {
            hasArg = true;
        }
    }
}

void MoveFirstImageToTheTop(QString& text)
{
    QRegularExpression imgRxp("(\\)",
            QRegularExpression::CaseInsensitiveOption);
    QRegularExpressionMatch match = imgRxp.match(text);
    if (match.hasMatch())
    {
        QString matched = match.captured(0);
        text.remove(match.capturedStart(0), match.capturedLength(0));
        text.push_front(matched);
    }
}

void RemoveStyleTag(QString& text)
{
    QRegularExpression styleRxp ("style=\"(.+?)\"",
            QRegularExpression::CaseInsensitiveOption);
    text.remove(styleRxp);
}

void FixUntaggedUrls(QString& text)
{
    auto pattern = "(?<!='|\")((http:\\/\\/|ftp:\\/\\/|https:\\/\\/|www\\.)([\\w\u0410-\u044f_-]+(?:(?:\\.[\\w\u0410-\u044f_-]+)+))([\\w\u0410-\u044f.,@?^=%&:\\/~+#-]*[\\w\u0410-\u044f@?^=%&\\/~+#-])?)";
    QRegularExpression untaggedUrlRxp(pattern, QRegularExpression::CaseInsensitiveOption);
    text.replace(untaggedUrlRxp, "\\1");
}

void TryToFillEventFields(LJEvent& event)
{
    if (!event.GetPosterID() && !event.GetPosterPicUrl().isEmpty())
    {
        QString url = event.GetPosterPicUrl().toString();
        event.SetPosterID(url.mid(url.lastIndexOf("/") + 1)
                .toLongLong());
    }

    if (event.GetPosterName().isEmpty())
    {
        QString url = event.GetUrl().toString();
        QString name = url.mid(7, url.indexOf(".") - 7);
        name.replace('-', "_");
        event.SetPosterName(name);
    }
}

QString AccessToString(Access acc)
{
    switch (acc)
    {
    case APrivate:
        return "private";
    case APublic:
        return "public";
    case ACustom:
    default:
        return "usemask";
    }
}

QString AdultContentToString(AdultContent ac)
{
    switch (ac)
    {
    case ACAdultsFrom14:
        return "concepts";
    case ACAdultsFrom18:
        return "explicit";
    case ACWithoutAdultContent:
    default:
        return "none";
    }
}

QString ScreeningToString(CommentsManagement cm)
{
    switch (cm)
    {
    case CMShowFriendsComments:
        return "F";
    case CMScreenComments:
        return "A";
    case CMScreenAnonymouseComments:
        return "R";
    case CMScreenNotFromFriendsWithLinks:
        return "L";
    case CMShowComments:
    default:
        return "N";
    }
}
}
} // namespace Mnemosy

<|endoftext|>


<commit_before>#include "ed.h"

utimer::timer_entry::timer_entry (const utime_t &time, u_long interval,
                                  lisp fn, int one_shot_p)
     : te_time (time + interval * utime_t (UNITS_PER_SEC / 1000)),
       te_interval (interval), te_fn (fn),
       te_flags (one_shot_p ? (TE_ONE_SHOT | TE_NEW) : TE_NEW)
{
}

utimer::utimer ()
     : t_hwnd (0), t_timer_on (0), t_in_timer (0)
{
}

utimer::~utimer ()
{
  while (!t_entries.empty_p ())
    delete t_entries.remove_head ();
  while (!t_defers.empty_p ())
    delete t_defers.remove_head ();
}

void
utimer::stop_timer ()
{
  if (t_timer_on)
    {
      KillTimer (t_hwnd, TID_USER);
      t_timer_on = 0;
    }
}

void
utimer::start_timer (const utime_t &t)
{
  stop_timer ();

  timer_entry *entry = t_entries.head ();
  if (entry)
    {
      utime_t d = (entry->te_time - t) / (timer_entry::UNITS_PER_SEC / 1000);
      if (d < 0)
        d = 0;
      else if (d >= LONG_MAX)
        d = LONG_MAX;
      SetTimer (t_hwnd, TID_USER, UINT (d), 0);
      t_timer_on = 1;
    }
}

void
utimer::insert (timer_entry *entry)
{
  for (timer_entry *p = t_entries.head (); p; p = p->next ())
    if (entry->te_time < p->te_time)
      {
        t_entries.insert_before (entry, p);
        return;
      }
  t_entries.add_tail (entry);
}

void
utimer::timer ()
{
  stop_timer ();

  if (t_in_timer)
    return;
  t_in_timer = 1;

  utime_t t;
  current_time (t);
  while (1)
    {
      timer_entry *entry = t_entries.head ();
      if (!entry)
        break;
      if (entry->te_time > t)
        break;

      lisp fn = entry->te_fn;

      t_entries.remove (entry);
      if (entry->te_flags & timer_entry::TE_ONE_SHOT)
        delete entry;
      else
        t_defers.add_tail (entry);

      try {Ffuncall (fn, Qnil);} catch (nonlocal_jump &) {}
    }

  t_in_timer = 0;

  current_time (t);
  while (!t_defers.empty_p ())
    {
      timer_entry *entry = t_defers.remove_head ();
      if (entry->te_flags & timer_entry::TE_NEW)
        entry->te_flags &= ~timer_entry::TE_NEW;
      else
        entry->te_time = t + (entry->te_interval
                              * utime_t (timer_entry::UNITS_PER_SEC / 1000));
      insert (entry);
    }

  start_timer (t);
}

void
utimer::add (u_long interval, lisp fn, int one_shot_p)
{
  utime_t t;
  current_time (t);
  timer_entry *entry = new timer_entry (t, interval, fn, one_shot_p);
  if (t_in_timer)
    t_defers.add_tail (entry);
  else
    {
      insert (entry);
      start_timer (t);
    }
}

int
utimer::remove (xlist <timer_entry> &list, lisp fn)
{
  for (timer_entry *p = list.head (); p; p = p->next ())
    if (p->te_fn == fn)
      {
        delete list.remove (p);
        return 1;
      }
  return 0;
}

int
utimer::remove (lisp fn)
{
  if (!remove (t_entries, fn) && !remove (t_defers, fn))
    return 0;
  if (!t_in_timer)
    {
      utime_t t;
      current_time (t);
      start_timer (t);
    }
  return 1;
}

void
utimer::gc_mark (void (*f)(lisp))
{
  for (timer_entry *p = t_entries.head (); p; p = p->next ())
    (*f)(p->te_fn);
  for (p = t_defers.head (); p; p = p->next ())
    (*f)(p->te_fn);
}

lisp
Fstart_timer (lisp linterval, lisp lfn, lisp lone_shot_p)
{
  double interval (coerce_to_double_float (linterval) * 1000);
  if (interval < 0 || interval > LONG_MAX)
    FErange_error (linterval);
  app.user_timer.add (u_long (interval), lfn, lone_shot_p && lone_shot_p != Qnil);
  return Qt;
}

lisp
Fstop_timer (lisp fn)
{
  return boole (app.user_timer.remove (fn));
}
<commit_msg>xyzzy.src : fix start-timer.<commit_after>#include "ed.h"

utimer::timer_entry::timer_entry (const utime_t &time, u_long interval,
                                  lisp fn, int one_shot_p)
     : te_time (time + interval * utime_t (UNITS_PER_SEC / 1000)),
       te_interval (interval), te_fn (fn),
       te_flags (one_shot_p ? (TE_ONE_SHOT | TE_NEW) : TE_NEW)
{
}

utimer::utimer ()
     : t_hwnd (0), t_timer_on (0), t_in_timer (0)
{
}

utimer::~utimer ()
{
  while (!t_entries.empty_p ())
    delete t_entries.remove_head ();
  while (!t_defers.empty_p ())
    delete t_defers.remove_head ();
}

void
utimer::stop_timer ()
{
  if (t_timer_on)
    {
      KillTimer (t_hwnd, TID_USER);
      t_timer_on = 0;
    }
}

void
utimer::start_timer (const utime_t &t)
{
  stop_timer ();

  timer_entry *entry = t_entries.head ();
  if (entry)
    {
      utime_t d = (entry->te_time - t) / (timer_entry::UNITS_PER_SEC / 1000);
      if (d < 0)
        d = 0;
      else if (d >= LONG_MAX)
        d = LONG_MAX;
      SetTimer (t_hwnd, TID_USER, UINT (d), 0);
      t_timer_on = 1;
    }
}

void
utimer::insert (timer_entry *entry)
{
  for (timer_entry *p = t_entries.head (); p; p = p->next ())
    if (entry->te_time < p->te_time)
      {
        t_entries.insert_before (entry, p);
        return;
      }
  t_entries.add_tail (entry);
}

void
utimer::timer ()
{
  stop_timer ();

  if (t_in_timer)
    return;
  t_in_timer = 1;

  utime_t t;
  current_time (t);
  while (1)
    {
      timer_entry *entry = t_entries.head ();
      if (!entry)
        break;
      if (entry->te_time > t)
        break;

      lisp fn = entry->te_fn;

      t_entries.remove (entry);
      if (entry->te_flags & timer_entry::TE_ONE_SHOT)
        delete entry;
      else
        t_defers.add_tail (entry);

      try {Ffuncall (fn, Qnil);} catch (nonlocal_jump &) {}
    }

  t_in_timer = 0;

  current_time (t);
  while (!t_defers.empty_p ())
    {
      timer_entry *entry = t_defers.remove_head ();
      if (entry->te_flags & timer_entry::TE_NEW)
        entry->te_flags &= ~timer_entry::TE_NEW;
      entry->te_time = t + (entry->te_interval
                            * utime_t (timer_entry::UNITS_PER_SEC / 1000));
      insert (entry);
    }

  start_timer (t);
}

void
utimer::add (u_long interval, lisp fn, int one_shot_p)
{
  utime_t t;
  current_time (t);
  timer_entry *entry = new timer_entry (t, interval, fn, one_shot_p);
  if (t_in_timer)
    t_defers.add_tail (entry);
  else
    {
      insert (entry);
      start_timer (t);
    }
}

int
utimer::remove (xlist <timer_entry> &list, lisp fn)
{
  for (timer_entry *p = list.head (); p; p = p->next ())
    if (p->te_fn == fn)
      {
        delete list.remove (p);
        return 1;
      }
  return 0;
}

int
utimer::remove (lisp fn)
{
  if (!remove (t_entries, fn) && !remove (t_defers, fn))
    return 0;
  if (!t_in_timer)
    {
      utime_t t;
      current_time (t);
      start_timer (t);
    }
  return 1;
}

void
utimer::gc_mark (void (*f)(lisp))
{
  for (timer_entry *p = t_entries.head (); p; p = p->next ())
    (*f)(p->te_fn);
  for (p = t_defers.head (); p; p = p->next ())
    (*f)(p->te_fn);
}

lisp
Fstart_timer (lisp linterval, lisp lfn, lisp lone_shot_p)
{
  double interval (coerce_to_double_float (linterval) * 1000);
  if (interval < 0 || interval > LONG_MAX)
    FErange_error (linterval);
  app.user_timer.add (u_long (interval), lfn, lone_shot_p && lone_shot_p != Qnil);
  return Qt;
}

lisp
Fstop_timer (lisp fn)
{
  return boole (app.user_timer.remove (fn));
}
<|endoftext|>


<commit_before>// This file is part of xsonrpc, an XML/JSON RPC library.
// Copyright (C) 2015 Erik Johansson <erik@ejohansson.se
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
// for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

#include "util.h"
#include "fault.h"
#include "value.h"

#include <ctime>
#include <ostream>
#include <string>
#include <tinyxml2.h>
#include <typeinfo>

namespace {

const char VALUE_TAG[] = "value";

const char ARRAY_TAG[] = "array";
const char BASE_64_TAG[] = "base64";
const char BOOLEAN_TAG[] = "boolean";
const char DATE_TIME_TAG[] = "dateTime.iso8601";
const char DOUBLE_TAG[] = "double";
const char INTEGER_INT_TAG[] = "int";
const char INTEGER_32_TAG[] = "i4";
const char INTEGER_64_TAG[] = "i8";
const char NIL_TAG[] = "nil";
const char STRING_TAG[] = "string";
const char STRUCT_TAG[] = "struct";

const char DATA_TAG[] = "data";
const char MEMBER_TAG[] = "member";
const char NAME_TAG[] = "name";

const char DATE_TIME_FORMAT[] = "%Y%m%dT%T";

std::string FormatIso8601DateTime(const tm& dt)
{
  char str[128];
  return std::string(str, strftime(str, sizeof(str), DATE_TIME_FORMAT, &dt));
}

} // namespace

namespace xsonrpc {

Value::Value(const tinyxml2::XMLElement* element)
{
  if (!element || !util::IsTag(*element, VALUE_TAG)) {
    throw InvalidXmlRpcFault("missing value element");
  }

  auto value = element->FirstChildElement();
  if (!value) {
    throw InvalidXmlRpcFault("empty value element");
  }

  if (util::IsTag(*value, ARRAY_TAG)) {
    auto data = value->FirstChildElement(DATA_TAG);
    if (!data) {
      throw InvalidXmlRpcFault("missing data element in array");
    }
    myType = Type::ARRAY;
    Array array;
    for (auto element = data->FirstChildElement();
         element; element = element->NextSiblingElement()) {
      array.emplace_back(element);
    }
    as.myArray = new Array(std::move(array));
  }
  else if (util::IsTag(*value, BASE_64_TAG)) {
    myType = Type::BINARY;
    auto text = value->GetText();
    if (!text) {
      throw InvalidXmlRpcFault("value is not base64");
    }
    auto binary = util::Base64Decode(text, strlen(text));
    as.myBinary = new Binary(std::move(binary));
  }
  else if (util::IsTag(*value, BOOLEAN_TAG)) {
    myType = Type::BOOLEAN;
    if (value->QueryBoolText(&as.myBoolean) != tinyxml2::XML_SUCCESS) {
      throw InvalidXmlRpcFault("value is not a boolean");
    }
  }
  else if (util::IsTag(*value, DATE_TIME_TAG)) {
    myType = Type::DATE_TIME;
    if (!value->GetText()) {
      throw InvalidXmlRpcFault("value is not a date/time");
    }
    DateTime dateTime;
    memset(&dateTime, 0, sizeof(dateTime));
    auto* res = strptime(value->GetText(), DATE_TIME_FORMAT, &dateTime);
    if (!res || *res != '\0') {
      throw InvalidXmlRpcFault("value is not a valid date/time");
    }
    dateTime.tm_isdst = -1;
    as.myDateTime = new DateTime(dateTime);
  }
  else if (util::IsTag(*value, DOUBLE_TAG)) {
    myType = Type::DOUBLE;
    if (value->QueryDoubleText(&as.myDouble) != tinyxml2::XML_SUCCESS) {
      throw InvalidXmlRpcFault("value is not a double");
    }
  }
  else if (util::IsTag(*value, INTEGER_32_TAG)
           || util::IsTag(*value, INTEGER_INT_TAG)) {
    myType = Type::INTEGER_32;
    if (value->QueryIntText(&as.myInteger32) != tinyxml2::XML_SUCCESS) {
      throw InvalidXmlRpcFault("value is not a 32-bit integer");
    }
  }
  else if (util::IsTag(*value, INTEGER_64_TAG)) {
    if (!value->GetText()) {
      throw InvalidXmlRpcFault("value is not a 64-bit integer");
    }
    myType = Type::INTEGER_64;
    as.myInteger64 = std::stoll(value->GetText());
  }
  else if (util::IsTag(*value, NIL_TAG)) {
    myType = Type::NIL;
  }
  else if (util::IsTag(*value, STRING_TAG)) {
    myType = Type::STRING;
    as.myString = new String(value->GetText() ? value->GetText() : "");
  }
  else if (util::IsTag(*value, STRUCT_TAG)) {
    myType = Type::STRUCT;

    Struct data;
    for (auto member = value->FirstChildElement(MEMBER_TAG);
         member; member = member->NextSiblingElement(MEMBER_TAG)) {
      auto name = member->FirstChildElement(NAME_TAG);
      if (!name || util::HasEmptyText(*name)) {
        throw InvalidXmlRpcFault("missing name element in struct");
      }
      data.emplace(name->GetText(),
                   Value(member->LastChildElement(VALUE_TAG)));
    }
    as.myStruct = new Struct(std::move(data));
  }
  else {
    throw InvalidXmlRpcFault("invalid type");
  }
}

Value::Value(Array value)
  : myType(Type::ARRAY)
{
  as.myArray = new Array(std::move(value));
}

Value::Value(Binary value)
  : myType(Type::BINARY)
{
  as.myBinary = new Binary(std::move(value));
}

Value::Value(const DateTime& value)
  : myType(Type::DATE_TIME)
{
  as.myDateTime = new DateTime(value);
  as.myDateTime->tm_isdst = -1;
}

Value::Value(String value)
  : myType(Type::STRING)
{
  as.myString = new String(std::move(value));
}

Value::Value(Struct value)
  : myType(Type::STRUCT)
{
  as.myStruct = new Struct(std::move(value));
}

Value::~Value()
{
  Reset();
}

Value::Value(const Value& other)
  : myType(other.myType),
    as(other.as)
{
  switch (myType) {
    case Type::BOOLEAN:
    case Type::DOUBLE:
    case Type::INTEGER_32:
    case Type::INTEGER_64:
    case Type::NIL:
      break;

    case Type::ARRAY:
      as.myArray = new Array(other.AsArray());
      break;
    case Type::BINARY:
      as.myBinary = new Binary(other.AsBinary());
      break;
    case Type::DATE_TIME:
      as.myDateTime = new DateTime(other.AsDateTime());
      break;
    case Type::STRING:
      as.myString = new String(other.AsString());
      break;
    case Type::STRUCT:
      as.myStruct = new Struct(other.AsStruct());
      break;
  }
}

Value::Value(Value&& other) noexcept
  : myType(other.myType),
    as(other.as)
{
  other.myType = Type::NIL;
}

Value& Value::operator=(Value&& other) noexcept
{
  if (this != &other) {
    Reset();

    myType = other.myType;
    as = other.as;

    other.myType = Type::NIL;
  }
  return *this;
}

const Value::Array& Value::AsArray() const
{
  if (IsArray()) {
    return *as.myArray;
  }
  throw InvalidParametersFault();
}

const Value::Binary& Value::AsBinary() const
{
  if (IsBinary()) {
    return *as.myBinary;
  }
  throw InvalidParametersFault();
}

const bool& Value::AsBoolean() const
{
  if (IsBoolean()) {
    return as.myBoolean;
  }
  throw InvalidParametersFault();
}

const Value::DateTime& Value::AsDateTime() const
{
  if (IsDateTime()) {
    return *as.myDateTime;
  }
  throw InvalidParametersFault();
}

const double& Value::AsDouble() const
{
  if (IsDouble()) {
    return as.myDouble;
  }
  throw InvalidParametersFault();
}

const int32_t& Value::AsInteger32() const
{
  if (IsInteger32()) {
    return as.myInteger32;
  }
  throw InvalidParametersFault();
}

const int64_t& Value::AsInteger64() const
{
  if (IsInteger64()) {
    return as.myInteger64;
  }
  throw InvalidParametersFault();
}

const Value::String& Value::AsString() const
{
  if (IsString()) {
    return *as.myString;
  }
  throw InvalidParametersFault();
}

const Value::Struct& Value::AsStruct() const
{
  if (IsStruct()) {
    return *as.myStruct;
  }
  throw InvalidParametersFault();
}

std::string Value::GetTypeName(Type type)
{
  switch (type) {
    case Type::ARRAY:
      return ARRAY_TAG;
    case Type::BINARY:
      return BASE_64_TAG;
    case Type::BOOLEAN:
      return BOOLEAN_TAG;
    case Type::DATE_TIME:
      return DATE_TIME_TAG;
    case Type::DOUBLE:
      return DOUBLE_TAG;
    case Type::INTEGER_32:
      return INTEGER_32_TAG;
    case Type::INTEGER_64:
      return INTEGER_64_TAG;
    case Type::NIL:
      return NIL_TAG;
    case Type::STRING:
      return STRING_TAG;
    case Type::STRUCT:
      return STRUCT_TAG;
  }
  return {};
}

void Value::Print(tinyxml2::XMLPrinter& printer) const
{
  printer.OpenElement(VALUE_TAG);

  bool compact = false;
  switch (myType) {
    case Type::ARRAY: {
      printer.OpenElement(ARRAY_TAG);
      printer.OpenElement(DATA_TAG);
      for (const auto& element : *as.myArray) {
        element.Print(printer);
      }
      printer.CloseElement();
      printer.CloseElement();
      break;
    }
    case Type::BINARY:
      printer.OpenElement(BASE_64_TAG);
      printer.PushText(util::Base64Encode(*as.myBinary).c_str());
      printer.CloseElement();
      break;
    case Type::BOOLEAN:
      compact = true;
      printer.OpenElement(BOOLEAN_TAG, compact);
      printer.PushText(as.myBoolean);
      printer.CloseElement(compact);
      break;
    case Type::DATE_TIME:
      compact = true;
      printer.OpenElement(DATE_TIME_TAG, compact);
      printer.PushText(FormatIso8601DateTime(*as.myDateTime).c_str());
      printer.CloseElement(compact);
      break;
    case Type::DOUBLE:
      compact = true;
      printer.OpenElement(DOUBLE_TAG, compact);
      printer.PushText(as.myDouble);
      printer.CloseElement(compact);
      break;
    case Type::INTEGER_32:
      compact = true;
      printer.OpenElement(INTEGER_32_TAG, compact);
      printer.PushText(as.myInteger32);
      printer.CloseElement(compact);
      break;
    case Type::INTEGER_64:
      compact = true;
      printer.OpenElement(INTEGER_64_TAG, compact);
      printer.PushText(std::to_string(as.myInteger64).c_str());
      printer.CloseElement(compact);
      break;
    case Type::NIL:
      compact = true;
      printer.OpenElement(NIL_TAG, compact);
      printer.CloseElement(compact);
      break;
    case Type::STRING:
      compact = true;
      printer.OpenElement(STRING_TAG, compact);
      printer.PushText(as.myString->c_str());
      printer.CloseElement(compact);
      break;
    case Type::STRUCT: {
      printer.OpenElement(STRUCT_TAG);
      for (const auto& element : *as.myStruct) {
        printer.OpenElement(MEMBER_TAG);

        printer.OpenElement(NAME_TAG);
        printer.PushText(element.first.c_str());
        printer.CloseElement(true);

        element.second.Print(printer);
        printer.CloseElement();
      }
      printer.CloseElement();
      break;
    }
  }

  printer.CloseElement(compact);
}

void Value::Reset()
{
  switch (myType) {
    case Type::ARRAY:
      delete as.myArray;
      break;
    case Type::BINARY:
      delete as.myBinary;
      break;
    case Type::DATE_TIME:
      delete as.myDateTime;
      break;
    case Type::STRING:
      delete as.myString;
      break;
    case Type::STRUCT:
      delete as.myStruct;
      break;

    case Type::BOOLEAN:
    case Type::DOUBLE:
    case Type::INTEGER_32:
    case Type::INTEGER_64:
    case Type::NIL:
      break;
  }

  myType = Type::NIL;
}

std::ostream& operator<<(std::ostream& os, const Value& value)
{
  switch (value.GetType()) {
    case Value::Type::ARRAY: {
      os << '[';
      auto& a = value.AsArray();
      for (auto it = a.begin(); it != a.end(); ++it) {
        if (it != a.begin()) {
          os << ", ";
        }
        os << *it;
      }
      os << ']';
      break;
    }
    case Value::Type::BINARY:
      os << util::Base64Encode(value.AsBinary());
      break;
    case Value::Type::BOOLEAN:
      os << value.AsBoolean();
      break;
    case Value::Type::DATE_TIME:
      os << FormatIso8601DateTime(value.AsDateTime());
      break;
    case Value::Type::DOUBLE:
      os << value.AsDouble();
      break;
    case Value::Type::INTEGER_32:
      os << value.AsInteger32();
      break;
    case Value::Type::INTEGER_64:
      os << value.AsInteger64();
      break;
    case Value::Type::NIL:
      os << "<nil>";
      break;
    case Value::Type::STRING:
      os << '"' << value.AsString() << '"';
      break;
    case Value::Type::STRUCT: {
      os << '{';
      auto& s = value.AsStruct();
      for (auto it = s.begin(); it != s.end(); ++it) {
        if (it != s.begin()) {
          os << ", ";
        }
        os << '"' << it->first << "\": " << it->second;
      }
      os << '}';
      break;
    }
  }
  return os;
}

} // namespace xsonrpc
<commit_msg>value: print struct without " around names<commit_after>// This file is part of xsonrpc, an XML/JSON RPC library.
// Copyright (C) 2015 Erik Johansson <erik@ejohansson.se
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 2.1 of the License, or (at your
// option) any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
// for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

#include "util.h"
#include "fault.h"
#include "value.h"

#include <ctime>
#include <ostream>
#include <string>
#include <tinyxml2.h>
#include <typeinfo>

namespace {

const char VALUE_TAG[] = "value";

const char ARRAY_TAG[] = "array";
const char BASE_64_TAG[] = "base64";
const char BOOLEAN_TAG[] = "boolean";
const char DATE_TIME_TAG[] = "dateTime.iso8601";
const char DOUBLE_TAG[] = "double";
const char INTEGER_INT_TAG[] = "int";
const char INTEGER_32_TAG[] = "i4";
const char INTEGER_64_TAG[] = "i8";
const char NIL_TAG[] = "nil";
const char STRING_TAG[] = "string";
const char STRUCT_TAG[] = "struct";

const char DATA_TAG[] = "data";
const char MEMBER_TAG[] = "member";
const char NAME_TAG[] = "name";

const char DATE_TIME_FORMAT[] = "%Y%m%dT%T";

std::string FormatIso8601DateTime(const tm& dt)
{
  char str[128];
  return std::string(str, strftime(str, sizeof(str), DATE_TIME_FORMAT, &dt));
}

} // namespace

namespace xsonrpc {

Value::Value(const tinyxml2::XMLElement* element)
{
  if (!element || !util::IsTag(*element, VALUE_TAG)) {
    throw InvalidXmlRpcFault("missing value element");
  }

  auto value = element->FirstChildElement();
  if (!value) {
    throw InvalidXmlRpcFault("empty value element");
  }

  if (util::IsTag(*value, ARRAY_TAG)) {
    auto data = value->FirstChildElement(DATA_TAG);
    if (!data) {
      throw InvalidXmlRpcFault("missing data element in array");
    }
    myType = Type::ARRAY;
    Array array;
    for (auto element = data->FirstChildElement();
         element; element = element->NextSiblingElement()) {
      array.emplace_back(element);
    }
    as.myArray = new Array(std::move(array));
  }
  else if (util::IsTag(*value, BASE_64_TAG)) {
    myType = Type::BINARY;
    auto text = value->GetText();
    if (!text) {
      throw InvalidXmlRpcFault("value is not base64");
    }
    auto binary = util::Base64Decode(text, strlen(text));
    as.myBinary = new Binary(std::move(binary));
  }
  else if (util::IsTag(*value, BOOLEAN_TAG)) {
    myType = Type::BOOLEAN;
    if (value->QueryBoolText(&as.myBoolean) != tinyxml2::XML_SUCCESS) {
      throw InvalidXmlRpcFault("value is not a boolean");
    }
  }
  else if (util::IsTag(*value, DATE_TIME_TAG)) {
    myType = Type::DATE_TIME;
    if (!value->GetText()) {
      throw InvalidXmlRpcFault("value is not a date/time");
    }
    DateTime dateTime;
    memset(&dateTime, 0, sizeof(dateTime));
    auto* res = strptime(value->GetText(), DATE_TIME_FORMAT, &dateTime);
    if (!res || *res != '\0') {
      throw InvalidXmlRpcFault("value is not a valid date/time");
    }
    dateTime.tm_isdst = -1;
    as.myDateTime = new DateTime(dateTime);
  }
  else if (util::IsTag(*value, DOUBLE_TAG)) {
    myType = Type::DOUBLE;
    if (value->QueryDoubleText(&as.myDouble) != tinyxml2::XML_SUCCESS) {
      throw InvalidXmlRpcFault("value is not a double");
    }
  }
  else if (util::IsTag(*value, INTEGER_32_TAG)
           || util::IsTag(*value, INTEGER_INT_TAG)) {
    myType = Type::INTEGER_32;
    if (value->QueryIntText(&as.myInteger32) != tinyxml2::XML_SUCCESS) {
      throw InvalidXmlRpcFault("value is not a 32-bit integer");
    }
  }
  else if (util::IsTag(*value, INTEGER_64_TAG)) {
    if (!value->GetText()) {
      throw InvalidXmlRpcFault("value is not a 64-bit integer");
    }
    myType = Type::INTEGER_64;
    as.myInteger64 = std::stoll(value->GetText());
  }
  else if (util::IsTag(*value, NIL_TAG)) {
    myType = Type::NIL;
  }
  else if (util::IsTag(*value, STRING_TAG)) {
    myType = Type::STRING;
    as.myString = new String(value->GetText() ? value->GetText() : "");
  }
  else if (util::IsTag(*value, STRUCT_TAG)) {
    myType = Type::STRUCT;

    Struct data;
    for (auto member = value->FirstChildElement(MEMBER_TAG);
         member; member = member->NextSiblingElement(MEMBER_TAG)) {
      auto name = member->FirstChildElement(NAME_TAG);
      if (!name || util::HasEmptyText(*name)) {
        throw InvalidXmlRpcFault("missing name element in struct");
      }
      data.emplace(name->GetText(),
                   Value(member->LastChildElement(VALUE_TAG)));
    }
    as.myStruct = new Struct(std::move(data));
  }
  else {
    throw InvalidXmlRpcFault("invalid type");
  }
}

Value::Value(Array value)
  : myType(Type::ARRAY)
{
  as.myArray = new Array(std::move(value));
}

Value::Value(Binary value)
  : myType(Type::BINARY)
{
  as.myBinary = new Binary(std::move(value));
}

Value::Value(const DateTime& value)
  : myType(Type::DATE_TIME)
{
  as.myDateTime = new DateTime(value);
  as.myDateTime->tm_isdst = -1;
}

Value::Value(String value)
  : myType(Type::STRING)
{
  as.myString = new String(std::move(value));
}

Value::Value(Struct value)
  : myType(Type::STRUCT)
{
  as.myStruct = new Struct(std::move(value));
}

Value::~Value()
{
  Reset();
}

Value::Value(const Value& other)
  : myType(other.myType),
    as(other.as)
{
  switch (myType) {
    case Type::BOOLEAN:
    case Type::DOUBLE:
    case Type::INTEGER_32:
    case Type::INTEGER_64:
    case Type::NIL:
      break;

    case Type::ARRAY:
      as.myArray = new Array(other.AsArray());
      break;
    case Type::BINARY:
      as.myBinary = new Binary(other.AsBinary());
      break;
    case Type::DATE_TIME:
      as.myDateTime = new DateTime(other.AsDateTime());
      break;
    case Type::STRING:
      as.myString = new String(other.AsString());
      break;
    case Type::STRUCT:
      as.myStruct = new Struct(other.AsStruct());
      break;
  }
}

Value::Value(Value&& other) noexcept
  : myType(other.myType),
    as(other.as)
{
  other.myType = Type::NIL;
}

Value& Value::operator=(Value&& other) noexcept
{
  if (this != &other) {
    Reset();

    myType = other.myType;
    as = other.as;

    other.myType = Type::NIL;
  }
  return *this;
}

const Value::Array& Value::AsArray() const
{
  if (IsArray()) {
    return *as.myArray;
  }
  throw InvalidParametersFault();
}

const Value::Binary& Value::AsBinary() const
{
  if (IsBinary()) {
    return *as.myBinary;
  }
  throw InvalidParametersFault();
}

const bool& Value::AsBoolean() const
{
  if (IsBoolean()) {
    return as.myBoolean;
  }
  throw InvalidParametersFault();
}

const Value::DateTime& Value::AsDateTime() const
{
  if (IsDateTime()) {
    return *as.myDateTime;
  }
  throw InvalidParametersFault();
}

const double& Value::AsDouble() const
{
  if (IsDouble()) {
    return as.myDouble;
  }
  throw InvalidParametersFault();
}

const int32_t& Value::AsInteger32() const
{
  if (IsInteger32()) {
    return as.myInteger32;
  }
  throw InvalidParametersFault();
}

const int64_t& Value::AsInteger64() const
{
  if (IsInteger64()) {
    return as.myInteger64;
  }
  throw InvalidParametersFault();
}

const Value::String& Value::AsString() const
{
  if (IsString()) {
    return *as.myString;
  }
  throw InvalidParametersFault();
}

const Value::Struct& Value::AsStruct() const
{
  if (IsStruct()) {
    return *as.myStruct;
  }
  throw InvalidParametersFault();
}

std::string Value::GetTypeName(Type type)
{
  switch (type) {
    case Type::ARRAY:
      return ARRAY_TAG;
    case Type::BINARY:
      return BASE_64_TAG;
    case Type::BOOLEAN:
      return BOOLEAN_TAG;
    case Type::DATE_TIME:
      return DATE_TIME_TAG;
    case Type::DOUBLE:
      return DOUBLE_TAG;
    case Type::INTEGER_32:
      return INTEGER_32_TAG;
    case Type::INTEGER_64:
      return INTEGER_64_TAG;
    case Type::NIL:
      return NIL_TAG;
    case Type::STRING:
      return STRING_TAG;
    case Type::STRUCT:
      return STRUCT_TAG;
  }
  return {};
}

void Value::Print(tinyxml2::XMLPrinter& printer) const
{
  printer.OpenElement(VALUE_TAG);

  bool compact = false;
  switch (myType) {
    case Type::ARRAY: {
      printer.OpenElement(ARRAY_TAG);
      printer.OpenElement(DATA_TAG);
      for (const auto& element : *as.myArray) {
        element.Print(printer);
      }
      printer.CloseElement();
      printer.CloseElement();
      break;
    }
    case Type::BINARY:
      printer.OpenElement(BASE_64_TAG);
      printer.PushText(util::Base64Encode(*as.myBinary).c_str());
      printer.CloseElement();
      break;
    case Type::BOOLEAN:
      compact = true;
      printer.OpenElement(BOOLEAN_TAG, compact);
      printer.PushText(as.myBoolean);
      printer.CloseElement(compact);
      break;
    case Type::DATE_TIME:
      compact = true;
      printer.OpenElement(DATE_TIME_TAG, compact);
      printer.PushText(FormatIso8601DateTime(*as.myDateTime).c_str());
      printer.CloseElement(compact);
      break;
    case Type::DOUBLE:
      compact = true;
      printer.OpenElement(DOUBLE_TAG, compact);
      printer.PushText(as.myDouble);
      printer.CloseElement(compact);
      break;
    case Type::INTEGER_32:
      compact = true;
      printer.OpenElement(INTEGER_32_TAG, compact);
      printer.PushText(as.myInteger32);
      printer.CloseElement(compact);
      break;
    case Type::INTEGER_64:
      compact = true;
      printer.OpenElement(INTEGER_64_TAG, compact);
      printer.PushText(std::to_string(as.myInteger64).c_str());
      printer.CloseElement(compact);
      break;
    case Type::NIL:
      compact = true;
      printer.OpenElement(NIL_TAG, compact);
      printer.CloseElement(compact);
      break;
    case Type::STRING:
      compact = true;
      printer.OpenElement(STRING_TAG, compact);
      printer.PushText(as.myString->c_str());
      printer.CloseElement(compact);
      break;
    case Type::STRUCT: {
      printer.OpenElement(STRUCT_TAG);
      for (const auto& element : *as.myStruct) {
        printer.OpenElement(MEMBER_TAG);

        printer.OpenElement(NAME_TAG);
        printer.PushText(element.first.c_str());
        printer.CloseElement(true);

        element.second.Print(printer);
        printer.CloseElement();
      }
      printer.CloseElement();
      break;
    }
  }

  printer.CloseElement(compact);
}

void Value::Reset()
{
  switch (myType) {
    case Type::ARRAY:
      delete as.myArray;
      break;
    case Type::BINARY:
      delete as.myBinary;
      break;
    case Type::DATE_TIME:
      delete as.myDateTime;
      break;
    case Type::STRING:
      delete as.myString;
      break;
    case Type::STRUCT:
      delete as.myStruct;
      break;

    case Type::BOOLEAN:
    case Type::DOUBLE:
    case Type::INTEGER_32:
    case Type::INTEGER_64:
    case Type::NIL:
      break;
  }

  myType = Type::NIL;
}

std::ostream& operator<<(std::ostream& os, const Value& value)
{
  switch (value.GetType()) {
    case Value::Type::ARRAY: {
      os << '[';
      auto& a = value.AsArray();
      for (auto it = a.begin(); it != a.end(); ++it) {
        if (it != a.begin()) {
          os << ", ";
        }
        os << *it;
      }
      os << ']';
      break;
    }
    case Value::Type::BINARY:
      os << util::Base64Encode(value.AsBinary());
      break;
    case Value::Type::BOOLEAN:
      os << value.AsBoolean();
      break;
    case Value::Type::DATE_TIME:
      os << FormatIso8601DateTime(value.AsDateTime());
      break;
    case Value::Type::DOUBLE:
      os << value.AsDouble();
      break;
    case Value::Type::INTEGER_32:
      os << value.AsInteger32();
      break;
    case Value::Type::INTEGER_64:
      os << value.AsInteger64();
      break;
    case Value::Type::NIL:
      os << "<nil>";
      break;
    case Value::Type::STRING:
      os << '"' << value.AsString() << '"';
      break;
    case Value::Type::STRUCT: {
      os << '{';
      auto& s = value.AsStruct();
      for (auto it = s.begin(); it != s.end(); ++it) {
        if (it != s.begin()) {
          os << ", ";
        }
        os << it->first << ": " << it->second;
      }
      os << '}';
      break;
    }
  }
  return os;
}

} // namespace xsonrpc
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_DEFAULT_HH
#define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_DEFAULT_HH

// dune-common
#include <dune/common/parametertree.hh>
#include <dune/common/shared_ptr.hh>

// dune-stuff
#include <dune/stuff/function/expression.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/grid/boundaryinfo.hh>

namespace Dune {

namespace Detailed {

namespace Solvers {

namespace Stationary {

namespace Linear {

namespace Elliptic {

namespace Model {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Default
{
public:
  typedef DomainFieldImp DomainFieldType;

  static const int dimDomain = domainDim;

  typedef RangeFieldImp RangeFieldType;

  static const int dimRange = rangeDim;

  typedef Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ThisType;

  static const std::string id;

  typedef Dune::Stuff::Function::Expression< DomainFieldType, dimDomain, RangeFieldType, dimRange > DiffusionType;

  typedef DiffusionType ForceType;

  typedef DiffusionType DirichletType;

  Default(const Dune::Stuff::Common::ExtendedParameterTree paramTree)
    : diffusionOrder_(-1)
    , forceOrder_(-1)
    , dirichletOrder_(-1)
  {
    // check parametertree
    paramTree.assertSub("diffusion", id);
    paramTree.assertSub("force", id);
    paramTree.assertSub("dirichlet", id);
    paramTree.assertKey("diffusion.order", id);
    paramTree.assertKey("force.order", id);
    paramTree.assertKey("dirichlet.order", id);
    // build functions
    diffusion_ = Dune::shared_ptr< DiffusionType >(new DiffusionType(paramTree.sub("diffusion")));
    force_ = Dune::shared_ptr< ForceType >(new ForceType(paramTree.sub("force")));
    dirichlet_ = Dune::shared_ptr< DirichletType >(new DirichletType(paramTree.sub("dirichlet")));
    // set orders
    diffusionOrder_ = paramTree.sub("diffusion").get("order", -1);
    forceOrder_ = paramTree.sub("force").get("order", -1);
    dirichletOrder_ = paramTree.sub("dirichlet").get("order", -1);
  }

  Default(const ThisType& other)
    : diffusionOrder_(other.diffusionOrder_)
    , forceOrder_(other.forceOrder_)
    , dirichletOrder_(other.dirichletOrder_)
    , diffusion_(other.diffusion_)
    , force_(other.force_)
    , dirichlet_(other.dirichlet_)
  {}

  const Dune::shared_ptr< DiffusionType > diffusion() const
  {
    return diffusion_;
  }

  int diffusionOrder() const
  {
    return diffusionOrder_;
  }

  const Dune::shared_ptr< ForceType > force() const
  {
    return force_;
  }

  int forceOrder() const
  {
    return forceOrder_;
  }

  const Dune::shared_ptr< DirichletType > dirichlet() const
  {
    return dirichlet_;
  }

  int dirichletOrder() const
  {
    return dirichletOrder_;
  }

private:
  ThisType& operator=(const ThisType&);

  int diffusionOrder_;
  int forceOrder_;
  int dirichletOrder_;
  Dune::shared_ptr< DiffusionType > diffusion_;
  Dune::shared_ptr< ForceType > force_;
  Dune::shared_ptr< DirichletType > dirichlet_;
}; // class Default

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
const std::string Default< DomainFieldType, dimDomain, RangeFieldType, dimRange >::id = "detailed.solvers.stationary.linear.elliptic.model.default";

} // namespace Model

} // namespace Elliptic

} // namespace Linear

} // namespace Stationary

} // namespace Solvers

} // namespace Detailed

} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_DEFAULT_HH
<commit_msg>[...elliptic.model.default] derived from interface<commit_after>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_DEFAULT_HH
#define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_DEFAULT_HH

// dune-common
#include <dune/common/shared_ptr.hh>

// dune-stuff
#include <dune/stuff/function/expression.hh>
#include <dune/stuff/common/parameter/tree.hh>

// local
#include "interface.hh"

namespace Dune {

namespace Detailed {

namespace Solvers {

namespace Stationary {

namespace Linear {

namespace Elliptic {

namespace Model {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Default
  : public Interface < DomainFieldImp, domainDim, RangeFieldImp, rangeDim >
{
public:
  typedef DomainFieldImp DomainFieldType;

  static const int dimDomain = domainDim;

  typedef RangeFieldImp RangeFieldType;

  static const int dimRange = rangeDim;

  typedef Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > BaseType;

  typedef Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > ThisType;

  static const std::string id;

  typedef typename BaseType::DiffusionType DiffusionType;

  typedef typename BaseType::ForceType ForceType;

  typedef typename BaseType::DirichletType DirichletType;

  Default(const Dune::Stuff::Common::ExtendedParameterTree paramTree)
    : diffusionOrder_(-1)
    , forceOrder_(-1)
    , dirichletOrder_(-1)
  {
    // check parametertree
    paramTree.assertSub("diffusion", id);
    paramTree.assertSub("force", id);
    paramTree.assertSub("dirichlet", id);
    paramTree.assertKey("diffusion.order", id);
    paramTree.assertKey("force.order", id);
    paramTree.assertKey("dirichlet.order", id);
    // build functions
    typedef Dune::Stuff::Function::Expression< DomainFieldType, dimDomain, RangeFieldType, dimRange > ExpressionFunctionType;
    diffusion_ = Dune::shared_ptr< DiffusionType >(new ExpressionFunctionType(paramTree.sub("diffusion")));
    force_ = Dune::shared_ptr< ForceType >(new ExpressionFunctionType(paramTree.sub("force")));
    dirichlet_ = Dune::shared_ptr< DirichletType >(new ExpressionFunctionType(paramTree.sub("dirichlet")));
    // set orders
    diffusionOrder_ = paramTree.sub("diffusion").get("order", -1);
    forceOrder_ = paramTree.sub("force").get("order", -1);
    dirichletOrder_ = paramTree.sub("dirichlet").get("order", -1);
  }

  Default(const ThisType& other)
    : diffusionOrder_(other.diffusionOrder_)
    , forceOrder_(other.forceOrder_)
    , dirichletOrder_(other.dirichletOrder_)
    , diffusion_(other.diffusion_)
    , force_(other.force_)
    , dirichlet_(other.dirichlet_)
  {}

  virtual const Dune::shared_ptr< const DiffusionType > diffusion() const
  {
    return diffusion_;
  }

  virtual int diffusionOrder() const
  {
    return diffusionOrder_;
  }

  virtual const Dune::shared_ptr< const ForceType > force() const
  {
    return force_;
  }

  virtual int forceOrder() const
  {
    return forceOrder_;
  }

  virtual const Dune::shared_ptr< const DirichletType > dirichlet() const
  {
    return dirichlet_;
  }

  virtual int dirichletOrder() const
  {
    return dirichletOrder_;
  }

private:
  ThisType& operator=(const ThisType&);

  int diffusionOrder_;
  int forceOrder_;
  int dirichletOrder_;
  Dune::shared_ptr< DiffusionType > diffusion_;
  Dune::shared_ptr< ForceType > force_;
  Dune::shared_ptr< DirichletType > dirichlet_;
}; // class Default

template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange >
const std::string Default< DomainFieldType, dimDomain, RangeFieldType, dimRange >::id = "detailed.solvers.stationary.linear.elliptic.model.default";

} // namespace Model

} // namespace Elliptic

} // namespace Linear

} // namespace Stationary

} // namespace Solvers

} // namespace Detailed

} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_DEFAULT_HH
<|endoftext|>