<commit_before>
#include <iostream>
#include <sstream>
#include <random>
#include <functional>
#include <memory>

#include <gui/application.h>
#include <gui/dark_style.h>
#include <gui/container.h>
#include <gui/layouts.h>
#include <gui/label.h>
#include <gui/button.h>
#include <gui/slider.h>
#include <gui/background_color.h>
#include <gui/scroll_area.h>
#include <gui/tree_node.h>
#include <gui/line_edit.h>
#include <gui/color_picker.h>

constexpr double padding = 12.5;

namespace {

struct test_record : public model::record
{
	field<std::string> title = field<std::string>( this );
	field<double> rating = field<double>( this, 0.5 );
};

std::shared_ptr<test_record> testrec = std::make_shared<test_record>();

////////////////////////////////////////

std::shared_ptr<gui::form> build_form( direction dir )
{
	auto container = std::make_shared<gui::form>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	auto button = std::make_shared<gui::button>( "Click Me" );
	button->when_activated += []()
	{
		testrec->title = "Goodbye World";
	};

	container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ), button );
	container->add( std::make_shared<gui::label>( "What" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
	container->add( std::make_shared<gui::label>( "Who" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::background> build_grid( direction dir )
{
	auto container = std::make_shared<gui::grid>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	std::string name( "A" );
	std::vector<std::shared_ptr<gui::widget>> row;
	const double weights[5] = { 0.25, 0.5, 1.0, 0.5, 0.25 };
	for ( size_t y = 0; y < 5; ++y )
	{
		row.clear();
		for ( size_t x = 0; x < 5; ++x )
		{
			row.push_back( std::make_shared<gui::label>( name, alignment::CENTER ) );
			++name[0];
		}
		container->add_row( row, weights[y] );
	}
	for ( size_t y = 0; y < 5; ++y )
		container->set_column_weight( y, weights[y] );

	auto bg = std::make_shared<gui::background_color>();// { 1, 0, 1, 1 }, container );
	bg->set_color( { 1, 0, 1, 1 } );
	bg->set_widget( container );

	return bg;
}

////////////////////////////////////////

std::shared_ptr<gui::simple_container> build_box( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	std::string name( "A" );
	std::vector<std::shared_ptr<gui::widget>> row;
	for ( size_t y = 0; y < 5; ++y )
	{
		container->add( std::make_shared<gui::label>( name, alignment::CENTER ) );
		++name[0];
	}

	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::tree_node> build_tree( direction dir )
{
	auto container = std::make_shared<gui::tree_node>( 24.0, dir );
	container->set_root( std::make_shared<gui::label>( "Root" ) );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	std::string name( "A" );
	for ( size_t y = 0; y < 3; ++y )
	{
		auto node = std::make_shared<gui::tree_node>( 24.0, dir );
		if( y == 1 )
		{
			auto button = std::make_shared<gui::button>( "+" );
			button->when_activated += [=]( void )
			{
				node->set_collapsed( !node->collapsed() );
			};
			node->set_root( button );
		}
		else
			node->set_root( std::make_shared<gui::label>( name ) );
		std::string sub( "1" );
		for ( size_t x = 0; x < 3; ++x )
		{
			node->add( std::make_shared<gui::label>( sub ) );
			node->set_spacing( 12, 6 );
			++sub[0];
		}
		container->add( node );
		++name[0];
	}

	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::simple_container> build_edit( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ) );
	container->add( std::make_shared<gui::line_edit>( model::make_datum( testrec, testrec->title ) ) );
	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::widget> build_all( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );

	std::vector<std::shared_ptr<gui::widget>> list = { build_form( dir ), build_grid( dir ), build_box( dir ), build_tree( dir ) };

	for ( auto c: list )
		container->add( c );
	container->set_weight( 1, 1.0 );

	auto scroll = std::make_shared<gui::scroll_area>( gui::scroll_behavior::NONE, gui::scroll_behavior::BOUND );
	scroll->set_widget( container );

	return scroll;
}

////////////////////////////////////////

std::shared_ptr<gui::simple_container> build_color( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	container->add( std::make_shared<gui::color_picker>( core::color::space::HSL ), 1.0 );
	container->add( std::make_shared<gui::color_picker>( core::color::space::LAB ), 1.0 );

	return container;
}

////////////////////////////////////////

int safemain( int argc, char **argv )
{
	testrec->title = "Hello World";

	auto app = std::make_shared<gui::application>();
	app->push();
	app->set_style( std::make_shared<gui::dark_style>() );

	auto win = app->new_window();
	win->set_title( app->active_platform() );

	std::string test = "form";
	if ( argc > 1 )
		test = argv[1];

	std::string dirname = "box";
	if ( argc > 2 )
		dirname = argv[2];
	direction dir = direction::DOWN;
	if ( dirname == "down" )
		dir = direction::DOWN;
	else if ( dirname == "up" )
		dir = direction::UP;
	else if ( dirname == "left" )
		dir = direction::LEFT;
	else if ( dirname == "right" )
		dir = direction::RIGHT;

	if ( test == "form" )
		win->set_widget( build_form( dir ) );
	else if ( test == "grid" )
		win->set_widget( build_grid( dir ) );
	else if ( test == "box" )
		win->set_widget( build_box( dir ) );
	else if ( test == "tree" )
		win->set_widget( build_tree( dir ) );
	else if ( test == "edit" )
		win->set_widget( build_edit( dir ) );
	else if ( test == "color" )
		win->set_widget( build_color( dir ) );
	else if ( test == "all" )
		win->set_widget( build_all( dir ) );
	else
		throw std::runtime_error( "unknown test" );

	win->show();
	int code = app->run();
	app->pop();
	return code;
}

////////////////////////////////////////

}

////////////////////////////////////////

int main( int argc, char *argv[] )
{
	int ret = -1;
	try
	{
		ret = safemain( argc, argv );
	}
	catch ( std::exception &e )
	{
		print_exception( std::cerr, e );
	}
	return ret;
}

////////////////////////////////////////

<commit_msg>Use integer coordinates.<commit_after>
#include <iostream>
#include <sstream>
#include <random>
#include <functional>
#include <memory>

#include <gui/application.h>
#include <gui/dark_style.h>
#include <gui/container.h>
#include <gui/layouts.h>
#include <gui/label.h>
#include <gui/button.h>
#include <gui/slider.h>
#include <gui/background_color.h>
#include <gui/scroll_area.h>
#include <gui/tree_node.h>
#include <gui/line_edit.h>
#include <gui/color_picker.h>

constexpr double padding = 12;

namespace {

struct test_record : public model::record
{
	field<std::string> title = field<std::string>( this );
	field<double> rating = field<double>( this, 1.0 );
};

std::shared_ptr<test_record> testrec = std::make_shared<test_record>();

////////////////////////////////////////

std::shared_ptr<gui::form> build_form( direction dir )
{
	auto container = std::make_shared<gui::form>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	auto button = std::make_shared<gui::button>( "Click Me" );
	button->when_activated += []()
	{
		testrec->title = "Goodbye World";
	};

	container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ), button );
	container->add( std::make_shared<gui::label>( "What" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
	container->add( std::make_shared<gui::label>( "Who" ), std::make_shared<gui::slider>( model::make_datum( testrec, testrec->rating ) ) );
	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::background> build_grid( direction dir )
{
	auto container = std::make_shared<gui::grid>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	std::string name( "A" );
	std::vector<std::shared_ptr<gui::widget>> row;
	const double weights[5] = { 0.25, 0.5, 1.0, 0.5, 0.25 };
	for ( size_t y = 0; y < 5; ++y )
	{
		row.clear();
		for ( size_t x = 0; x < 5; ++x )
		{
			row.push_back( std::make_shared<gui::label>( name, alignment::CENTER ) );
			++name[0];
		}
		container->add_row( row, weights[y] );
	}
	for ( size_t y = 0; y < 5; ++y )
		container->set_column_weight( y, weights[y] );

	auto bg = std::make_shared<gui::background_color>();// { 1, 0, 1, 1 }, container );
	bg->set_color( { 1, 0, 1, 1 } );
	bg->set_widget( container );

	return bg;
}

////////////////////////////////////////

std::shared_ptr<gui::simple_container> build_box( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	std::string name( "A" );
	std::vector<std::shared_ptr<gui::widget>> row;
	for ( size_t y = 0; y < 5; ++y )
	{
		container->add( std::make_shared<gui::label>( name, alignment::CENTER ) );
		++name[0];
	}

	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::tree_node> build_tree( direction dir )
{
	auto container = std::make_shared<gui::tree_node>( 24.0, dir );
	container->set_root( std::make_shared<gui::label>( "Root" ) );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	std::string name( "A" );
	for ( size_t y = 0; y < 3; ++y )
	{
		auto node = std::make_shared<gui::tree_node>( 24.0, dir );
		if( y == 1 )
		{
			auto button = std::make_shared<gui::button>( "+" );
			button->when_activated += [=]( void )
			{
				node->set_collapsed( !node->collapsed() );
			};
			node->set_root( button );
		}
		else
			node->set_root( std::make_shared<gui::label>( name ) );
		std::string sub( "1" );
		for ( size_t x = 0; x < 3; ++x )
		{
			node->add( std::make_shared<gui::label>( sub ) );
			node->set_spacing( 12, 6 );
			++sub[0];
		}
		container->add( node );
		++name[0];
	}

	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::simple_container> build_edit( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	container->add( std::make_shared<gui::label>( model::make_datum( testrec, testrec->title ) ) );
	container->add( std::make_shared<gui::line_edit>( model::make_datum( testrec, testrec->title ) ) );
	return container;
}

////////////////////////////////////////

std::shared_ptr<gui::widget> build_all( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );

	std::vector<std::shared_ptr<gui::widget>> list = { build_form( dir ), build_grid( dir ), build_box( dir ), build_tree( dir ) };

	for ( auto c: list )
		container->add( c );
	container->set_weight( 1, 1.0 );

	auto scroll = std::make_shared<gui::scroll_area>( gui::scroll_behavior::NONE, gui::scroll_behavior::BOUND );
	scroll->set_widget( container );

	return scroll;
}

////////////////////////////////////////

std::shared_ptr<gui::simple_container> build_color( direction dir )
{
	auto container = std::make_shared<gui::simple_container>( dir );
	container->set_spacing( 12, 6 );
	container->set_pad( padding, padding, padding, padding );

	container->add( std::make_shared<gui::color_picker>( core::color::space::HSL ), 1.0 );
	container->add( std::make_shared<gui::color_picker>( core::color::space::LAB ), 1.0 );

	return container;
}

////////////////////////////////////////

int safemain( int argc, char **argv )
{
	testrec->title = "Hello World";

	auto app = std::make_shared<gui::application>();
	app->push();
	app->set_style( std::make_shared<gui::dark_style>() );

	auto win = app->new_window();
	win->set_title( app->active_platform() );

	std::string test = "form";
	if ( argc > 1 )
		test = argv[1];

	std::string dirname = "box";
	if ( argc > 2 )
		dirname = argv[2];
	direction dir = direction::DOWN;
	if ( dirname == "down" )
		dir = direction::DOWN;
	else if ( dirname == "up" )
		dir = direction::UP;
	else if ( dirname == "left" )
		dir = direction::LEFT;
	else if ( dirname == "right" )
		dir = direction::RIGHT;

	if ( test == "form" )
		win->set_widget( build_form( dir ) );
	else if ( test == "grid" )
		win->set_widget( build_grid( dir ) );
	else if ( test == "box" )
		win->set_widget( build_box( dir ) );
	else if ( test == "tree" )
		win->set_widget( build_tree( dir ) );
	else if ( test == "edit" )
		win->set_widget( build_edit( dir ) );
	else if ( test == "color" )
		win->set_widget( build_color( dir ) );
	else if ( test == "all" )
		win->set_widget( build_all( dir ) );
	else
		throw std::runtime_error( "unknown test" );

	win->show();
	int code = app->run();
	app->pop();
	return code;
}

////////////////////////////////////////

}

////////////////////////////////////////

int main( int argc, char *argv[] )
{
	int ret = -1;
	try
	{
		ret = safemain( argc, argv );
	}
	catch ( std::exception &e )
	{
		print_exception( std::cerr, e );
	}
	return ret;
}

////////////////////////////////////////

<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iterator>
#include <utility>
#include <deque>
#include <string>
#include <stdlib.h>
#include "nfa.hxx"

extern int yyparse (void*);
extern FILE* yyin;

int main(int argc, char* argv[])
{
    if (argc == 2) {
	if (!(yyin = fopen(argv[1],"r"))) {
	    perror("chyba fopen()");
	    exit(EXIT_FAILURE);
	}
    }
    else
	yyin = stdin;

    NFA nfa;
    int ret = yyparse((void*)&nfa);
    std::cerr << "yyparse() == " << ret << std::endl;
    if (ret == 1) {
	std::cerr << "chyba pri parsovani vstupu" << std::endl;
	exit(EXIT_FAILURE);
    }

    for (DeltaMappingT::const_iterator i = nfa.delta.begin();
	 i != nfa.delta.end();
	 ++i) {
	std::cout << i->first << std::endl;
    }

}
<commit_msg>2002-09-01 2002-09-01 * testgram.cxx: Remove.<commit_after><|endoftext|>


<commit_before>
#include "external/hash_impl.h"

namespace BitCrypto{

template<class Iterator, class OutIterator>
void Sha256::hash(Iterator begin, Iterator end, OutIterator out) const
{
    secp256k1_sha256_t hash;
    secp256k1_sha256_initialize(&hash);
    secp256k1_sha256_write(&hash, &*begin, end-begin);
    secp256k1_sha256_finalize(&hash, &*out);
}

template<class Output, class Iterator>
Output Sha256::hash(Iterator begin, Iterator end) const
{
    Output output;
    output.resize(32);
    hash(begin, end, output.begin());
    return output;
}

template<class Iterator>
Data Sha256::hash(Iterator begin, Iterator end) const
{
    return hash<Data>(begin, end);
}

template<class Input>
Data Sha256::hash(const Input &input) const
{
    return hash(input.begin(), input.end());
}

}
<commit_msg>conversion to unsigned char *<commit_after>
#include "external/hash_impl.h"

namespace BitCrypto{

template<class Iterator, class OutIterator>
void Sha256::hash(Iterator begin, Iterator end, OutIterator out) const
{
    secp256k1_sha256_t hash;
    secp256k1_sha256_initialize(&hash);
    secp256k1_sha256_write(&hash, (const unsigned char *)&*begin, end-begin);
    secp256k1_sha256_finalize(&hash, &*out);
}

template<class Output, class Iterator>
Output Sha256::hash(Iterator begin, Iterator end) const
{
    Output output;
    output.resize(32);
    hash(begin, end, output.begin());
    return output;
}

template<class Iterator>
Data Sha256::hash(Iterator begin, Iterator end) const
{
    return hash<Data>(begin, end);
}

template<class Input>
Data Sha256::hash(const Input &input) const
{
    return hash(input.begin(), input.end());
}

}
<|endoftext|>


<commit_before>#include <ostream>
#include <vector>
#include <utility>
#include "core/cexception.h"
#include "modules/std/core/function.h"
#include "modules/std/io/serializer.h"

namespace clever { namespace modules { namespace std {

void Serializer::dump(TypeObject* obj, ::std::ostream& out) const
{
	SerializerData* sobj = static_cast<SerializerData*>(obj);

	sobj->type->dump(sobj->info.second, out);
}

// Serializer.serialize()
CLEVER_METHOD(Serializer::doSerialize)
{
	if (!clever_static_check_args(".")) {
		return;
	}

	SerializerData* sobj = new SerializerData(args[0]->getType());

	sobj->info = args[0]->getType()->serialize(args[0]);

	clever_addref(args[0]);

	result->setObj(this, sobj);
}

// Serializer.unserialize()
CLEVER_METHOD(Serializer::doUnserialize)
{
	if (!clever_static_check_args(".")) {
		return;
	}

	if (args[0]->getType() != this) {
		clever_throw("Parameter must be of SerializerData type");
		return;
	}
	SerializerData* sobj = CLEVER_GET_OBJECT(SerializerData*, args[0]);
	Value* res = unserialize(sobj->type, sobj->info);

	if (res) {
		result->copy(res);
		clever_delref(res);
	}
}

// Serializer type initialization
CLEVER_TYPE_INIT(Serializer::init)
{
	addMethod(new Function("serialize", (MethodPtr)&Serializer::doSerialize))
		->setStatic();

	addMethod(new Function("unserialize", (MethodPtr)&Serializer::doUnserialize))
		->setStatic();
}

}}} // clever::modules::std
<commit_msg>- Fixed memory leak<commit_after>#include <ostream>
#include <vector>
#include <utility>
#include "core/cexception.h"
#include "modules/std/core/function.h"
#include "modules/std/io/serializer.h"

namespace clever { namespace modules { namespace std {

void Serializer::dump(TypeObject* obj, ::std::ostream& out) const
{
	SerializerData* sobj = static_cast<SerializerData*>(obj);

	sobj->type->dump(sobj->info.second, out);
}

// Serializer.serialize()
CLEVER_METHOD(Serializer::doSerialize)
{
	if (!clever_static_check_args(".")) {
		return;
	}

	SerializerData* sobj = new SerializerData(args[0]->getType());

	sobj->info = args[0]->getType()->serialize(args[0]);

	clever_addref(args[0]->getObj());

	result->setObj(this, sobj);
}

// Serializer.unserialize()
CLEVER_METHOD(Serializer::doUnserialize)
{
	if (!clever_static_check_args(".")) {
		return;
	}

	if (args[0]->getType() != this) {
		clever_throw("Parameter must be of SerializerData type");
		return;
	}
	SerializerData* sobj = CLEVER_GET_OBJECT(SerializerData*, args[0]);
	Value* res = unserialize(sobj->type, sobj->info);

	if (res) {
		result->copy(res);
		clever_delref(res);
	}
}

// Serializer type initialization
CLEVER_TYPE_INIT(Serializer::init)
{
	addMethod(new Function("serialize", (MethodPtr)&Serializer::doSerialize))
		->setStatic();

	addMethod(new Function("unserialize", (MethodPtr)&Serializer::doUnserialize))
		->setStatic();
}

}}} // clever::modules::std
<|endoftext|>


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

  Program:   Visualization Library
  Module:    StrData.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Description:
---------------------------------------------------------------------------
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "StrData.hh"

vlStructuredDataSet::vlStructuredDataSet()
{
  this->Dimensions[0] = 1;
  this->Dimensions[1] = 1;
  this->Dimensions[2] = 1;
  this->DataDescription = SINGLE_POINT;

  this->Blanking = 0;
  this->PointVisibility = 0;
}

vlStructuredDataSet::vlStructuredDataSet(const vlStructuredDataSet& sds)
{
  this->Dimensions[0] = sds.Dimensions[0];
  this->Dimensions[1] = sds.Dimensions[1];
  this->Dimensions[2] = sds.Dimensions[2];
  this->DataDescription = sds.DataDescription;

  this->Blanking = sds.Blanking;
  this->PointVisibility = sds.PointVisibility;
}

vlStructuredDataSet::~vlStructuredDataSet()
{
  this->Initialize();
}

void vlStructuredDataSet::SetDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetDimensions(dim);
}

void vlStructuredDataSet::SetDimensions(int dim[3])
{
  if ( dim[0] != this->Dimensions[0] || dim[1] != Dimensions[1] ||
  dim[2] != Dimensions[2] )
    {
    if ( dim[0]<1 || dim[1]<1 || dim[2]<1 )
      {
      vlErrorMacro (<< "Bad Dimensions, retaining previous values");
      return;
      }

    for (int dataDim=0, i=0; i<3 ; i++)
      {
      this->Dimensions[i] = dim[i];
      if (dim[i] > 1) dataDim++;
      }

    if ( dataDim == 3 )
      {
      this->DataDescription = XYZ_GRID;
      }
    else if ( dataDim == 2)
      {
      if ( dim[0] == 1 ) this->DataDescription = YZ_PLANE;
      else if ( dim[1] == 1 ) this->DataDescription = XZ_PLANE;
      else this->DataDescription = XY_PLANE;
      }
    else if ( dataDim == 1 )
      {
      if ( dim[0] != 1 ) this->DataDescription = X_LINE;
      else if ( dim[1] != 1 ) this->DataDescription = Y_LINE;
      else this->DataDescription = Z_LINE;
      }
    else
      {
      this->DataDescription = SINGLE_POINT;
      }

    this->Modified();
    }
}

void vlStructuredDataSet::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlStructuredDataSet::GetClassName()))
    {
    vlDataSet::PrintSelf(os,indent);

    os << indent << "Dimensions: (" << this->Dimensions[0] << ", "
                                    << this->Dimensions[1] << ", "
                                    << this->Dimensions[2] << ")\n";
    }
}

int vlStructuredDataSet::GetNumberOfCells()
{
  int nCells=1;
  int i;

  for (i=0; i<3; i++)
    if (this->Dimensions[i] > 1)
      nCells *= (this->Dimensions[1]-1);

  return nCells;
}

int vlStructuredDataSet::GetNumberOfPoints()
{
  return Dimensions[0]*Dimensions[1]*Dimensions[2];
}

void vlStructuredDataSet::BlankingOn()
{
  this->Blanking = 1;
  this->Modified();

  if ( !this->PointVisibility )
    {
    this->PointVisibility = new vlCharArray(this->GetNumberOfPoints(),1000);
    for (int i=0; i<this->GetNumberOfPoints(); i++)
      {
      this->PointVisibility->InsertValue(i,1);
      }
    }
}

void vlStructuredDataSet::BlankingOff()
{
  this->Blanking = 0;
  this->Modified();
}

void vlStructuredDataSet::BlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->BlankingOn();
  this->PointVisibility->InsertValue(ptId,0);
}

void vlStructuredDataSet::UnBlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->BlankingOn();
  this->PointVisibility->InsertValue(ptId,1);
}

void vlStructuredDataSet::Initialize()
{
  vlDataSet::Initialize();

  this->SetDimensions(1,1,1);
  this->Blanking = 0;

  if ( this->PointVisibility )
    {
    this->PointVisibility->UnRegister(this);
    this->PointVisibility = 0;
    }
}

void vlStructuredDataSet::GetPointCells(int ptId, vlIdList *cellIds)
{
  int ptDim[3], cellDim[3];
  int ptLoc[3], cellLoc[3];
  int i, j, cellId, add;
  static int offset[8][3] = {-1,0,0, -1,-1,0, -1,-1,-1, -1,0,-1,
                               0,0,0,  0,-1,0,  0,-1,-1,  0,0,-1};

  for (i=0; i<3; i++)
    {
    ptDim[i] = this->Dimensions[i];
    cellDim[i] = ptDim[i] - 1;
    }
//
//  Get the location of the point
//
  ptLoc[0] = ptId % ptDim[0];
  ptLoc[1] = ptId % (ptDim[0]*ptDim[1]) / ptDim[0];
  ptLoc[2] = ptId / (ptDim[0]*ptDim[1]);
//
//  From the point lcoation, compute the cell locations.  There are at
//  most eight possible.
//
  cellIds->Reset();

  for (j=0; j<8; j++)
    {
    for (add=1, i=0; i<3; i++)
      {
      cellLoc[i] = ptLoc[i] + offset[j][i];
      if ( cellLoc[i] < 0 || cellLoc[i] >= cellDim[i] )
        {
        add = 0;
        break;
        }
      }
    if ( add )
      {
      cellId = cellLoc[0] + cellLoc[1]*cellDim[0] +
                            cellLoc[2]*cellDim[0]*cellDim[1];
      cellIds->InsertNextId(cellId);
      }
    }

  return;
}
<commit_msg>added a debug statement<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    StrData.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Description:
---------------------------------------------------------------------------
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "StrData.hh"

vlStructuredDataSet::vlStructuredDataSet()
{
  this->Dimensions[0] = 1;
  this->Dimensions[1] = 1;
  this->Dimensions[2] = 1;
  this->DataDescription = SINGLE_POINT;

  this->Blanking = 0;
  this->PointVisibility = 0;
}

vlStructuredDataSet::vlStructuredDataSet(const vlStructuredDataSet& sds)
{
  this->Dimensions[0] = sds.Dimensions[0];
  this->Dimensions[1] = sds.Dimensions[1];
  this->Dimensions[2] = sds.Dimensions[2];
  this->DataDescription = sds.DataDescription;

  this->Blanking = sds.Blanking;
  this->PointVisibility = sds.PointVisibility;
}

vlStructuredDataSet::~vlStructuredDataSet()
{
  this->Initialize();
}

void vlStructuredDataSet::SetDimensions(int i, int j, int k)
{
  int dim[3];

  dim[0] = i;
  dim[1] = j;
  dim[2] = k;

  this->SetDimensions(dim);
}

void vlStructuredDataSet::SetDimensions(int dim[3])
{
  vlDebugMacro(<< " setting Dimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")\n\n");

  if ( dim[0] != this->Dimensions[0] || dim[1] != Dimensions[1] ||
  dim[2] != Dimensions[2] )
    {
    if ( dim[0]<1 || dim[1]<1 || dim[2]<1 )
      {
      vlErrorMacro (<< "Bad Dimensions, retaining previous values");
      return;
      }

    for (int dataDim=0, i=0; i<3 ; i++)
      {
      this->Dimensions[i] = dim[i];
      if (dim[i] > 1) dataDim++;
      }

    if ( dataDim == 3 )
      {
      this->DataDescription = XYZ_GRID;
      }
    else if ( dataDim == 2)
      {
      if ( dim[0] == 1 ) this->DataDescription = YZ_PLANE;
      else if ( dim[1] == 1 ) this->DataDescription = XZ_PLANE;
      else this->DataDescription = XY_PLANE;
      }
    else if ( dataDim == 1 )
      {
      if ( dim[0] != 1 ) this->DataDescription = X_LINE;
      else if ( dim[1] != 1 ) this->DataDescription = Y_LINE;
      else this->DataDescription = Z_LINE;
      }
    else
      {
      this->DataDescription = SINGLE_POINT;
      }

    this->Modified();
    }
}

void vlStructuredDataSet::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlStructuredDataSet::GetClassName()))
    {
    vlDataSet::PrintSelf(os,indent);

    os << indent << "Dimensions: (" << this->Dimensions[0] << ", "
                                    << this->Dimensions[1] << ", "
                                    << this->Dimensions[2] << ")\n";
    }
}

int vlStructuredDataSet::GetNumberOfCells()
{
  int nCells=1;
  int i;

  for (i=0; i<3; i++)
    if (this->Dimensions[i] > 1)
      nCells *= (this->Dimensions[1]-1);

  return nCells;
}

int vlStructuredDataSet::GetNumberOfPoints()
{
  return Dimensions[0]*Dimensions[1]*Dimensions[2];
}

void vlStructuredDataSet::BlankingOn()
{
  this->Blanking = 1;
  this->Modified();

  if ( !this->PointVisibility )
    {
    this->PointVisibility = new vlCharArray(this->GetNumberOfPoints(),1000);
    for (int i=0; i<this->GetNumberOfPoints(); i++)
      {
      this->PointVisibility->InsertValue(i,1);
      }
    }
}

void vlStructuredDataSet::BlankingOff()
{
  this->Blanking = 0;
  this->Modified();
}

void vlStructuredDataSet::BlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->BlankingOn();
  this->PointVisibility->InsertValue(ptId,0);
}

void vlStructuredDataSet::UnBlankPoint(int ptId)
{
  if ( !this->PointVisibility ) this->BlankingOn();
  this->PointVisibility->InsertValue(ptId,1);
}

void vlStructuredDataSet::Initialize()
{
  vlDataSet::Initialize();

  this->SetDimensions(1,1,1);
  this->Blanking = 0;

  if ( this->PointVisibility )
    {
    this->PointVisibility->UnRegister(this);
    this->PointVisibility = 0;
    }
}

void vlStructuredDataSet::GetPointCells(int ptId, vlIdList *cellIds)
{
  int ptDim[3], cellDim[3];
  int ptLoc[3], cellLoc[3];
  int i, j, cellId, add;
  static int offset[8][3] = {-1,0,0, -1,-1,0, -1,-1,-1, -1,0,-1,
                               0,0,0,  0,-1,0,  0,-1,-1,  0,0,-1};

  for (i=0; i<3; i++)
    {
    ptDim[i] = this->Dimensions[i];
    cellDim[i] = ptDim[i] - 1;
    }
//
//  Get the location of the point
//
  ptLoc[0] = ptId % ptDim[0];
  ptLoc[1] = ptId % (ptDim[0]*ptDim[1]) / ptDim[0];
  ptLoc[2] = ptId / (ptDim[0]*ptDim[1]);
//
//  From the point lcoation, compute the cell locations.  There are at
//  most eight possible.
//
  cellIds->Reset();

  for (j=0; j<8; j++)
    {
    for (add=1, i=0; i<3; i++)
      {
      cellLoc[i] = ptLoc[i] + offset[j][i];
      if ( cellLoc[i] < 0 || cellLoc[i] >= cellDim[i] )
        {
        add = 0;
        break;
        }
      }
    if ( add )
      {
      cellId = cellLoc[0] + cellLoc[1]*cellDim[0] +
                            cellLoc[2]*cellDim[0]*cellDim[1];
      cellIds->InsertNextId(cellId);
      }
    }

  return;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------- Sudoku.cpp

#include "AppInfo.h"
#include "SudokuSolver.h"

#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

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

int main(int argc, char *argv[])
{
  vector<string> input;

  if (argc > 1)
  {
    cout << "- " << APPNAME_VERSION << " started\n\n";

    for (int i = 1; i < argc; ++i)
    {
      input.push_back(argv[i]);
    }

    for (auto fileName: input)
    {
      try
      {
        ifstream Input(fileName.c_str());

        if (!Input)
        {
          cerr << "- ERROR:  can not open file " << fileName << "\n\n";
          exit(EXIT_FAILURE);
        }

        cout << "---- Sudoku file: " << fileName << "\n\n";

        SudokuGrid sdkg;
        vector<SudokuGrid> solutions;

        Input >> sdkg;
        writeCandidates(cout, sdkg);
        getchar();
        SudokuSolver sdkSolver(sdkg, 1);

        auto t1 = chrono::system_clock::now();
        solutions = sdkSolver.solve();
        chrono::duration<double> d = chrono::system_clock::now() - t1;
        cout << "---- Processing time: " << fixed << setprecision(4)
             << d.count() << " sec" << endl << endl;
        cout << "---- Sudoku solution(s), " << solutions.size()
             << " found:\n\n";
        for (auto solution: solutions)
        {
          cout << solution << endl;
        }
        cout << "- Sudoku solver, solved puzzle: " << fileName << endl << endl;
      }
      catch(const exception& e)
      {
        clog << "- EXCEPTION: " << argv[0] << " " << e.what() << endl;
      }
      catch(...)
      {
        clog << "- UNKNOWN EXCEPTION " << argv[0] << endl;
      }
    }
  }
  else
  {
    cout << "- USAGE: " << argv[0] << " <Sudoku files>" << endl;
  }

  return 0;
}

//--------------------------------------------------------------- eof Sudoku.cpp
<commit_msg>Shows number of clues<commit_after>//------------------------------------------------------------------- Sudoku.cpp

#include "AppInfo.h"
#include "SudokuSolver.h"

#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

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

int main(int argc, char *argv[])
{
  vector<string> input;

  if (argc > 1)
  {
    cout << "- " << APPNAME_VERSION << " started\n\n";

    for (int i = 1; i < argc; ++i)
    {
      input.push_back(argv[i]);
    }

    for (auto fileName: input)
    {
      try
      {
        ifstream Input(fileName.c_str());

        if (!Input)
        {
          cerr << "- ERROR:  can not open file " << fileName << "\n\n";
          exit(EXIT_FAILURE);
        }

        cout << "---- Sudoku file: " << fileName << "\n\n";

        SudokuGrid sdkg;
        vector<SudokuGrid> solutions;

        Input >> sdkg;
        cout << "- Number of clues: " << sdkg.getNumberOfCellsSolved() << endl;
        writeCandidates(cout, sdkg);
        getchar();
        SudokuSolver sdkSolver(sdkg, 1);

        auto t1 = chrono::system_clock::now();
        solutions = sdkSolver.solve();
        chrono::duration<double> d = chrono::system_clock::now() - t1;
        cout << "---- Processing time: " << fixed << setprecision(4)
             << d.count() << " sec" << endl << endl;
        cout << "---- Sudoku solution(s), " << solutions.size()
             << " found:\n\n";
        for (auto solution: solutions)
        {
          cout << solution << endl;
        }
        cout << "- Sudoku solver, solved puzzle: " << fileName << endl << endl;
      }
      catch(const exception& e)
      {
        clog << "- EXCEPTION: " << argv[0] << " " << e.what() << endl;
      }
      catch(...)
      {
        clog << "- UNKNOWN EXCEPTION " << argv[0] << endl;
      }
    }
  }
  else
  {
    cout << "- USAGE: " << argv[0] << " <Sudoku files>" << endl;
  }

  return 0;
}

//--------------------------------------------------------------- eof Sudoku.cpp
<|endoftext|>


<commit_before>#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP

#include "util/coordinate_calculation.hpp"

#include <boost/assert.hpp>

#include "osrm/coordinate.hpp"

#include <algorithm>
#include <cstdint>
#include <limits>

namespace osrm
{
namespace util
{

// TODO: Make template type, add tests
struct RectangleInt2D
{
    RectangleInt2D()
        : min_lon(std::numeric_limits<int32_t>::max()),
          max_lon(std::numeric_limits<int32_t>::min()),
          min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())
    {
    }

    RectangleInt2D(int32_t min_lon_, int32_t max_lon_, int32_t min_lat_, int32_t max_lat_)
        : min_lon(min_lon_), max_lon(max_lon_), min_lat(min_lat_), max_lat(max_lat_)
    {
    }

    int32_t min_lon, max_lon;
    int32_t min_lat, max_lat;

    void MergeBoundingBoxes(const RectangleInt2D &other)
    {
        min_lon = std::min(min_lon, other.min_lon);
        max_lon = std::max(max_lon, other.max_lon);
        min_lat = std::min(min_lat, other.min_lat);
        max_lat = std::max(max_lat, other.max_lat);
        BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
    }

    FixedPointCoordinate Centroid() const
    {
        FixedPointCoordinate centroid;
        // The coordinates of the midpoints are given by:
        // x = (x1 + x2) /2 and y = (y1 + y2) /2.
        centroid.lon = (min_lon + max_lon) / 2;
        centroid.lat = (min_lat + max_lat) / 2;
        return centroid;
    }

    bool Intersects(const RectangleInt2D &other) const
    {
        // Standard box intersection test - check if boxes *don't* overlap,
        // and return the negative of that
        return !(max_lon < other.min_lon || min_lon > other.max_lon || max_lat < other.min_lat ||
                 min_lat > other.max_lat);
    }

    double GetMinDist(const FixedPointCoordinate location) const
    {
        const bool is_contained = Contains(location);
        if (is_contained)
        {
            return 0.0f;
        }

        enum Direction
        {
            INVALID = 0,
            NORTH = 1,
            SOUTH = 2,
            EAST = 4,
            NORTH_EAST = 5,
            SOUTH_EAST = 6,
            WEST = 8,
            NORTH_WEST = 9,
            SOUTH_WEST = 10
        };

        Direction d = INVALID;
        if (location.lat > max_lat)
            d = (Direction)(d | NORTH);
        else if (location.lat < min_lat)
            d = (Direction)(d | SOUTH);
        if (location.lon > max_lon)
            d = (Direction)(d | EAST);
        else if (location.lon < min_lon)
            d = (Direction)(d | WEST);

        BOOST_ASSERT(d != INVALID);

        double min_dist = std::numeric_limits<double>::max();
        switch (d)
        {
        case NORTH:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(max_lat, location.lon));
            break;
        case SOUTH:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(min_lat, location.lon));
            break;
        case WEST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(location.lat, min_lon));
            break;
        case EAST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(location.lat, max_lon));
            break;
        case NORTH_EAST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(max_lat, max_lon));
            break;
        case NORTH_WEST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(max_lat, min_lon));
            break;
        case SOUTH_EAST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(min_lat, max_lon));
            break;
        case SOUTH_WEST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(min_lat, min_lon));
            break;
        default:
            break;
        }

        BOOST_ASSERT(min_dist < std::numeric_limits<double>::max());

        return min_dist;
    }

    double GetMinMaxDist(const FixedPointCoordinate location) const
    {
        double min_max_dist = std::numeric_limits<double>::max();
        // Get minmax distance to each of the four sides
        const FixedPointCoordinate upper_left(max_lat, min_lon);
        const FixedPointCoordinate upper_right(max_lat, max_lon);
        const FixedPointCoordinate lower_right(min_lat, max_lon);
        const FixedPointCoordinate lower_left(min_lat, min_lon);

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, upper_left),
                              coordinate_calculation::greatCircleDistance(location, upper_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, upper_right),
                              coordinate_calculation::greatCircleDistance(location, lower_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, lower_right),
                              coordinate_calculation::greatCircleDistance(location, lower_left)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, lower_left),
                              coordinate_calculation::greatCircleDistance(location, upper_left)));
        return min_max_dist;
    }

    bool Contains(const FixedPointCoordinate location) const
    {
        const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
        const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
        return lats_contained && lons_contained;
    }
};
}
}

#endif
<commit_msg>Fixes rectangle header includes<commit_after>#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP

#include "util/coordinate_calculation.hpp"

#include <boost/assert.hpp>

#include "osrm/coordinate.hpp"

#include <algorithm>
#include <utility>
#include <limits>

#include <cstdint>

namespace osrm
{
namespace util
{

// TODO: Make template type, add tests
struct RectangleInt2D
{
    RectangleInt2D()
        : min_lon(std::numeric_limits<int32_t>::max()),
          max_lon(std::numeric_limits<int32_t>::min()),
          min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())
    {
    }

    RectangleInt2D(int32_t min_lon_, int32_t max_lon_, int32_t min_lat_, int32_t max_lat_)
        : min_lon(min_lon_), max_lon(max_lon_), min_lat(min_lat_), max_lat(max_lat_)
    {
    }

    int32_t min_lon, max_lon;
    int32_t min_lat, max_lat;

    void MergeBoundingBoxes(const RectangleInt2D &other)
    {
        min_lon = std::min(min_lon, other.min_lon);
        max_lon = std::max(max_lon, other.max_lon);
        min_lat = std::min(min_lat, other.min_lat);
        max_lat = std::max(max_lat, other.max_lat);
        BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
        BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
    }

    FixedPointCoordinate Centroid() const
    {
        FixedPointCoordinate centroid;
        // The coordinates of the midpoints are given by:
        // x = (x1 + x2) /2 and y = (y1 + y2) /2.
        centroid.lon = (min_lon + max_lon) / 2;
        centroid.lat = (min_lat + max_lat) / 2;
        return centroid;
    }

    bool Intersects(const RectangleInt2D &other) const
    {
        // Standard box intersection test - check if boxes *don't* overlap,
        // and return the negative of that
        return !(max_lon < other.min_lon || min_lon > other.max_lon || max_lat < other.min_lat ||
                 min_lat > other.max_lat);
    }

    double GetMinDist(const FixedPointCoordinate location) const
    {
        const bool is_contained = Contains(location);
        if (is_contained)
        {
            return 0.0f;
        }

        enum Direction
        {
            INVALID = 0,
            NORTH = 1,
            SOUTH = 2,
            EAST = 4,
            NORTH_EAST = 5,
            SOUTH_EAST = 6,
            WEST = 8,
            NORTH_WEST = 9,
            SOUTH_WEST = 10
        };

        Direction d = INVALID;
        if (location.lat > max_lat)
            d = (Direction)(d | NORTH);
        else if (location.lat < min_lat)
            d = (Direction)(d | SOUTH);
        if (location.lon > max_lon)
            d = (Direction)(d | EAST);
        else if (location.lon < min_lon)
            d = (Direction)(d | WEST);

        BOOST_ASSERT(d != INVALID);

        double min_dist = std::numeric_limits<double>::max();
        switch (d)
        {
        case NORTH:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(max_lat, location.lon));
            break;
        case SOUTH:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(min_lat, location.lon));
            break;
        case WEST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(location.lat, min_lon));
            break;
        case EAST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(location.lat, max_lon));
            break;
        case NORTH_EAST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(max_lat, max_lon));
            break;
        case NORTH_WEST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(max_lat, min_lon));
            break;
        case SOUTH_EAST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(min_lat, max_lon));
            break;
        case SOUTH_WEST:
            min_dist = coordinate_calculation::greatCircleDistance(
                location, FixedPointCoordinate(min_lat, min_lon));
            break;
        default:
            break;
        }

        BOOST_ASSERT(min_dist < std::numeric_limits<double>::max());

        return min_dist;
    }

    double GetMinMaxDist(const FixedPointCoordinate location) const
    {
        double min_max_dist = std::numeric_limits<double>::max();
        // Get minmax distance to each of the four sides
        const FixedPointCoordinate upper_left(max_lat, min_lon);
        const FixedPointCoordinate upper_right(max_lat, max_lon);
        const FixedPointCoordinate lower_right(min_lat, max_lon);
        const FixedPointCoordinate lower_left(min_lat, min_lon);

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, upper_left),
                              coordinate_calculation::greatCircleDistance(location, upper_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, upper_right),
                              coordinate_calculation::greatCircleDistance(location, lower_right)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, lower_right),
                              coordinate_calculation::greatCircleDistance(location, lower_left)));

        min_max_dist =
            std::min(min_max_dist,
                     std::max(coordinate_calculation::greatCircleDistance(location, lower_left),
                              coordinate_calculation::greatCircleDistance(location, upper_left)));
        return min_max_dist;
    }

    bool Contains(const FixedPointCoordinate location) const
    {
        const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
        const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
        return lats_contained && lons_contained;
    }
};
}
}

#endif
<|endoftext|>


<commit_before>/// @file   variableTracer.hpp
/// @author Enrico Fraccaroli
/// @date   Jul 20, 2016
/// @copyright
/// Copyright (c) 2016,2017,2018 Enrico Fraccaroli <enrico.fraccaroli@gmail.com>
/// Permission to use, copy, modify, and distribute this software for any
/// purpose with or without fee is hereby granted, provided that the above
/// copyright notice and this permission notice appear in all copies.
///
/// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
/// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
/// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
/// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
/// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
/// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
/// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#pragma once

#include "genericTrace.hpp"
#include "timeScale.hpp"

#include <vector>
#include <fstream> // std::ofstream
#include <iomanip> // std::setprecision
#include <set>
#include <string>
#include <random>
#include <cassert>

#define VARIABLE_TRACER_MAJOR 3
#define VARIABLE_TRACER_MINOR 0
#define VARIABLE_TRACER_PATCH 0

/// @brief C++ variable tracer.
class VariableTracer
{
private:
    typedef struct scope_t
    {
        std::string name;
        std::vector<GenericTrace *> traceList;
        std::vector<scope_t> subscopes;
        scope_t * parentScope;

        /// @brief Constructor.
        scope_t(std::string const & _name) :
            name(_name),
            traceList(),
            subscopes(),
            parentScope()
        {
            // Nothing to do.
        }

        inline void printScope(std::ofstream & stream) const
        {
            stream << "$scope module " << name << " $end\n";
            for (auto const & trace : traceList)
            {
                stream << "    " << trace->getVar();
            }
            for (auto const & subscope : subscopes)
            {
                subscope.printScope(stream);
            }
            stream << "$upscope $end\n";
        }

        inline void deleteTraces()
        {
            for (auto trace : traceList)
                delete (trace);
            for (auto & subscope : subscopes)
                subscope.deleteTraces();
        }
    } scope_t;

    /// Name of the trace file.
    std::string filename;
    /// The output file.
    std::ofstream outfile;
    /// The root of the scopes.
    scope_t scopeRoot;
    /// Pointer to the current scope.
    scope_t * current_scope;
    /// The timescale.
    TimeScale timescale;
    /// The timescale.
    TimeScale sampling;
    /// Identifies the first dump of the values.
    bool firstDump;
    /// Next sampling time.
    double next_sample;

public:
    /// @brief Constructor.
    /// @param _filename The name of the file.
    /// @param _timescale The timescale to use.
    VariableTracer(std::string const & _filename,
                   TimeScale const & _timescale) :
        filename(_filename),
        outfile(_filename),
        scopeRoot("CPP"),
        current_scope(&scopeRoot),
        timescale(_timescale),
        sampling(_timescale),
        firstDump(true),
        next_sample()
    {
        scopeRoot.parentScope = &scopeRoot;
    }

    /// @brief Destructor.
    ~VariableTracer()
    {
        // Delete the traces.
        scopeRoot.deleteTraces();
        // Close the output file.
        this->closeTrace();
    }

    inline void setSampling(TimeScale const & _sampling)
    {
        sampling = _sampling;
    }

    /// @brief Creates the trace.
    void createTrace()
    {
        // Write the header.
        outfile << "$date\n";
        outfile << "    " + this->getDateTime() + "\n";
        outfile << "$end\n";
        outfile << "$version\n";
        outfile << "    VariableTracer "
                << VARIABLE_TRACER_MAJOR << "."
                << VARIABLE_TRACER_MINOR << "."
                << VARIABLE_TRACER_PATCH
                << " - By Galfurian --- Mar 30, 2016\n";
        outfile << "$end\n";
        outfile << "$timescale\n";
        outfile <<
                "    " + std::to_string(static_cast<int>(timescale.getBase()));
        outfile << timescale.getMagnitudeString() + "\n";
        outfile << "$end\n";

        scopeRoot.printScope(outfile);

        outfile << "$enddefinitions $end\n";
    }

    void addScope(std::string const & scopeName)
    {
        assert(current_scope && "There is no current scope.");
        assert(current_scope->parentScope && "Current scope has no parent.");
        auto parentScope = current_scope->parentScope;
        parentScope->subscopes.emplace_back(scope_t(scopeName));
        parentScope->subscopes.back().parentScope = parentScope;
        current_scope = &parentScope->subscopes.back();
    }

    void addSubScope(std::string const & scopeName)
    {
        assert(current_scope && "There is no current scope.");
        current_scope->subscopes.emplace_back(scope_t(scopeName));
        current_scope->subscopes.back().parentScope = current_scope;
        current_scope = &current_scope->subscopes.back();
    }

    inline void closeScope()
    {
        assert(current_scope && "There is no current scope.");
        assert(current_scope->parentScope && "Current scope has no parent.");
        current_scope = current_scope->parentScope;
    }

    /// @brief Add a variable to the list of traces.
    /// @param name     The name of the trace.
    /// @param variable The variable which has to be traced.
    template<typename T>
    void addTrace(T & variable, const std::string & name)
    {
        assert(current_scope && "There is no current scope.");
        current_scope->traceList.push_back(
            new GenericTraceWrapper<T>(
                name, VariableTracer::getUniqueName(), &variable));
    }

    /// @brief Updates the trace file with the current variable values.
    /// @param t The time at which the traces have been updated.
    void updateTrace(const double & t)
    {
        // --------------------------------------------------------------------
        // TIME
        // --------------------------------------------------------------------
        if (firstDump) outfile << "$dumpvars\n";
        else if (!this->changed()) return;
        else if (next_sample > t) return;
        else outfile << '#' << get_time<uint64_t>(t) << "\n";
        // --------------------------------------------------------------------
        // VALUES
        // --------------------------------------------------------------------
        this->updateTraceRecursive(scopeRoot);
        // --------------------------------------------------------------------
        // END
        // --------------------------------------------------------------------
        if (firstDump)
        {
            outfile << "$end\n";
            firstDump = false;
        }
        next_sample += sampling.getValue();
    }

    /// @brief Checks if some value has changed.
    inline bool changed() const
    {
        return this->changedRecursive(scopeRoot);
    }

    /// @brief Closes the trace file.
    inline void closeTrace()
    {
        if (outfile.is_open()) outfile.close();
    }

private:
    template<typename T>
    inline T get_time(long double const & t) const
    {
        return static_cast<T>(t / timescale.getMagnitude());
    }

    /// @brief Provides the current date.
    std::string getDateTime()
    {
        time_t rawtime;
        struct tm * timeinfo;
        char buffer[80];

        time(&rawtime);
        timeinfo = localtime(&rawtime);

        strftime(buffer, 80, "%b %d, %Y %I:%M:%S", timeinfo);
        std::string str(buffer);
        return str;
    }

    /// @brief Allows to generate a unique name.
    /// @return The generated name.
    static inline std::string getUniqueName()
    {
        static const size_t characters = 27;
        // Define the usable character.
        static const char alphanum[characters] = "abcdefghijklmnopqrstuvwxyz";
        /// Lenght of the name.
        static size_t length = 3;
        /// Set of already used symbols.
        static std::set<std::string> usedSymbols;
        /// Will be used to obtain a seed for the random number engine
        static std::random_device rd;
        /// Standard mersenne_twister_engine seeded with rd().
        static std::mt19937 gen(rd());
        // Create an uniform distribution.
        static std::uniform_int_distribution<int> dis(0, characters - 1);
        // Establish a new seed.
        std::string symbol;
        do
        {
            symbol.clear();
            for (unsigned int it = 0; it < length; ++it)
            {
                symbol += alphanum[dis(gen) % (sizeof(alphanum) - 1)];
            }
        } while (!usedSymbols.insert(symbol).second);
        return symbol;
    }

    inline void updateTraceRecursive(scope_t & scope)
    {
        for (auto const & trace : scope.traceList)
        {
            if (trace->hasChanged() || firstDump)
            {
                // Print the trace.
                outfile << trace->getValue();
                // Update previous value.
                trace->updatePrevious();
            }
        }
        for (auto & subscope : scope.subscopes)
        {
            this->updateTraceRecursive(subscope);
        }
    }

    inline bool changedRecursive(scope_t const & scope) const
    {
        for (auto const & trace : scope.traceList)
        {
            if (trace->hasChanged()) return true;
        }
        for (auto & subscope : scope.subscopes)
        {
            if (this->changedRecursive(subscope)) return true;
        }
        return false;
    }
};
<commit_msg>Update major version<commit_after>/// @file   variableTracer.hpp
/// @author Enrico Fraccaroli
/// @date   Jul 20, 2016
/// @copyright
/// Copyright (c) 2016,2017,2018 Enrico Fraccaroli <enrico.fraccaroli@gmail.com>
/// Permission to use, copy, modify, and distribute this software for any
/// purpose with or without fee is hereby granted, provided that the above
/// copyright notice and this permission notice appear in all copies.
///
/// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
/// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
/// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
/// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
/// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
/// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
/// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#pragma once

#include "genericTrace.hpp"
#include "timeScale.hpp"

#include <vector>
#include <fstream> // std::ofstream
#include <iomanip> // std::setprecision
#include <set>
#include <string>
#include <random>
#include <cassert>

#define VARIABLE_TRACER_MAJOR 2
#define VARIABLE_TRACER_MINOR 0
#define VARIABLE_TRACER_PATCH 0

/// @brief C++ variable tracer.
class VariableTracer
{
private:
    typedef struct scope_t
    {
        std::string name;
        std::vector<GenericTrace *> traceList;
        std::vector<scope_t> subscopes;
        scope_t * parentScope;

        /// @brief Constructor.
        scope_t(std::string const & _name) :
            name(_name),
            traceList(),
            subscopes(),
            parentScope()
        {
            // Nothing to do.
        }

        inline void printScope(std::ofstream & stream) const
        {
            stream << "$scope module " << name << " $end\n";
            for (auto const & trace : traceList)
            {
                stream << "    " << trace->getVar();
            }
            for (auto const & subscope : subscopes)
            {
                subscope.printScope(stream);
            }
            stream << "$upscope $end\n";
        }

        inline void deleteTraces()
        {
            for (auto trace : traceList)
                delete (trace);
            for (auto & subscope : subscopes)
                subscope.deleteTraces();
        }
    } scope_t;

    /// Name of the trace file.
    std::string filename;
    /// The output file.
    std::ofstream outfile;
    /// The root of the scopes.
    scope_t scopeRoot;
    /// Pointer to the current scope.
    scope_t * current_scope;
    /// The timescale.
    TimeScale timescale;
    /// The timescale.
    TimeScale sampling;
    /// Identifies the first dump of the values.
    bool firstDump;
    /// Next sampling time.
    double next_sample;

public:
    /// @brief Constructor.
    /// @param _filename The name of the file.
    /// @param _timescale The timescale to use.
    VariableTracer(std::string const & _filename,
                   TimeScale const & _timescale) :
        filename(_filename),
        outfile(_filename),
        scopeRoot("CPP"),
        current_scope(&scopeRoot),
        timescale(_timescale),
        sampling(_timescale),
        firstDump(true),
        next_sample()
    {
        scopeRoot.parentScope = &scopeRoot;
    }

    /// @brief Destructor.
    ~VariableTracer()
    {
        // Delete the traces.
        scopeRoot.deleteTraces();
        // Close the output file.
        this->closeTrace();
    }

    inline void setSampling(TimeScale const & _sampling)
    {
        sampling = _sampling;
    }

    /// @brief Creates the trace.
    void createTrace()
    {
        // Write the header.
        outfile << "$date\n";
        outfile << "    " + this->getDateTime() + "\n";
        outfile << "$end\n";
        outfile << "$version\n";
        outfile << "    VariableTracer "
                << VARIABLE_TRACER_MAJOR << "."
                << VARIABLE_TRACER_MINOR << "."
                << VARIABLE_TRACER_PATCH
                << " - By Galfurian --- Mar 30, 2016\n";
        outfile << "$end\n";
        outfile << "$timescale\n";
        outfile <<
                "    " + std::to_string(static_cast<int>(timescale.getBase()));
        outfile << timescale.getMagnitudeString() + "\n";
        outfile << "$end\n";

        scopeRoot.printScope(outfile);

        outfile << "$enddefinitions $end\n";
    }

    void addScope(std::string const & scopeName)
    {
        assert(current_scope && "There is no current scope.");
        assert(current_scope->parentScope && "Current scope has no parent.");
        auto parentScope = current_scope->parentScope;
        parentScope->subscopes.emplace_back(scope_t(scopeName));
        parentScope->subscopes.back().parentScope = parentScope;
        current_scope = &parentScope->subscopes.back();
    }

    void addSubScope(std::string const & scopeName)
    {
        assert(current_scope && "There is no current scope.");
        current_scope->subscopes.emplace_back(scope_t(scopeName));
        current_scope->subscopes.back().parentScope = current_scope;
        current_scope = &current_scope->subscopes.back();
    }

    inline void closeScope()
    {
        assert(current_scope && "There is no current scope.");
        assert(current_scope->parentScope && "Current scope has no parent.");
        current_scope = current_scope->parentScope;
    }

    /// @brief Add a variable to the list of traces.
    /// @param name     The name of the trace.
    /// @param variable The variable which has to be traced.
    template<typename T>
    void addTrace(T & variable, const std::string & name)
    {
        assert(current_scope && "There is no current scope.");
        current_scope->traceList.push_back(
            new GenericTraceWrapper<T>(
                name, VariableTracer::getUniqueName(), &variable));
    }

    /// @brief Updates the trace file with the current variable values.
    /// @param t The time at which the traces have been updated.
    void updateTrace(const double & t)
    {
        // --------------------------------------------------------------------
        // TIME
        // --------------------------------------------------------------------
        if (firstDump) outfile << "$dumpvars\n";
        else if (!this->changed()) return;
        else if (next_sample > t) return;
        else outfile << '#' << get_time<uint64_t>(t) << "\n";
        // --------------------------------------------------------------------
        // VALUES
        // --------------------------------------------------------------------
        this->updateTraceRecursive(scopeRoot);
        // --------------------------------------------------------------------
        // END
        // --------------------------------------------------------------------
        if (firstDump)
        {
            outfile << "$end\n";
            firstDump = false;
        }
        next_sample += sampling.getValue();
    }

    /// @brief Checks if some value has changed.
    inline bool changed() const
    {
        return this->changedRecursive(scopeRoot);
    }

    /// @brief Closes the trace file.
    inline void closeTrace()
    {
        if (outfile.is_open()) outfile.close();
    }

private:
    template<typename T>
    inline T get_time(long double const & t) const
    {
        return static_cast<T>(t / timescale.getMagnitude());
    }

    /// @brief Provides the current date.
    std::string getDateTime()
    {
        time_t rawtime;
        struct tm * timeinfo;
        char buffer[80];

        time(&rawtime);
        timeinfo = localtime(&rawtime);

        strftime(buffer, 80, "%b %d, %Y %I:%M:%S", timeinfo);
        std::string str(buffer);
        return str;
    }

    /// @brief Allows to generate a unique name.
    /// @return The generated name.
    static inline std::string getUniqueName()
    {
        static const size_t characters = 27;
        // Define the usable character.
        static const char alphanum[characters] = "abcdefghijklmnopqrstuvwxyz";
        /// Lenght of the name.
        static size_t length = 3;
        /// Set of already used symbols.
        static std::set<std::string> usedSymbols;
        /// Will be used to obtain a seed for the random number engine
        static std::random_device rd;
        /// Standard mersenne_twister_engine seeded with rd().
        static std::mt19937 gen(rd());
        // Create an uniform distribution.
        static std::uniform_int_distribution<int> dis(0, characters - 1);
        // Establish a new seed.
        std::string symbol;
        do
        {
            symbol.clear();
            for (unsigned int it = 0; it < length; ++it)
            {
                symbol += alphanum[dis(gen) % (sizeof(alphanum) - 1)];
            }
        } while (!usedSymbols.insert(symbol).second);
        return symbol;
    }

    inline void updateTraceRecursive(scope_t & scope)
    {
        for (auto const & trace : scope.traceList)
        {
            if (trace->hasChanged() || firstDump)
            {
                // Print the trace.
                outfile << trace->getValue();
                // Update previous value.
                trace->updatePrevious();
            }
        }
        for (auto & subscope : scope.subscopes)
        {
            this->updateTraceRecursive(subscope);
        }
    }

    inline bool changedRecursive(scope_t const & scope) const
    {
        for (auto const & trace : scope.traceList)
        {
            if (trace->hasChanged()) return true;
        }
        for (auto & subscope : scope.subscopes)
        {
            if (this->changedRecursive(subscope)) return true;
        }
        return false;
    }
};
<|endoftext|>


<commit_before>//============================================================================
// include/vsmc/rng/m128i.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distributed under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_RNG_M128I_HPP
#define VSMC_RNG_M128I_HPP

#include <vsmc/rng/internal/common.hpp>

#ifdef VSMC_MSVC
#include <intrin.h>
#else
#include <emmintrin.h>
#endif

#define VSMC_STATIC_ASSERT_RNG_M128I_PACK(Offset, T, N) \
    VSMC_STATIC_ASSERT(                                                      \
            ((Offset < N) && (sizeof(T) * (N - Offset) >= sizeof(__m128i))), \
            TRY_TO_PACK_OR_UNPACK_A_TOO_SMALL_VECTOR_INTO_OR_FROM_m128i)

namespace vsmc {

/// \brief Aligned pack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_pack_a (const Array<T, N> &c, __m128i &m)
{m = _mm_load_si128(reinterpret_cast<const __m128i *>(c.data() + Offset));}

/// \brief Unaligned pack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_pack_u (const Array<T, N> &c, __m128i &m)
{m = _mm_loadu_si128(reinterpret_cast<const __m128i *>(c.data() + Offset));}

/// \brief Aligned unpack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_unpack_a (const __m128i &m, Array<T, N> &c)
{_mm_store_si128(reinterpret_cast<__m128i *>(c.data() + Offset), m);}

/// \brief Unaligned unpack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_unpack_u (const __m128i &m, Array<T, N> &c)
{_mm_storeu_si128(reinterpret_cast<__m128i *>(c.data() + Offset), m);}

/// \brief Pack an Array into an __m128i object
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_pack (const Array<T, N> &c, __m128i &m)
{
    VSMC_STATIC_ASSERT_RNG_M128I_PACK(Offset, T, N);
    m128i_pack_u<Offset>(c, m);
}

/// \brief Unpack an __m128i object into an Array
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_unpack (const __m128i &m, Array<T, N> &c)
{
    VSMC_STATIC_ASSERT_RNG_M128I_PACK(Offset, T, N);
    m128i_unpack_u<Offset>(m, c);
}

/// \brief Compare two __m128i objects
/// \ingroup RNG
VSMC_STRONG_INLINE bool m128i_is_equal (const __m128i &a, const __m128i &b)
{
    Array<uint64_t, 2> sa;
    Array<uint64_t, 2> sb;
    m128i_unpack<0>(a, sa);
    m128i_unpack<0>(b, sb);

    return sa == sb;
}

/// \brief Write an __m128i object into an output stream as 16 bytes
/// unsigned integers
/// \ingroup RNG
template <typename CharT, typename Traits>
VSMC_STRONG_INLINE std::basic_ostream<CharT, Traits> &m128i_output (
        std::basic_ostream<CharT, Traits> &os, const __m128i &a)
{
    if (os.good()) {
        Array<unsigned char, 16> sa;
        m128i_unpack<0>(a, sa);
        os << sa;
    }

    return os;
}

/// \brief Input an __m128i object from an input stream as 16 bytes
/// unsigned integers written by m128i_output
/// \ingroup RNG
template <typename CharT, typename Traits>
VSMC_STRONG_INLINE std::basic_istream<CharT, Traits> &m128i_input (
        std::basic_istream<CharT, Traits> &is, __m128i &a)
{
    if (is.good()) {
        Array<unsigned char, 16> sa;
        is >> sa;
        if (is) m128i_pack<0>(sa, a);
    }

    return is;
}

} // namespace vsmc

#endif // VSMC_RNG_M128I_HPP
<commit_msg>io operators does not use strong inline<commit_after>//============================================================================
// include/vsmc/rng/m128i.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distributed under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_RNG_M128I_HPP
#define VSMC_RNG_M128I_HPP

#include <vsmc/rng/internal/common.hpp>

#ifdef VSMC_MSVC
#include <intrin.h>
#else
#include <emmintrin.h>
#endif

#define VSMC_STATIC_ASSERT_RNG_M128I_PACK(Offset, T, N) \
    VSMC_STATIC_ASSERT(                                                      \
            ((Offset < N) && (sizeof(T) * (N - Offset) >= sizeof(__m128i))), \
            TRY_TO_PACK_OR_UNPACK_A_TOO_SMALL_VECTOR_INTO_OR_FROM_m128i)

namespace vsmc {

/// \brief Aligned pack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_pack_a (const Array<T, N> &c, __m128i &m)
{m = _mm_load_si128(reinterpret_cast<const __m128i *>(c.data() + Offset));}

/// \brief Unaligned pack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_pack_u (const Array<T, N> &c, __m128i &m)
{m = _mm_loadu_si128(reinterpret_cast<const __m128i *>(c.data() + Offset));}

/// \brief Aligned unpack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_unpack_a (const __m128i &m, Array<T, N> &c)
{_mm_store_si128(reinterpret_cast<__m128i *>(c.data() + Offset), m);}

/// \brief Unaligned unpack
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_unpack_u (const __m128i &m, Array<T, N> &c)
{_mm_storeu_si128(reinterpret_cast<__m128i *>(c.data() + Offset), m);}

/// \brief Pack an Array into an __m128i object
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_pack (const Array<T, N> &c, __m128i &m)
{
    VSMC_STATIC_ASSERT_RNG_M128I_PACK(Offset, T, N);
    m128i_pack_u<Offset>(c, m);
}

/// \brief Unpack an __m128i object into an Array
/// \ingroup RNG
template <std::size_t Offset, typename T, std::size_t N>
VSMC_STRONG_INLINE void m128i_unpack (const __m128i &m, Array<T, N> &c)
{
    VSMC_STATIC_ASSERT_RNG_M128I_PACK(Offset, T, N);
    m128i_unpack_u<Offset>(m, c);
}

/// \brief Compare two __m128i objects
/// \ingroup RNG
VSMC_STRONG_INLINE bool m128i_is_equal (const __m128i &a, const __m128i &b)
{
    Array<uint64_t, 2> sa;
    Array<uint64_t, 2> sb;
    m128i_unpack<0>(a, sa);
    m128i_unpack<0>(b, sb);

    return sa == sb;
}

/// \brief Write an __m128i object into an output stream as 16 bytes
/// unsigned integers
/// \ingroup RNG
template <typename CharT, typename Traits>
inline std::basic_ostream<CharT, Traits> &m128i_output (
        std::basic_ostream<CharT, Traits> &os, const __m128i &a)
{
    if (os.good()) {
        Array<unsigned char, 16> sa;
        m128i_unpack<0>(a, sa);
        os << sa;
    }

    return os;
}

/// \brief Input an __m128i object from an input stream as 16 bytes
/// unsigned integers written by m128i_output
/// \ingroup RNG
template <typename CharT, typename Traits>
inline std::basic_istream<CharT, Traits> &m128i_input (
        std::basic_istream<CharT, Traits> &is, __m128i &a)
{
    if (is.good()) {
        Array<unsigned char, 16> sa;
        is >> sa;
        if (is) m128i_pack<0>(sa, a);
    }

    return is;
}

} // namespace vsmc

#endif // VSMC_RNG_M128I_HPP
<|endoftext|>


<commit_before>#ifndef COFFEE_MILL_DCD_WRITER
#define COFFEE_MILL_DCD_WRITER
#include <cstring>
#include "DCDDef.hpp"

namespace coffeemill
{
    /*@brief > this class recieves data of trajectory(array of snapshot) and *
     *         output the data to dcd file. you can set all trajectory data  *
     *         and also write each snapshot step by step.                    *
     *         Use set_data     & write_file     for all-trajectory output   *
     *             write_header & write_SnapShot for step by step output     */
    class DCDWriter
    {
        public:
            using iterator = std::vector<SnapShot>::iterator;
            using const_iterator = std::vector<SnapShot>::const_iterator;

        public:

            DCDWriter()
                : header_written(false)
            {
                ;
            }

            DCDWriter(const std::string& filename_)
                : header_written(false), filename(filename_)
            {
                ;
            }

            ~DCDWriter() = default;

            void write_file();
            void write_file(const std::string& filename);

            void write_header();
            void write_SnapShot(const SnapShot& snapshot);

            void set_nset       (const int nset_)   {nset = nset_;}
            void set_istart     (const int istart_) {istart = istart_;}
            void set_nstep_save (const int nsave_)  {nstep_save = nsave_;}
            void set_nstep      (const int nstep_)  {nstep = nstep_;}
            void set_nunit      (const int nunit_)  {nunit = nunit_;}
            void set_npart      (const int npart_)  {nparticle = npart_;}
            void set_delta_t    (const double dt)   {delta_t = dt;}
            void set_header     (const std::vector<std::string>& h);

            SnapShot& at(const std::size_t i)       {return data.at(i);}
            SnapShot  at(const std::size_t i) const {return data.at(i);}

            void set_all_data(const std::vector<SnapShot>& data_){data = data_;}

        private:

            // these private member asserts that file is open at any time.
            void write_core();
            void write_head_block1();
            void write_head_block2();
            void write_head_block3();
            void write_coord(const std::vector<double>& coord);

        private:

            bool header_written;// already write header
            int nset;           // number of frame
            int istart;         // initial value of isteps
            int nstep_save;     // saving frequency
            int nstep;          // total step number
            int nunit;          // total unit number
            int verCHARMM = 24; // have no meaning but write something
            int nparticle;      // total number of particle
            double delta_t;
            std::string filename;
            std::ofstream dcdfile;
            std::vector<std::string> header;
            std::vector<SnapShot> data;

        private:

            static constexpr int size_int = sizeof(int);
            static constexpr int size_float = sizeof(float);
            static constexpr int size_char = sizeof(char);
    };

    void DCDWriter::write_file(const std::string& filename_)
    {
        if(!filename.empty())
        {
            std::cerr << "Warning: you already specify filename in dcdwriter "
                      << filename << " but now you are trying to open "
                      << filename_ << std::endl;
        }

        filename = filename_;
        write_file();
        return;
    }

    void DCDWriter::write_file()
    {
        if(header_written)
            throw std::invalid_argument("file is partially written");

        write_header();
        write_core();

        std::cout << "Info   : write_file completed" << std::endl;
        return;
    }

    void DCDWriter::write_SnapShot(const SnapShot& snapshot)
    {
        if(filename.empty())
            throw std::invalid_argument("filename is not specified!");

        if(!header_written)
            throw std::invalid_argument("write DCD file without header");

        if(dcdfile.is_open())
        {
            throw std::invalid_argument("DCDWriter: file already open");
        }
        else
        {
            dcdfile.open(filename, std::ios::binary | std::ios::app);
            if(dcdfile.fail())
                throw std::invalid_argument("file open error: " + filename);
        }

        std::vector<double> x(snapshot.size());
        std::vector<double> y(snapshot.size());
        std::vector<double> z(snapshot.size());
        int counter(0);
        for(auto iter = (snapshot).cbegin(); iter != (snapshot).cend(); ++iter)
        {
            x[counter] = (*iter)[0];
            y[counter] = (*iter)[1];
            z[counter] = (*iter)[2];
            ++counter;
        }

        write_coord(x);
        write_coord(y);
        write_coord(z);

        dcdfile.close();

        return;
    }

    void DCDWriter::set_header(const std::vector<std::string>& h)
    {
        if(!header.empty())
            std::cout << "Warning: trying to set header but header is not empty"
                      << std::endl;

        for(auto iter = h.begin(); iter != h.end(); ++iter)
        {
            if((*iter).size() > 80)
            {
                throw std::invalid_argument("too long header line");
            }
            else if((*iter).size() < 80)
            {
                std::string filler((80 - (*iter).size()), '=');
                std::string temp = *iter + filler;
                if(temp.size() != 80)
                    throw std::length_error("header generate error");

                header.push_back(temp);
            }
            else
            {// just 80 chars
                header.push_back(*iter);
            }
        }
        return;
    }

    void DCDWriter::write_header()
    {
        dcdfile.open(filename, std::ios::binary);
        write_head_block1();
        write_head_block2();
        write_head_block3();
        dcdfile.close();
        header_written = true;
        return;
    }

    void DCDWriter::write_head_block1()
    {
        int wrote(0);
        int bytes(84);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);

        char cord[5] = "CORD";
        dcdfile.write(reinterpret_cast<char*>(&cord), size_char*4);
        wrote += size_char*4;

        dcdfile.write(reinterpret_cast<char*>(&nset), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&istart), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&nstep_save), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&nstep), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&nunit), size_int);
        wrote += size_int;

        // null data
        int fill_zero(0);
        for(int i(0); i<4; ++i)
        {
            dcdfile.write(reinterpret_cast<char*>(&fill_zero), size_int);
            wrote += size_int;
        }

        float dt(static_cast<float>(delta_t));
        dcdfile.write(reinterpret_cast<char*>(&dt), size_float);
        wrote += size_float;

        // null data
        for(int i(0); i<9; ++i)
        {
            dcdfile.write(reinterpret_cast<char*>(&fill_zero), size_int);
            wrote += size_int;
        }

//         verCHARMM = 24;
        dcdfile.write(reinterpret_cast<char*>(&verCHARMM), size_int);
        wrote += size_int;

        if(wrote != bytes)
        {
            throw std::invalid_argument("byte information error");
        }

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

    void DCDWriter::write_head_block2()
    {
        if(header.empty())
        {
            header.push_back("==================== Molecular Dynamics Code : CafeMol ver.  2.02 ==============");
            header.push_back("==================== Developed by Kyoto University =============================");
            header.push_back("==================== This file is modified using coffee-mill ===================");
        }

        int lines(header.size());
        int bytes(4 + 80*lines);
        int wrote(0);

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);

        dcdfile.write(reinterpret_cast<char*>(&lines), size_int);
        wrote += size_int;

        for(auto iter = header.begin(); iter != header.end(); ++iter)
        {
//             char* line = new char[81];
//             memcpy(line, iter->c_str(), 81);
            dcdfile << *iter;
//             dcdfile.write(reinterpret_cast<char*>(&line), size_char*80);
            wrote += size_char*80;
        }

        if(wrote != bytes)
            throw std::invalid_argument("internal byte information error");

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

    void DCDWriter::write_head_block3()
    {
        int bytes(size_int);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        dcdfile.write(reinterpret_cast<char*>(&nparticle), size_int);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

    void DCDWriter::write_core()
    {
        for(auto iter = data.cbegin(); iter != data.cend(); ++iter)
        {
            write_SnapShot(*iter);
        }
        return;
    }

    void DCDWriter::write_coord(const std::vector<double>& coord)
    {
        int size(coord.size());
        int bytes(size * size_float);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);

        for(auto iter = coord.cbegin(); iter != coord.cend(); ++iter)
        {
            float temp(static_cast<float>(*iter));
            dcdfile.write(reinterpret_cast<char*>(&temp), size_float);
        }

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

}//end namespace coffeemill

#endif //COFFEE_MILL_DCD_WRITER
<commit_msg>sort members in DCDWriter<commit_after>#ifndef COFFEE_MILL_DCD_WRITER
#define COFFEE_MILL_DCD_WRITER
#include <cstring>
#include "DCDDef.hpp"

namespace coffeemill
{
    /*@brief > this class recieves data of trajectory(array of snapshot) and *
     *         output the data to dcd file. you can set all trajectory data  *
     *         and also write each snapshot step by step.                    *
     *         Use set_data     & write_file     for all-trajectory output   *
     *             write_header & write_SnapShot for step by step output     */
    class DCDWriter
    {
        public:
            using iterator = std::vector<SnapShot>::iterator;
            using const_iterator = std::vector<SnapShot>::const_iterator;

        public:

            DCDWriter()
                : header_written(false)
            {
                ;
            }

            DCDWriter(const std::string& filename_)
                : header_written(false), filename(filename_)
            {
                ;
            }

            ~DCDWriter() = default;

            void write_file();
            void write_file(const std::string& filename);

            void write_header();
            void write_SnapShot(const SnapShot& snapshot);

            void set_nset       (const int nset_)   {nset = nset_;}
            void set_istart     (const int istart_) {istart = istart_;}
            void set_nstep_save (const int nsave_)  {nstep_save = nsave_;}
            void set_nstep      (const int nstep_)  {nstep = nstep_;}
            void set_nunit      (const int nunit_)  {nunit = nunit_;}
            void set_npart      (const int npart_)  {nparticle = npart_;}
            void set_delta_t    (const double dt)   {delta_t = dt;}
            void set_header     (const std::vector<std::string>& h);

            SnapShot& at(const std::size_t i)       {return data.at(i);}
            SnapShot  at(const std::size_t i) const {return data.at(i);}

            void set_all_data(const std::vector<SnapShot>& data_){data = data_;}

        private:

            // these private member asserts that file is open at any time.
            void write_core();
            void write_head_block1();
            void write_head_block2();
            void write_head_block3();
            void write_coord(const std::vector<double>& coord);

        private:

            bool header_written;// already write header
            int nset;           // number of frame
            int istart;         // initial value of isteps
            int nstep_save;     // saving frequency
            int nstep;          // total step number
            int nunit;          // total unit number
            int verCHARMM = 24; // have no meaning but write something
            int nparticle;      // total number of particle
            double delta_t;
            std::string filename;
            std::ofstream dcdfile;
            std::vector<std::string> header;
            std::vector<SnapShot> data;

        private:

            static constexpr int size_int   = sizeof(int);
            static constexpr int size_float = sizeof(float);
            static constexpr int size_char  = sizeof(char);
    };

    void DCDWriter::write_file(const std::string& filename_)
    {
        if(!filename.empty())
        {
            std::cerr << "Warning: you already specify filename in dcdwriter "
                      << filename << " but now you are trying to open "
                      << filename_ << std::endl;
        }

        filename = filename_;
        write_file();
        return;
    }

    void DCDWriter::write_file()
    {
        if(header_written)
            throw std::invalid_argument("file is partially written");

        write_header();
        write_core();

        std::cout << "Info   : write_file completed" << std::endl;
        return;
    }

    void DCDWriter::set_header(const std::vector<std::string>& h)
    {
        if(!header.empty())
            std::cout << "Warning: trying to set header but header is not empty"
                      << std::endl;

        for(auto iter = h.begin(); iter != h.end(); ++iter)
        {
            if((*iter).size() > 80)
            {
                throw std::invalid_argument("too long header line");
            }
            else if((*iter).size() < 80)
            {
                std::string filler((80 - (*iter).size()), '=');
                std::string temp = *iter + filler;
                if(temp.size() != 80)
                    throw std::length_error("header generate error");

                header.push_back(temp);
            }
            else
            {// just 80 chars
                header.push_back(*iter);
            }
        }
        return;
    }

    void DCDWriter::write_header()
    {
        dcdfile.open(filename, std::ios::binary);
        write_head_block1();
        write_head_block2();
        write_head_block3();
        dcdfile.close();
        header_written = true;
        return;
    }

    void DCDWriter::write_head_block1()
    {
        int wrote(0);
        int bytes(84);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);

        char cord[5] = "CORD";
        dcdfile.write(reinterpret_cast<char*>(&cord), size_char*4);
        wrote += size_char*4;

        dcdfile.write(reinterpret_cast<char*>(&nset), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&istart), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&nstep_save), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&nstep), size_int);
        wrote += size_int;

        dcdfile.write(reinterpret_cast<char*>(&nunit), size_int);
        wrote += size_int;

        // null data
        int fill_zero(0);
        for(int i(0); i<4; ++i)
        {
            dcdfile.write(reinterpret_cast<char*>(&fill_zero), size_int);
            wrote += size_int;
        }

        float dt(static_cast<float>(delta_t));
        dcdfile.write(reinterpret_cast<char*>(&dt), size_float);
        wrote += size_float;

        // null data
        for(int i(0); i<9; ++i)
        {
            dcdfile.write(reinterpret_cast<char*>(&fill_zero), size_int);
            wrote += size_int;
        }

        dcdfile.write(reinterpret_cast<char*>(&verCHARMM), size_int);
        wrote += size_int;

        if(wrote != bytes)
        {
            throw std::invalid_argument("byte information error");
        }

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

    void DCDWriter::write_head_block2()
    {
        if(header.empty())
        {
            header.push_back("==================== Molecular Dynamics Code : CafeMol ver.  2.02 ==============");
            header.push_back("==================== Developed by Kyoto University =============================");
            header.push_back("==================== This file is modified using coffee-mill ===================");
        }

        int lines(header.size());
        int bytes(4 + 80*lines);
        int wrote(0);

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);

        dcdfile.write(reinterpret_cast<char*>(&lines), size_int);
        wrote += size_int;

        for(auto iter = header.begin(); iter != header.end(); ++iter)
        {
//             char* line = new char[81];
//             memcpy(line, iter->c_str(), 81);
            dcdfile << *iter;
//             dcdfile.write(reinterpret_cast<char*>(&line), size_char*80);
            wrote += size_char*80;
        }

        if(wrote != bytes)
            throw std::invalid_argument("internal byte information error");

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

    void DCDWriter::write_head_block3()
    {
        int bytes(size_int);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        dcdfile.write(reinterpret_cast<char*>(&nparticle), size_int);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

    void DCDWriter::write_core()
    {
        for(auto iter = data.cbegin(); iter != data.cend(); ++iter)
        {
            write_SnapShot(*iter);
        }
        return;
    }

    void DCDWriter::write_SnapShot(const SnapShot& snapshot)
    {
        if(filename.empty())
            throw std::invalid_argument("filename is not specified!");

        if(!header_written)
            throw std::invalid_argument("write DCD file without header");

        if(dcdfile.is_open())
        {
            throw std::invalid_argument("DCDWriter: file already open");
        }
        else
        {
            dcdfile.open(filename, std::ios::binary | std::ios::app);
            if(dcdfile.fail())
                throw std::invalid_argument("file open error: " + filename);
        }

        std::vector<double> x(snapshot.size());
        std::vector<double> y(snapshot.size());
        std::vector<double> z(snapshot.size());
        int counter(0);
        for(auto iter = (snapshot).cbegin(); iter != (snapshot).cend(); ++iter)
        {
            x[counter] = (*iter)[0];
            y[counter] = (*iter)[1];
            z[counter] = (*iter)[2];
            ++counter;
        }

        write_coord(x);
        write_coord(y);
        write_coord(z);

        dcdfile.close();

        return;
    }

    void DCDWriter::write_coord(const std::vector<double>& coord)
    {
        int size(coord.size());
        int bytes(size * size_float);
        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);

        for(auto iter = coord.cbegin(); iter != coord.cend(); ++iter)
        {
            float temp(static_cast<float>(*iter));
            dcdfile.write(reinterpret_cast<char*>(&temp), size_float);
        }

        dcdfile.write(reinterpret_cast<char*>(&bytes), size_int);
        return;
    }

}//end namespace coffeemill

#endif //COFFEE_MILL_DCD_WRITER
<|endoftext|>