<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	ファイル操作ユーティリティー
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/sdc_man.hpp"
#include "common/fixed_stack.hpp"

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	ファイラー制御型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class filer_ctrl {
		OPEN,		///< ファイラーを起動
		UP,			///< スクロール上
		DOWN,		///< スクロール下
		BACK,		///< ディレクトリーを戻る
		SELECT,		///< 選択
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	制御データ構築
		@param[in]	pos		ファイラー制御型
		@param[in]	ctrl	制御データ（参照）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void set(filer_ctrl pos, uint32_t& ctrl) noexcept
	{
		ctrl |= 1 << static_cast<uint8_t>(pos);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	ファイラー
		@param[in]	SDC	sdc_man クラス型
		@param[in]	RDR	render クラス型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class SDC, class RDR>
	class filer {

		static const int16_t SPC = 2;                           ///< 文字間隙間
		static const int16_t FLN = RDR::font_height + SPC;      ///< 行幅
		static const int16_t SCN = (RDR::height - SPC) / FLN;   ///< 行数

		static const uint32_t PATH_MAX = 128;					///< パスの最大文字数

		SDC&	sdc_;
		RDR&	rdr_;

		uint32_t	ctrl_;
		bool		open_;

		struct rdr_st {
			RDR&		rdr_;
			int16_t		vofs_;
			int16_t		vpos_;
			int16_t		hmax_;
			int16_t		sel_pos_;
			uint16_t	num_;

			char		path_[PATH_MAX * SCN];

			rdr_st(RDR& rdr) noexcept : rdr_(rdr), vofs_(0), vpos_(0), hmax_(0), sel_pos_(0),
				num_(0), path_{ 0 }
			{ }
		};
		rdr_st	rdr_st_;

		struct pos_t {
			int16_t		vofs_;
			int16_t		sel_pos_;
			pos_t(int16_t vofs = 0, int16_t sel_pos = 0) noexcept :
				vofs_(vofs), sel_pos_(sel_pos) { }
		};
		typedef utils::fixed_stack<pos_t, 16> POS_STACK;
		POS_STACK		pos_stack_;

		static uint32_t ctrl_mask_(filer_ctrl ctrl) noexcept
		{
			return 1 << static_cast<uint8_t>(ctrl);
		}

		static void dir_draw_func_(const char* name, const FILINFO* fi, bool dir, void* opt)
			noexcept
		{
			rdr_st& t = *static_cast<rdr_st*>(opt);
			if(t.vpos_ >= 0 && t.vpos_ < RDR::height) {
				t.rdr_.set_fore_color(RDR::COLOR::White);
				t.rdr_.fill(SPC, t.vpos_, RDR::width - SPC * 2, RDR::font_height, 0x0000);
				if(dir) t.rdr_.draw_font(SPC, t.vpos_, '/');
			}
			if(dir) {
				t.rdr_.set_fore_color(RDR::COLOR::Blue);
			} else {
				t.rdr_.set_fore_color(RDR::COLOR::White);
			}
			auto w = t.rdr_.draw_text(SPC + 8, t.vpos_, name);
			if(t.hmax_ < w) t.hmax_ = w;
			uint32_t n = t.num_ + t.vofs_ / FLN;
			if(n < SCN) {
				strncpy(&t.path_[n * PATH_MAX], name, PATH_MAX);
				if(dir) {
					strncat(&t.path_[n * PATH_MAX], "/", PATH_MAX);
				}
			}
			t.vpos_ += FLN;
			++t.num_;
		}

		void start_dir_draw_() noexcept
		{
			uint32_t num = (RDR::height - 2) / (RDR::font_height + 2);
			rdr_st_.vpos_ = rdr_st_.vofs_ + 2;
			rdr_st_.num_ = 0;
			sdc_.start_dir_list("", dir_draw_func_, true, &rdr_st_);
		}

		void draw_sel_frame_(int16_t pos, uint16_t c)
		{
			int16_t h = RDR::font_height + 2;
			int16_t y = pos * h;
			rdr_.frame(0, y, rdr_st_.hmax_ + 3, h + 1, c);
		}

		void scan_dir_(bool back)
		{
			if(back) {
				if(pos_stack_.empty()) {
					rdr_st_.vofs_ = 0;
					rdr_st_.sel_pos_ = 0;
				} else {
					const auto& t = pos_stack_.pull();
					rdr_st_.vofs_ = t.vofs_;
					rdr_st_.sel_pos_ = t.sel_pos_;
				}
			} else {
				rdr_st_.vofs_ = 0;
				rdr_st_.sel_pos_ = 0;
			}
			start_dir_draw_();
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		filer(SDC& sdc, RDR& rdr) noexcept : sdc_(sdc), rdr_(rdr),
			ctrl_(0), open_(false),
			rdr_st_(rdr_)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	アップデート（毎フレーム呼ぶ）
			@param[in]	ctrl	ファイラー制御
			@return ファイルが選択された場合、ファイルパス
		*/
		//-----------------------------------------------------------------//
		const char* update(uint32_t ctrl) noexcept
		{
			uint32_t ptrg = ~ctrl_ &  ctrl;
			uint32_t ntrg =  ctrl_ & ~ctrl;
			ctrl_ = ctrl;

			if(!sdc_.get_mount()) {
				open_ = false;
				pos_stack_.clear();
				rdr_.clear(RDR::COLOR::Black);
				return nullptr;
			}

			if(ptrg & ctrl_mask_(filer_ctrl::OPEN)) {
				open_ = !open_;
				if(open_) {
					scan_dir_(false);
				} else {
					rdr_.clear(RDR::COLOR::Black);
				}
			}

			if(!open_) return nullptr;

			{
				uint32_t n;
				bool f = sdc_.probe_dir_list(n);
				if(f) return nullptr;
				if(rdr_st_.num_ < static_cast<int16_t>(n)) return nullptr;
			}

			// 選択フレームの描画
			draw_sel_frame_(rdr_st_.sel_pos_, 0xffff);
			int16_t pos = rdr_st_.sel_pos_;
			if(ptrg & ctrl_mask_(filer_ctrl::UP)) {
				pos--;
			}
			if(ptrg & ctrl_mask_(filer_ctrl::DOWN)) {
				++pos;
			}
			int16_t vofs = rdr_st_.vofs_;
			int16_t scn = SCN;
			if(rdr_st_.num_ < scn) scn = rdr_st_.num_;
			if(pos < 0) {
				pos = 0;
				vofs += FLN;
			} else if(pos >= scn) {
				pos = scn - 1;
				vofs -= FLN;
			}
			int16_t lim = 0;
			if(rdr_st_.num_ > scn) {
				lim = -(rdr_st_.num_ - scn) * FLN;
			}
			if(vofs > 0) {
				vofs = 0;
			} else if(vofs < lim) {
				vofs = lim;
			}
			if(vofs != rdr_st_.vofs_) {
				rdr_st_.vofs_ = vofs;
				start_dir_draw_();
			}

			if(pos != rdr_st_.sel_pos_) {
				draw_sel_frame_(rdr_st_.sel_pos_, 0x0000);
				rdr_st_.sel_pos_ = pos;
			}

			if(ptrg & ctrl_mask_(filer_ctrl::SELECT)) {
				char* p = &rdr_st_.path_[PATH_MAX * rdr_st_.sel_pos_];
				uint32_t l = strlen(p);
				if(p[l - 1] == '/') {
					pos_stack_.push(pos_t(rdr_st_.vofs_, rdr_st_.sel_pos_));
					p[l - 1] = 0;
					sdc_.cd(p);
					rdr_.clear(RDR::COLOR::Black);
					scan_dir_(false);
				} else {
					rdr_.clear(RDR::COLOR::Black);
					open_ = false;
					return static_cast<const char*>(p);
				}
			}

			if(ptrg & ctrl_mask_(filer_ctrl::BACK)) {
				if(!pos_stack_.empty()) {
					sdc_.cd("..");
					rdr_.clear(RDR::COLOR::Black);
					scan_dir_(true);
				}
			}

			return nullptr;
		}
	};
}
<commit_msg>update: file path length<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	ファイル操作ユーティリティー
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/sdc_man.hpp"
#include "common/fixed_stack.hpp"

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	ファイラー制御型
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class filer_ctrl {
		OPEN,		///< ファイラーを起動
		UP,			///< スクロール上
		DOWN,		///< スクロール下
		BACK,		///< ディレクトリーを戻る
		SELECT,		///< 選択
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	制御データ構築
		@param[in]	pos		ファイラー制御型
		@param[in]	ctrl	制御データ（参照）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void set(filer_ctrl pos, uint32_t& ctrl) noexcept
	{
		ctrl |= 1 << static_cast<uint8_t>(pos);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	ファイラー
		@param[in]	SDC	sdc_man クラス型
		@param[in]	RDR	render クラス型
		@param[in]	PTM	パス文字列最大数
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class SDC, class RDR, uint32_t PTM>
	class filer {

		static const int16_t SPC = 2;                           ///< 文字間隙間
		static const int16_t FLN = RDR::font_height + SPC;      ///< 行幅
		static const int16_t SCN = (RDR::height - SPC) / FLN;   ///< 行数

		static const uint32_t PATH_MAX = PTM;					///< パスの最大文字数

		SDC&	sdc_;
		RDR&	rdr_;

		uint32_t	ctrl_;
		bool		open_;

		struct rdr_st {
			RDR&		rdr_;
			int16_t		vofs_;
			int16_t		vpos_;
			int16_t		hmax_;
			int16_t		sel_pos_;
			uint16_t	num_;

			char		path_[PATH_MAX * SCN];

			rdr_st(RDR& rdr) noexcept : rdr_(rdr), vofs_(0), vpos_(0), hmax_(0), sel_pos_(0),
				num_(0), path_{ 0 }
			{ }
		};
		rdr_st	rdr_st_;

		struct pos_t {
			int16_t		vofs_;
			int16_t		sel_pos_;
			pos_t(int16_t vofs = 0, int16_t sel_pos = 0) noexcept :
				vofs_(vofs), sel_pos_(sel_pos) { }
		};
		typedef utils::fixed_stack<pos_t, 16> POS_STACK;
		POS_STACK		pos_stack_;

		static uint32_t ctrl_mask_(filer_ctrl ctrl) noexcept
		{
			return 1 << static_cast<uint8_t>(ctrl);
		}

		static void dir_draw_func_(const char* name, const FILINFO* fi, bool dir, void* opt)
			noexcept
		{
			rdr_st& t = *static_cast<rdr_st*>(opt);
			if(t.vpos_ >= 0 && t.vpos_ < RDR::height) {
				t.rdr_.set_fore_color(RDR::COLOR::White);
				t.rdr_.fill(SPC, t.vpos_, RDR::width - SPC * 2, RDR::font_height, 0x0000);
				if(dir) t.rdr_.draw_font(SPC, t.vpos_, '/');
			}
			if(dir) {
				t.rdr_.set_fore_color(RDR::COLOR::Blue);
			} else {
				t.rdr_.set_fore_color(RDR::COLOR::White);
			}
			auto w = t.rdr_.draw_text(SPC + 8, t.vpos_, name);
			if(t.hmax_ < w) t.hmax_ = w;
			uint32_t n = t.num_ + t.vofs_ / FLN;
			if(n < SCN) {
				strncpy(&t.path_[n * PATH_MAX], name, PATH_MAX);
				if(dir) {
					strncat(&t.path_[n * PATH_MAX], "/", PATH_MAX);
				}
			}
			t.vpos_ += FLN;
			++t.num_;
		}

		void start_dir_draw_() noexcept
		{
			uint32_t num = (RDR::height - 2) / (RDR::font_height + 2);
			rdr_st_.vpos_ = rdr_st_.vofs_ + 2;
			rdr_st_.num_ = 0;
			sdc_.start_dir_list("", dir_draw_func_, true, &rdr_st_);
		}

		void draw_sel_frame_(int16_t pos, uint16_t c)
		{
			int16_t h = RDR::font_height + 2;
			int16_t y = pos * h;
			rdr_.frame(0, y, rdr_st_.hmax_ + 3, h + 1, c);
		}

		void scan_dir_(bool back)
		{
			if(back) {
				if(pos_stack_.empty()) {
					rdr_st_.vofs_ = 0;
					rdr_st_.sel_pos_ = 0;
				} else {
					const auto& t = pos_stack_.pull();
					rdr_st_.vofs_ = t.vofs_;
					rdr_st_.sel_pos_ = t.sel_pos_;
				}
			} else {
				rdr_st_.vofs_ = 0;
				rdr_st_.sel_pos_ = 0;
			}
			start_dir_draw_();
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		filer(SDC& sdc, RDR& rdr) noexcept : sdc_(sdc), rdr_(rdr),
			ctrl_(0), open_(false),
			rdr_st_(rdr_)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	アップデート（毎フレーム呼ぶ）
			@param[in]	ctrl	ファイラー制御
			@return ファイルが選択された場合、ファイルパス
		*/
		//-----------------------------------------------------------------//
		const char* update(uint32_t ctrl) noexcept
		{
			uint32_t ptrg = ~ctrl_ &  ctrl;
			uint32_t ntrg =  ctrl_ & ~ctrl;
			ctrl_ = ctrl;

			if(!sdc_.get_mount()) {
				open_ = false;
				pos_stack_.clear();
				rdr_.clear(RDR::COLOR::Black);
				return nullptr;
			}

			if(ptrg & ctrl_mask_(filer_ctrl::OPEN)) {
				open_ = !open_;
				rdr_.clear(RDR::COLOR::Black);
				if(open_) {
					scan_dir_(false);
				}
			}

			if(!open_) return nullptr;

			{
				uint32_t n;
				bool f = sdc_.probe_dir_list(n);
				if(f) return nullptr;
				if(rdr_st_.num_ < static_cast<int16_t>(n)) return nullptr;
			}

			// 選択フレームの描画
			draw_sel_frame_(rdr_st_.sel_pos_, 0xffff);
			int16_t pos = rdr_st_.sel_pos_;
			if(ptrg & ctrl_mask_(filer_ctrl::UP)) {
				pos--;
			}
			if(ptrg & ctrl_mask_(filer_ctrl::DOWN)) {
				++pos;
			}
			int16_t vofs = rdr_st_.vofs_;
			int16_t scn = SCN;
			if(rdr_st_.num_ < scn) scn = rdr_st_.num_;
			if(pos < 0) {
				pos = 0;
				vofs += FLN;
			} else if(pos >= scn) {
				pos = scn - 1;
				vofs -= FLN;
			}
			int16_t lim = 0;
			if(rdr_st_.num_ > scn) {
				lim = -(rdr_st_.num_ - scn) * FLN;
			}
			if(vofs > 0) {
				vofs = 0;
			} else if(vofs < lim) {
				vofs = lim;
			}
			if(vofs != rdr_st_.vofs_) {
				rdr_st_.vofs_ = vofs;
				start_dir_draw_();
			}

			if(pos != rdr_st_.sel_pos_) {
				draw_sel_frame_(rdr_st_.sel_pos_, 0x0000);
				rdr_st_.sel_pos_ = pos;
			}

			if(ptrg & ctrl_mask_(filer_ctrl::SELECT)) {
				char* p = &rdr_st_.path_[PATH_MAX * rdr_st_.sel_pos_];
				uint32_t l = strlen(p);
				if(p[l - 1] == '/') {
					pos_stack_.push(pos_t(rdr_st_.vofs_, rdr_st_.sel_pos_));
					p[l - 1] = 0;
					sdc_.cd(p);
					rdr_.clear(RDR::COLOR::Black);
					scan_dir_(false);
				} else {
					rdr_.clear(RDR::COLOR::Black);
					open_ = false;
					return static_cast<const char*>(p);
				}
			}

			if(ptrg & ctrl_mask_(filer_ctrl::BACK)) {
				if(!pos_stack_.empty()) {
					sdc_.cd("..");
					rdr_.clear(RDR::COLOR::Black);
					scan_dir_(true);
				}
			}

			return nullptr;
		}
	};
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */
#include <cassert>
#include <iostream>
#include "hdf5MetaData.h"
#include "halCommon.h"

using namespace hal;
using namespace H5;
using namespace std;

HDF5MetaData::HDF5MetaData() :
  _parent(NULL)
{
}

HDF5MetaData::HDF5MetaData(CommonFG* parent, const string& name)
{
  open(parent, name);
}

HDF5MetaData::~HDF5MetaData()
{
  write();
}

void HDF5MetaData::set(const string& key, const string& value)
{
  if (has(key) == true)
  {
    _map[key] = value;
  }
  else
  {
    _map.insert(pair<string, string>(key, value));
  }
  _dirty = true;
}

const string& HDF5MetaData::get(const string& key) const
{
  assert (has(key) == true);
  return _map.find(key)->second;
}

bool HDF5MetaData::has(const string& key) const
{
  return _map.find(key) != _map.end();
}

const map<string, string>& HDF5MetaData::getMap() const
{
  return _map;
}

static void attr_operator(H5Object& loc/*in*/,
                          const H5std_string attr_name/*in*/,
                          void *operator_data/*in,out*/)
{
  map<string, string>* attMap =
     static_cast<map<string, string>*>(operator_data);
  StrType vlsType(0, H5T_VARIABLE);
  Attribute attr = loc.openAttribute(attr_name);
  H5std_string strg;
  attr.read(vlsType, strg);
  attMap->insert(pair<string, string>(attr_name, strg));
}

void HDF5MetaData::open(CommonFG* parent, const string& name)
{
  assert(parent != NULL);
  _map.clear();
  _parent = parent;
  _name = name;
  _dirty = false;

  H5::Exception::dontPrint();
  try
  {
    _group = parent->openGroup(name);
  }
  catch (Exception& e)
  {
    _group = parent->createGroup(name);
  }

  if (_group.getNumAttrs() > 0)
  {
    _group.iterateAttrs(attr_operator, NULL, &_map);
  }
  assert(_map.size() == (size_t)_group.getNumAttrs());
}

void HDF5MetaData::write()
{
  if (!_dirty)
     return;

  for (map<string, string>::iterator i = _map.begin();
       i != _map.end();
       ++i)
  {
    StrType vlsType(0, H5T_VARIABLE);
    DataSpace attSpace(H5S_SCALAR);
    Attribute attr;
    // we delve into C api for this test
    if (H5Aexists(_group.getId(), i->first.c_str()) == true)
    {
      _group.removeAttr(_name);
    }
    attr = _group.createAttribute(i->first, vlsType, attSpace);
    attr.write(vlsType, i->second);
  }
  _dirty = false;
}
<commit_msg>fix metadata rewrite bug<commit_after>/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */
#include <cassert>
#include <iostream>
#include "hdf5MetaData.h"
#include "halCommon.h"

using namespace hal;
using namespace H5;
using namespace std;

HDF5MetaData::HDF5MetaData() :
  _parent(NULL)
{
}

HDF5MetaData::HDF5MetaData(CommonFG* parent, const string& name)
{
  open(parent, name);
}

HDF5MetaData::~HDF5MetaData()
{
  write();
}

void HDF5MetaData::set(const string& key, const string& value)
{
  if (has(key) == true)
  {
    _map[key] = value;
  }
  else
  {
    _map.insert(pair<string, string>(key, value));
  }
  _dirty = true;
}

const string& HDF5MetaData::get(const string& key) const
{
  assert (has(key) == true);
  return _map.find(key)->second;
}

bool HDF5MetaData::has(const string& key) const
{
  return _map.find(key) != _map.end();
}

const map<string, string>& HDF5MetaData::getMap() const
{
  return _map;
}

static void attr_operator(H5Object& loc/*in*/,
                          const H5std_string attr_name/*in*/,
                          void *operator_data/*in,out*/)
{
  map<string, string>* attMap =
     static_cast<map<string, string>*>(operator_data);
  StrType vlsType(0, H5T_VARIABLE);
  Attribute attr = loc.openAttribute(attr_name);
  H5std_string strg;
  attr.read(vlsType, strg);
  attMap->insert(pair<string, string>(attr_name, strg));
}

void HDF5MetaData::open(CommonFG* parent, const string& name)
{
  assert(parent != NULL);
  _map.clear();
  _parent = parent;
  _name = name;
  _dirty = false;

  H5::Exception::dontPrint();
  try
  {
    _group = parent->openGroup(name);
  }
  catch (Exception& e)
  {
    _group = parent->createGroup(name);
  }

  if (_group.getNumAttrs() > 0)
  {
    _group.iterateAttrs(attr_operator, NULL, &_map);
  }
  assert(_map.size() == (size_t)_group.getNumAttrs());
}

void HDF5MetaData::write()
{
  if (!_dirty)
     return;

  for (map<string, string>::iterator i = _map.begin();
       i != _map.end();
       ++i)
  {
    StrType vlsType(0, H5T_VARIABLE);
    DataSpace attSpace(H5S_SCALAR);
    Attribute attr;
    // we delve into C api for this test
    if (H5Aexists(_group.getId(), i->first.c_str()) == true)
    {
      _group.removeAttr(i->first.c_str());
    }
    attr = _group.createAttribute(i->first, vlsType, attSpace);
    attr.write(vlsType, i->second);
  }
  _dirty = false;
}
<|endoftext|>


<commit_before>#include <network.h>
#include <server.h>
#include <stdexcept>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	if(argc != 3) {
		fprintf(stderr, "Usage: %s host port\n", argv[0]);
		return 10;
	}

	uint16_t port = strtoul(argv[2], NULL, 10);

	try {
		NetworkConfig *config = new NetworkConfig("test", "test", "n1CKn4M3", "us3RN4m3", "fuLLn4m3", "p4sSW0rd");
		if(!config) return 2;

		ServerConfig *server = new ServerConfig(argv[1], config, port);
		if(!server) return 3;
		config->servers.push_back(server);

		Network *n = new Network(config);
		if(!n) return 4;

		n->connectToNetwork(false);
		// run until disconnect
		n->run();

		delete n;
		delete server;
		delete config;
	} catch(std::runtime_error e) {
		return 1;
	}
	return 0;
}
<commit_msg>Add missing inclusion<commit_after>#include <network.h>
#include <server.h>
#include <stdexcept>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
	if(argc != 3) {
		fprintf(stderr, "Usage: %s host port\n", argv[0]);
		return 10;
	}

	uint16_t port = strtoul(argv[2], NULL, 10);

	try {
		NetworkConfig *config = new NetworkConfig("test", "test", "n1CKn4M3", "us3RN4m3", "fuLLn4m3", "p4sSW0rd");
		if(!config) return 2;

		ServerConfig *server = new ServerConfig(argv[1], config, port);
		if(!server) return 3;
		config->servers.push_back(server);

		Network *n = new Network(config);
		if(!n) return 4;

		n->connectToNetwork(false);
		// run until disconnect
		n->run();

		delete n;
		delete server;
		delete config;
	} catch(std::runtime_error e) {
		return 1;
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "CoordTransformer.h"
#include "../graphics/Rect.h"
#include "../graphics/Point.h"

#include "math.h"

namespace avg{
CoordTransformer::CoordTransformer(IntRect srcRect, double K1, double T, double RescaleFactor)
    :m_K1(K1),
    m_TrapezoidFactor(T),
    m_RescaleFactor(RescaleFactor)
{
    m_Center = DPoint((srcRect.tl.x+srcRect.br.x-1)/2., (srcRect.tl.y+srcRect.br.y-1)/2.);
    //normalize to center-edge distance
    m_Scale = sqrt( pow(m_Center.x - srcRect.Width(),2) +  pow(m_Center.y - srcRect.Height(),2) );
    m_TrapezoidScale = srcRect.Height()/2;

}
    CoordTransformer::~CoordTransformer(){};
    DPoint CoordTransformer::inv_distortion(const DPoint &pt){
        DPoint pt_norm = (pt - m_Center)/m_Scale;
        double r_d_squared = pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y;
        double S = (1 - m_K1*r_d_squared)*m_RescaleFactor;
        return (pt_norm*S)*m_Scale + m_Center;
    }
    DPoint CoordTransformer::distortion(const DPoint &pt){
        DPoint pt_norm = (pt - m_Center)/m_Scale;
        double r_d_squared = pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y;
        double S = (1 + m_K1*r_d_squared)/m_RescaleFactor;
        return pt_norm*S*m_Scale + m_Center;
    }
    DPoint CoordTransformer::inv_trapezoid(const DPoint &pt){
        //stretch x coord
        double yn = (pt.y - m_Center.y)/m_TrapezoidScale;
        return DPoint(
                (pt.x + m_Center.x * yn*m_TrapezoidFactor)/(1+yn*m_TrapezoidFactor),
                pt.y);
    }
    DPoint CoordTransformer::trapezoid(const DPoint &pt){
        //stretch x coord
        double yn = (pt.y - m_Center.y)/m_TrapezoidScale;
        return DPoint(
                //m_Center.x + ( pt.x - m_Center.x) * (1 + m_TrapezoidFactor * yn),
                pt.x + yn*m_TrapezoidFactor * (pt.x - m_Center.x),
                pt.y);
    }
    DPoint CoordTransformer::inverse_transform_point(const DPoint &pt){
        return inv_trapezoid(inv_distortion(pt));
    }
    DPoint CoordTransformer::transform_point(const DPoint &pt){
        return distortion(trapezoid(pt));
    }
    double CoordTransformer::getPixelSize(const DPoint &pt){
        //volume dxdy transforms as |D|dx'dy' where |D| is the functional determinant
        //det { { dx'/dx, dx'/dy}, {dy'/dx,dy'/dy}}
        //|D| = dx'/dx * dy'/dy - dx'/dy * dy'/dx
        //
        //with x'=x'(x,y) are the new coordinates in terms of the old ones
        //in our case.
        //trapezoid:
        //x' = m0 + (x-m0)*(1+m_TrapezoidFactor*yn)
        //y' = y
        //|D| = (1+m_TrapezoidFactor*yn)|(x,y)
        //
        //distortion:
        //x' = S*(x-x0) + x0
        //y' = S*(y-y0) + y0
        //oBdA x0=y0=0 (volume invariant under translation)
        //S = (1+m_K1*|(x,y)|^2/m_Scale)
        //dx'/dx = S+x*dS/dx
        //dx'/dy = x*dS/dy
        //dy'/dx = y*dS/dx
        //dy'/dy = S+y*dS/dx
        //maxima:
        //S(x,y):= (1+K1 *(x**2+y**2));
        //dS/dx = 2xK1
        //dS/dy = 2yK1
        //xd(x,y):=S(x,y)*x;
        //yd(x,y):=S(x,y)*y;
        //
        //diff(xd(x,y),x)*diff(yd(x,y),y)-diff(xd(x,y),y)*diff(yd(x,y),x);
        //|D| = S^2 + 2*x*y*dS/dx*dS/dy = S^2 + 16 x^2*y^2 K1^2
        //|D| = (...)|(xt,yt) where xt,yt are the coords after trapezoid trafo
        double yn = (pt.y - m_Center.y)/m_Scale;
        DPoint pt2 = trapezoid(pt);
        return (1+m_TrapezoidFactor*yn); // FIXME
    }

}
<commit_msg>inverse transforms finally correct<commit_after>#include "CoordTransformer.h"
#include "../graphics/Rect.h"
#include "../graphics/Point.h"
#include <iostream>
#include "math.h"
#define sqrt3 sqrt(3.)

namespace avg{
CoordTransformer::CoordTransformer(IntRect srcRect, double K1, double T, double RescaleFactor)
    :m_K1(K1),
    m_TrapezoidFactor(T),
    m_RescaleFactor(RescaleFactor)
{
    m_Center = DPoint((srcRect.tl.x+srcRect.br.x-1)/2., (srcRect.tl.y+srcRect.br.y-1)/2.);
    //normalize to center-edge distance
    m_Scale = sqrt( pow(m_Center.x - srcRect.Width(),2) +  pow(m_Center.y - srcRect.Height(),2) );
    m_TrapezoidScale = srcRect.Height()/2;

}
    CoordTransformer::~CoordTransformer(){};
    DPoint CoordTransformer::inv_distortion(const DPoint &pt){
        if (fabs(m_K1)<1e-10){
            return DPoint(pt);
        }
        DPoint pt_norm = (pt - m_Center)/m_Scale;
        double r_d = sqrt(pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y);
        double sub1;
        if (m_K1>0){
            sub1 =pow(sqrt((27*r_d*r_d*m_K1 + 4)/m_K1)/(6*sqrt(3)*m_K1) +
                        r_d/(2*m_K1), 1./3.);
        }else{
            sub1 =pow(sqrt((27*r_d*r_d*m_K1 - 4)/m_K1)/(6*sqrt(3)*m_K1) -
                        r_d/(2*m_K1), 1./3.);
        }
        double oldr = (sub1 - 1./(3*m_K1*sub1));
        double inv_S = m_RescaleFactor*oldr/r_d;
        return (pt_norm*inv_S)*m_Scale + m_Center;
    }
    DPoint CoordTransformer::distortion(const DPoint &pt){
        DPoint pt_norm = (pt - m_Center)/m_Scale;
        double r_d_squared = pt_norm.x*pt_norm.x + pt_norm.y*pt_norm.y;
        double S = (1 + m_K1*r_d_squared)/m_RescaleFactor;
        return pt_norm*S*m_Scale + m_Center;
    }
    DPoint CoordTransformer::inv_trapezoid(const DPoint &pt){
        //stretch x coord
        double yn = (pt.y - m_Center.y)/m_TrapezoidScale;
        return DPoint(
                (pt.x + m_Center.x * yn*m_TrapezoidFactor)/(1+yn*m_TrapezoidFactor),
                pt.y);
    }
    DPoint CoordTransformer::trapezoid(const DPoint &pt){
        //stretch x coord
        double yn = (pt.y - m_Center.y)/m_TrapezoidScale;
        return DPoint(
                //m_Center.x + ( pt.x - m_Center.x) * (1 + m_TrapezoidFactor * yn),
                pt.x + yn*m_TrapezoidFactor * (pt.x - m_Center.x),
                pt.y);
    }
    DPoint CoordTransformer::inverse_transform_point(const DPoint &pt){
        return inv_trapezoid(inv_distortion(pt));
    }
    DPoint CoordTransformer::transform_point(const DPoint &pt){
        return distortion(trapezoid(pt));
    }
    double CoordTransformer::getPixelSize(const DPoint &pt){
        //volume dxdy transforms as |D|dx'dy' where |D| is the functional determinant
        //det { { dx'/dx, dx'/dy}, {dy'/dx,dy'/dy}}
        //|D| = dx'/dx * dy'/dy - dx'/dy * dy'/dx
        //
        //with x'=x'(x,y) are the new coordinates in terms of the old ones
        //in our case.
        //trapezoid:
        //x' = m0 + (x-m0)*(1+m_TrapezoidFactor*yn)
        //y' = y
        //|D| = (1+m_TrapezoidFactor*yn)|(x,y)
        //
        //distortion:
        //x' = S*(x-x0) + x0
        //y' = S*(y-y0) + y0
        //oBdA x0=y0=0 (volume invariant under translation)
        //S = (1+m_K1*|(x,y)|^2/m_Scale)
        //dx'/dx = S+x*dS/dx
        //dx'/dy = x*dS/dy
        //dy'/dx = y*dS/dx
        //dy'/dy = S+y*dS/dx
        //maxima:
        //S(x,y):= (1+K1 *(x**2+y**2));
        //dS/dx = 2xK1
        //dS/dy = 2yK1
        //xd(x,y):=S(x,y)*x;
        //yd(x,y):=S(x,y)*y;
        //
        //diff(xd(x,y),x)*diff(yd(x,y),y)-diff(xd(x,y),y)*diff(yd(x,y),x);
        //|D| = S^2 + 2*x*y*dS/dx*dS/dy = S^2 + 16 x^2*y^2 K1^2
        //|D| = (...)|(xt,yt) where xt,yt are the coords after trapezoid trafo
        double yn = (pt.y - m_Center.y)/m_Scale;
        DPoint pt2 = trapezoid(pt);
        return (1+m_TrapezoidFactor*yn); // FIXME
    }

}
<|endoftext|>


<commit_before>#include "line_plot.hpp"
#include "selector.hpp"
#include "../app/data_source.hpp"

#include <QPainter>
#include <QPainterPath>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <QDebug>

using namespace std;

namespace datavis {

LinePlot::LinePlot(QObject * parent):
    Plot(parent)
{}

void LinePlot::setDataSource(DataSource * source)
{
    m_data_source = source;

    if (!source || source->data()->size().empty())
    {
        m_dim = -1;
        m_selector_dim = -1;
        m_start = 0;
        m_end = 0;
    }
    else
    {
        auto size = source->data()->size();

        if (size.size() > 1)
        {
            m_selector_dim = 0;
            m_dim = 1;
        }
        else
        {
            m_selector_dim = -1;
            m_dim = 0;
        }

        m_start = 0;
        m_end = size[m_dim];
    }

    findEntireValueRange();

    update_selected_region();

    emit sourceChanged();
    emit dimensionChanged();
    emit selectorDimChanged();
    emit xRangeChanged();
    emit yRangeChanged();
    emit selectorRangeChanged();
    emit contentChanged();
}

void LinePlot::setSelector(Selector * selector)
{
    if (m_selector)
    {
        disconnect(m_selector, 0, this, 0);
    }

    m_selector = selector;

    if (m_selector)
    {
        connect(m_selector, &Selector::valueChanged,
                this, &LinePlot::onSelectorValueChanged);
    }

    update_selected_region();

    //emit yRangeChanged();
    emit contentChanged();
}

void LinePlot::setDimension(int dim)
{
    if (!m_data_source)
        return;

    auto size = m_data_source->data()->size();

    if (dim < 0 || dim >= size.size())
    {
        cerr << "Invalid dimension: " << dim << endl;
        return;
    }

    if (m_selector_dim == dim)
        m_selector_dim = -1;

    m_dim = dim;
    m_start = 0;
    m_end = size[dim];

    update_selected_region();

    emit dimensionChanged();
    emit selectorDimChanged();
    emit xRangeChanged();
    //emit yRangeChanged();
    emit selectorRangeChanged();
    emit contentChanged();
}

int LinePlot::selectorDim()
{
    return m_selector_dim;
}

void LinePlot::setSelectorDim(int new_dim)
{
    if (!m_data_source)
    {
        cerr << "No data." << endl;
        return;
    }

    auto n_data_dim = m_data_source->data()->size().size();

    if (new_dim < 0 || new_dim >= n_data_dim)
    {
        cerr << "Invalid dimension: " << new_dim << endl;
        return;
    }

    if (new_dim == m_dim)
    {
        m_dim = -1;
    }

    m_selector_dim = new_dim;

    emit dimensionChanged();
    emit selectorDimChanged();
    emit xRangeChanged();
    //emit yRangeChanged();
    emit selectorRangeChanged();
    emit contentChanged();
}

void LinePlot::setRange(int start, int end)
{
    if (!m_data_source)
        return;

    auto size = m_data_source->data()->size();

    if (size.empty())
        return;

    if (m_dim < 0 || m_dim >= size.size())
    {
        cerr << "Unexpected: current dimension is invalid." << endl;
        return;
    }

    if (end < start)
    {
        cerr << "Warning: negative range." << endl;
        return;
    }

    if (start < 0 || start + end >= size[m_dim])
    {
        cerr << "Warning: selected range out of array bounds." << endl;
        return;
    }

    m_start = start;
    m_end = end;

    update_selected_region();

    emit xRangeChanged();
    //emit yRangeChanged();
    emit contentChanged();
}

void LinePlot::setColor(const QColor & color)
{
    m_color = color;

    emit colorChanged();
    emit contentChanged();
}

void LinePlot::onSelectorValueChanged()
{
    update_selected_region();

    //emit yRangeChanged();
    emit contentChanged();
}

void LinePlot::findEntireValueRange()
{
    if (!m_data_source)
        m_value_range = Range(0,0);

    auto region = get_all(*m_data_source->data());

    auto min_it = std::min_element(region.begin(), region.end());
    auto max_it = std::max_element(region.begin(), region.end());

    m_value_range.min = min_it.value();
    m_value_range.max = max_it.value();
}

void LinePlot::update_selected_region()
{
    if (!m_data_source)
    {
        m_data_region = data_region_type();
        return;
    }

    auto data_size = m_data_source->data()->size();
    auto n_dim = data_size.size();
    vector<int> offset(n_dim, 0);
    vector<int> size(n_dim, 1);

    if (m_selector_dim >= 0 && m_selector)
    {
        assert(m_selector_dim < n_dim);
        int value = m_selector->value();
        //qDebug() << "Selector value:" << value;
        //qDebug() << "Data size: " << data_size[m_selector_dim];
        if (value >= 0 && value < data_size[m_selector_dim])
        {
            offset[m_selector_dim] = value;
            size[m_selector_dim] = 1;
        }
        else
        {
            m_data_region = data_region_type();
            return;
        }
    }

    offset[m_dim] = m_start;
    size[m_dim] = m_end - m_start;

    m_data_region = get_region(*m_data_source->data(), offset, size);
}

Plot::Range LinePlot::xRange()
{
    if (!m_data_region.is_valid())
    {
        return Range();
    }

    return Range { double(m_start), double(m_end) };
}

Plot::Range LinePlot::yRange()
{
    return m_value_range;
#if 0
    if (!m_data_region.is_valid())
    {
        return Range();
    }

    auto min_it = std::min_element(m_data_region.begin(), m_data_region.end());
    auto max_it = std::max_element(m_data_region.begin(), m_data_region.end());
    double min_value = min_it.value();
    double max_value = max_it.value();

    return Range { min_value, max_value };
#endif
}

Plot::Range LinePlot::selectorRange()
{
    if (!m_data_source)
        return Range();

    if (m_selector_dim < 0)
        return Range();

    auto data_size = m_data_source->data()->size();

    assert(m_selector_dim >= 0 && m_selector_dim < data_size.size());

    return Range { double(0), double(data_size[m_selector_dim] - 1) };
}

void LinePlot::plot(QPainter * painter,  const QTransform & transform)
{
    if (!m_data_region.is_valid())
        return;

    painter->save();

    painter->setPen(m_color);
    painter->setBrush(Qt::NoBrush);
    painter->setRenderHint(QPainter::Antialiasing, true);

    QPainterPath path;
    bool first = true;
    for (auto & element : m_data_region)
    {
        int loc = element.location()[m_dim];
        double value = element.value();
        if (first)
            path.moveTo(loc, value);
        else
            path.lineTo(loc, value);
        first = false;
    }
    painter->drawPath(path * transform);

    painter->restore();
}

}
<commit_msg>Line plot: fix selecting dimensions<commit_after>#include "line_plot.hpp"
#include "selector.hpp"
#include "../app/data_source.hpp"

#include <QPainter>
#include <QPainterPath>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <QDebug>

using namespace std;

namespace datavis {

LinePlot::LinePlot(QObject * parent):
    Plot(parent)
{}

void LinePlot::setDataSource(DataSource * source)
{
    m_data_source = source;

    if (!source || source->data()->size().empty())
    {
        m_dim = -1;
        m_selector_dim = -1;
        m_start = 0;
        m_end = 0;
    }
    else
    {
        auto size = source->data()->size();

        if (size.size() > 1)
        {
            m_selector_dim = 0;
            m_dim = 1;
        }
        else
        {
            m_selector_dim = -1;
            m_dim = 0;
        }

        m_start = 0;
        m_end = size[m_dim];
    }

    findEntireValueRange();

    update_selected_region();

    emit sourceChanged();
    emit dimensionChanged();
    emit selectorDimChanged();
    emit xRangeChanged();
    emit yRangeChanged();
    emit selectorRangeChanged();
    emit contentChanged();
}

void LinePlot::setSelector(Selector * selector)
{
    if (m_selector)
    {
        disconnect(m_selector, 0, this, 0);
    }

    m_selector = selector;

    if (m_selector)
    {
        connect(m_selector, &Selector::valueChanged,
                this, &LinePlot::onSelectorValueChanged);
    }

    update_selected_region();

    //emit yRangeChanged();
    emit contentChanged();
}

void LinePlot::setDimension(int dim)
{
    if (!m_data_source)
        return;

    auto size = m_data_source->data()->size();

    if (dim < 0 || dim >= size.size())
        dim = -1;

    if (m_selector_dim == dim)
        m_selector_dim = -1;

    m_dim = dim;

    if (dim >= 0)
    {
        m_start = 0;
        m_end = size[dim];
    }
    else
    {
        m_start = 0;
        m_end = 0;
    }

    update_selected_region();

    emit dimensionChanged();
    emit selectorDimChanged();
    emit xRangeChanged();
    //emit yRangeChanged();
    emit selectorRangeChanged();
    emit contentChanged();
}

int LinePlot::selectorDim()
{
    return m_selector_dim;
}

void LinePlot::setSelectorDim(int new_dim)
{
    if (!m_data_source)
    {
        cerr << "No data." << endl;
        return;
    }

    auto n_data_dim = m_data_source->data()->size().size();

    if (new_dim == m_dim)
    {
        m_dim = -1;
    }

    if (new_dim < 0 || new_dim >= n_data_dim)
        new_dim = -1;

    m_selector_dim = new_dim;

    update_selected_region();

    emit dimensionChanged();
    emit selectorDimChanged();
    emit xRangeChanged();
    //emit yRangeChanged();
    emit selectorRangeChanged();
    emit contentChanged();
}

void LinePlot::setRange(int start, int end)
{
    if (!m_data_source)
        return;

    auto size = m_data_source->data()->size();

    if (size.empty())
        return;

    if (m_dim < 0 || m_dim >= size.size())
    {
        cerr << "Unexpected: current dimension is invalid." << endl;
        return;
    }

    if (end < start)
    {
        cerr << "Warning: negative range." << endl;
        return;
    }

    if (start < 0 || start + end >= size[m_dim])
    {
        cerr << "Warning: selected range out of array bounds." << endl;
        return;
    }

    m_start = start;
    m_end = end;

    update_selected_region();

    emit xRangeChanged();
    //emit yRangeChanged();
    emit contentChanged();
}

void LinePlot::setColor(const QColor & color)
{
    m_color = color;

    emit colorChanged();
    emit contentChanged();
}

void LinePlot::onSelectorValueChanged()
{
    update_selected_region();

    //emit yRangeChanged();
    emit contentChanged();
}

void LinePlot::findEntireValueRange()
{
    if (!m_data_source)
        m_value_range = Range(0,0);

    auto region = get_all(*m_data_source->data());

    auto min_it = std::min_element(region.begin(), region.end());
    auto max_it = std::max_element(region.begin(), region.end());

    m_value_range.min = min_it.value();
    m_value_range.max = max_it.value();
}

void LinePlot::update_selected_region()
{
    if (!m_data_source)
    {
        m_data_region = data_region_type();
        return;
    }

    if (m_dim < 0)
    {
        m_data_region = data_region_type();
        return;
    }

    auto data_size = m_data_source->data()->size();
    auto n_dim = data_size.size();
    vector<int> offset(n_dim, 0);
    vector<int> size(n_dim, 1);

    if (m_selector_dim >= 0 && m_selector)
    {
        assert(m_selector_dim < n_dim);
        int value = m_selector->value();
        //qDebug() << "Selector value:" << value;
        //qDebug() << "Data size: " << data_size[m_selector_dim];
        if (value >= 0 && value < data_size[m_selector_dim])
        {
            offset[m_selector_dim] = value;
            size[m_selector_dim] = 1;
        }
        else
        {
            m_data_region = data_region_type();
            return;
        }
    }

    offset[m_dim] = m_start;
    size[m_dim] = m_end - m_start;

    m_data_region = get_region(*m_data_source->data(), offset, size);
}

Plot::Range LinePlot::xRange()
{
    if (!m_data_region.is_valid())
    {
        return Range();
    }

    return Range { double(m_start), double(m_end) };
}

Plot::Range LinePlot::yRange()
{
    return m_value_range;
#if 0
    if (!m_data_region.is_valid())
    {
        return Range();
    }

    auto min_it = std::min_element(m_data_region.begin(), m_data_region.end());
    auto max_it = std::max_element(m_data_region.begin(), m_data_region.end());
    double min_value = min_it.value();
    double max_value = max_it.value();

    return Range { min_value, max_value };
#endif
}

Plot::Range LinePlot::selectorRange()
{
    if (!m_data_source)
        return Range();

    if (m_selector_dim < 0)
        return Range();

    auto data_size = m_data_source->data()->size();

    assert(m_selector_dim >= 0 && m_selector_dim < data_size.size());

    return Range { double(0), double(data_size[m_selector_dim] - 1) };
}

void LinePlot::plot(QPainter * painter,  const QTransform & transform)
{
    if (!m_data_region.is_valid())
        return;

    painter->save();

    painter->setPen(m_color);
    painter->setBrush(Qt::NoBrush);
    painter->setRenderHint(QPainter::Antialiasing, true);

    QPainterPath path;
    bool first = true;
    for (auto & element : m_data_region)
    {
        int loc = element.location()[m_dim];
        double value = element.value();
        if (first)
            path.moveTo(loc, value);
        else
            path.lineTo(loc, value);
        first = false;
    }
    painter->drawPath(path * transform);

    painter->restore();
}

}
<|endoftext|>


<commit_before>// @(#) $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTAgentUtil.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTUtil library
*/

#include <cassert>
#include "AliHLTAgentUtil.h"
#include "AliHLTConfiguration.h"
#include "AliHLTOUTHandlerChain.h"

// header files of library components
#include "AliHLTDataGenerator.h"
#include "AliHLTRawReaderPublisherComponent.h"
#include "AliHLTLoaderPublisherComponent.h"
#include "AliHLTRootFileStreamerComponent.h"
#include "AliHLTRootFileWriterComponent.h"
#include "AliHLTRootFilePublisherComponent.h"
//#include "AliHLTMCGeneratorComponent.h"
#include "AliHLTESDMCEventPublisherComponent.h"
#include "AliHLTFileWriter.h"
#include "AliHLTFilePublisher.h"
#include "AliHLTBlockFilterComponent.h"
#include "AliHLTEsdCollectorComponent.h"
#include "AliHLTOUTPublisherComponent.h"
#include "AliHLTCompStatCollector.h"

/** global instance for agent registration */
AliHLTAgentUtil gAliHLTAgentUtil;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTAgentUtil)

AliHLTAgentUtil::AliHLTAgentUtil()
  :
  AliHLTModuleAgent("Util"),
  fCompStatDataHandler(NULL)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTAgentUtil::~AliHLTAgentUtil()
{
  // see header file for class documentation
}

int AliHLTAgentUtil::CreateConfigurations(AliHLTConfigurationHandler* handler,
					  AliRawReader* /*rawReader*/,
					  AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  if (!handler) return 0;

  /////////////////////////////////////////////////////////////////////////////////////
  //
  // a kChain HLTOUT configuration for processing of {'COMPSTAT':'PRIV'} data blocks
  // produces a TTree object of the component statistics and writes it to disc

  // publisher component
  handler->CreateConfiguration("UTIL-hltout-compstat-publisher", "AliHLTOUTPublisher"   , NULL, "");

  // collector configuration
  handler->CreateConfiguration("UTIL-compstat-converter", "StatisticsCollector", "UTIL-hltout-compstat-publisher", "");

  // writer configuration
  handler->CreateConfiguration("UTIL-compstat-writer", "ROOTFileWriter", "UTIL-compstat-converter", "-datafile HLT.statistics.root -concatenate-events -overwrite");

  return 0;
}

const char* AliHLTAgentUtil::GetReconstructionChains(AliRawReader* /*rawReader*/,
						     AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return NULL;
}

const char* AliHLTAgentUtil::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}

int AliHLTAgentUtil::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTDataGenerator);
  pHandler->AddComponent(new AliHLTRawReaderPublisherComponent);
  pHandler->AddComponent(new AliHLTLoaderPublisherComponent);
  pHandler->AddComponent(new AliHLTRootFileStreamerComponent);
  pHandler->AddComponent(new AliHLTRootFileWriterComponent);
  pHandler->AddComponent(new AliHLTRootFilePublisherComponent);
  //  pHandler->AddComponent(new AliHLTMCGeneratorComponent);
  pHandler->AddComponent(new AliHLTESDMCEventPublisherComponent);
  pHandler->AddComponent(new AliHLTFileWriter);
  pHandler->AddComponent(new AliHLTFilePublisher);
  pHandler->AddComponent(new AliHLTBlockFilterComponent);
  pHandler->AddComponent(new AliHLTEsdCollectorComponent);
  pHandler->AddComponent(new AliHLTOUTPublisherComponent);
  pHandler->AddComponent(new AliHLTCompStatCollector);
  return 0;
}

int AliHLTAgentUtil::GetHandlerDescription(AliHLTComponentDataType dt,
					   AliHLTUInt32_t /*spec*/,
					   AliHLTOUTHandlerDesc& desc) const
{
  // see header file for class documentation

  // handler for the component statistics data blocks {'COMPSTAT':'PRIV'}
  if (dt==kAliHLTDataTypeComponentStatistics ||
      dt==kAliHLTDataTypeComponentTable) {
      desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId());
      return 1;
  }

  return 0;
}

AliHLTOUTHandler* AliHLTAgentUtil::GetOutputHandler(AliHLTComponentDataType dt,
						   AliHLTUInt32_t /*spec*/)
{
  // see header file for class documentation

  // handler for the component statistics data blocks {'COMPSTAT':'PRIV'}
  if (dt==kAliHLTDataTypeComponentStatistics ||
      dt==kAliHLTDataTypeComponentTable) {
    if (fCompStatDataHandler==NULL)
      fCompStatDataHandler=new AliHLTOUTHandlerChain("chains=UTIL-compstat-writer");
    return fCompStatDataHandler;
  }

  return NULL;
}

int AliHLTAgentUtil::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
  // see header file for class documentation
  if (pInstance==NULL) return -EINVAL;

  if (pInstance==fCompStatDataHandler) {
    delete fCompStatDataHandler;
    fCompStatDataHandler=NULL;
  }
  return 0;
}
<commit_msg>disable HLTOUT handler for component statistics due to bug https://savannah.cern.ch/bugs/?51359<commit_after>// @(#) $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/** @file   AliHLTAgentUtil.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTUtil library
*/

#include <cassert>
#include "AliHLTAgentUtil.h"
#include "AliHLTConfiguration.h"
#include "AliHLTOUTHandlerChain.h"

// header files of library components
#include "AliHLTDataGenerator.h"
#include "AliHLTRawReaderPublisherComponent.h"
#include "AliHLTLoaderPublisherComponent.h"
#include "AliHLTRootFileStreamerComponent.h"
#include "AliHLTRootFileWriterComponent.h"
#include "AliHLTRootFilePublisherComponent.h"
//#include "AliHLTMCGeneratorComponent.h"
#include "AliHLTESDMCEventPublisherComponent.h"
#include "AliHLTFileWriter.h"
#include "AliHLTFilePublisher.h"
#include "AliHLTBlockFilterComponent.h"
#include "AliHLTEsdCollectorComponent.h"
#include "AliHLTOUTPublisherComponent.h"
#include "AliHLTCompStatCollector.h"

/** global instance for agent registration */
AliHLTAgentUtil gAliHLTAgentUtil;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTAgentUtil)

AliHLTAgentUtil::AliHLTAgentUtil()
  :
  AliHLTModuleAgent("Util"),
  fCompStatDataHandler(NULL)
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTAgentUtil::~AliHLTAgentUtil()
{
  // see header file for class documentation
}

int AliHLTAgentUtil::CreateConfigurations(AliHLTConfigurationHandler* handler,
					  AliRawReader* /*rawReader*/,
					  AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  if (!handler) return 0;

  /////////////////////////////////////////////////////////////////////////////////////
  //
  // a kChain HLTOUT configuration for processing of {'COMPSTAT':'PRIV'} data blocks
  // produces a TTree object of the component statistics and writes it to disc

  // publisher component
  handler->CreateConfiguration("UTIL-hltout-compstat-publisher", "AliHLTOUTPublisher"   , NULL, "");

  // collector configuration
  handler->CreateConfiguration("UTIL-compstat-converter", "StatisticsCollector", "UTIL-hltout-compstat-publisher", "");

  // writer configuration
  handler->CreateConfiguration("UTIL-compstat-writer", "ROOTFileWriter", "UTIL-compstat-converter", "-datafile HLT.statistics.root -concatenate-events -overwrite");

  return 0;
}

const char* AliHLTAgentUtil::GetReconstructionChains(AliRawReader* /*rawReader*/,
						     AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return NULL;
}

const char* AliHLTAgentUtil::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}

int AliHLTAgentUtil::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTDataGenerator);
  pHandler->AddComponent(new AliHLTRawReaderPublisherComponent);
  pHandler->AddComponent(new AliHLTLoaderPublisherComponent);
  pHandler->AddComponent(new AliHLTRootFileStreamerComponent);
  pHandler->AddComponent(new AliHLTRootFileWriterComponent);
  pHandler->AddComponent(new AliHLTRootFilePublisherComponent);
  //  pHandler->AddComponent(new AliHLTMCGeneratorComponent);
  pHandler->AddComponent(new AliHLTESDMCEventPublisherComponent);
  pHandler->AddComponent(new AliHLTFileWriter);
  pHandler->AddComponent(new AliHLTFilePublisher);
  pHandler->AddComponent(new AliHLTBlockFilterComponent);
  pHandler->AddComponent(new AliHLTEsdCollectorComponent);
  pHandler->AddComponent(new AliHLTOUTPublisherComponent);
  pHandler->AddComponent(new AliHLTCompStatCollector);
  return 0;
}

int AliHLTAgentUtil::GetHandlerDescription(AliHLTComponentDataType dt,
					   AliHLTUInt32_t /*spec*/,
					   AliHLTOUTHandlerDesc& desc) const
{
  // see header file for class documentation
  return 0;

  // handler for the component statistics data blocks {'COMPSTAT':'PRIV'}
  if (dt==kAliHLTDataTypeComponentStatistics ||
      dt==kAliHLTDataTypeComponentTable) {
      desc=AliHLTOUTHandlerDesc(kChain, dt, GetModuleId());
      return 1;
  }

  return 0;
}

AliHLTOUTHandler* AliHLTAgentUtil::GetOutputHandler(AliHLTComponentDataType dt,
						   AliHLTUInt32_t /*spec*/)
{
  // see header file for class documentation
  return NULL;

  // handler for the component statistics data blocks {'COMPSTAT':'PRIV'}
  if (dt==kAliHLTDataTypeComponentStatistics ||
      dt==kAliHLTDataTypeComponentTable) {
    if (fCompStatDataHandler==NULL)
      fCompStatDataHandler=new AliHLTOUTHandlerChain("chains=UTIL-compstat-writer");
    return fCompStatDataHandler;
  }

  return NULL;
}

int AliHLTAgentUtil::DeleteOutputHandler(AliHLTOUTHandler* pInstance)
{
  // see header file for class documentation
  if (pInstance==NULL) return -EINVAL;

  if (pInstance==fCompStatDataHandler) {
    delete fCompStatDataHandler;
    fCompStatDataHandler=NULL;
  }
  return 0;
}
<|endoftext|>


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

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

const sal_Int32 n_ConstBufferSize = 32768;
const sal_Int32 n_ConstNonSpannableBufferSize = 128;
const sal_Int32 n_ConstMaxMemoryStreamSize = 20480;

#endif
<commit_msg>#91797# remove unused constant<commit_after>/*************************************************************************
 *
 *  $RCSfile: PackageConstants.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: mtg $ $Date: 2001-09-05 19:31:12 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _PACKAGE_CONSTANTS_HXX_
#define _PACKAGE_CONSTANTS_HXX_

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

const sal_Int32 n_ConstBufferSize = 32768;
const sal_Int32 n_ConstMaxMemoryStreamSize = 20480;

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <ui/menuinterface.h>
using namespace std;

void welcomeBanner();

int main()
{
    MenuInterface mI;
    mI.banner();
    mI.DisplayMenu();

    return 0;
}
<commit_msg>git fix<commit_after>#include <iostream>
#include <ui/menuinterface.h>
using namespace std;

void welcomeBanner();

int main()
{
    MenuInterface mI;
    mI.banner();
    mI.DisplayMenu();

    return 0;
}

<|endoftext|>


<commit_before>#pragma once

namespace principia {
namespace base {

#if defined(CDECL)
#  error "CDECL already defined"
#else
// Architecture macros from http://goo.gl/ZypnO8.
// We use cdecl on x86, the calling convention is unambiguous on x86-64.
#  if defined(__i386) || defined(_M_IX86)
#    if defined(_MSC_VER) || defined(__clang__)
#      define CDECL __cdecl
#    elif defined(__GNUC__) || defined(__INTEL_COMPILER)
#      define CDECL __attribute__((cdecl))
#    else
#      error "Get a real compiler"
#    endif
#  elif defined(_M_X64) || defined(__x86_64__)
#    define CDECL
#  else
#    error "Have you tried a Cray-1?"
#  endif
#endif

// DLL-exported functions for interfacing with Platform Invocation Services.
#if defined(DLLEXPORT)
#  error "DLLEXPORT already defined"
#else
#  if defined(_WIN32) || defined(_WIN64)
#    define DLLEXPORT __declspec(dllexport)
#  else
#    define DLLEXPORT __attribute__((visibility("default")))
#  endif
#endif

// A function for use on control paths that don't return a value, typically
// because they end with a |LOG(FATAL)|.
// MSVC used to require __declspec(noreturn) but doesn't anymore.  Odd.
#ifdef __clang__
[[noreturn]]
#endif
inline void noreturn() { exit(0); }

// Used to force inlining.
#ifdef __clang__
#define FORCE_INLINE [[gnu::always_inline]]
#elif _MSC_VER
#define FORCE_INLINE __forceinline
#endif

}  // namespace base
}  // namespace principia<commit_msg>After egg's review.<commit_after>#pragma once

namespace principia {
namespace base {

#if defined(CDECL)
#  error "CDECL already defined"
#else
// Architecture macros from http://goo.gl/ZypnO8.
// We use cdecl on x86, the calling convention is unambiguous on x86-64.
#  if defined(__i386) || defined(_M_IX86)
#    if defined(_MSC_VER) || defined(__clang__)
#      define CDECL __cdecl
#    elif defined(__GNUC__) || defined(__INTEL_COMPILER)
#      define CDECL __attribute__((cdecl))
#    else
#      error "Get a real compiler"
#    endif
#  elif defined(_M_X64) || defined(__x86_64__)
#    define CDECL
#  else
#    error "Have you tried a Cray-1?"
#  endif
#endif

// DLL-exported functions for interfacing with Platform Invocation Services.
#if defined(DLLEXPORT)
#  error "DLLEXPORT already defined"
#else
#  if defined(_WIN32) || defined(_WIN64)
#    define DLLEXPORT __declspec(dllexport)
#  else
#    define DLLEXPORT __attribute__((visibility("default")))
#  endif
#endif

// A function for use on control paths that don't return a value, typically
// because they end with a |LOG(FATAL)|.
#ifdef __clang__
[[noreturn]]
#elif _MSC_VER
__declspec(noreturn)
#endif
inline void noreturn() { exit(0); }

// Used to force inlining.
#ifdef __clang__
#define FORCE_INLINE [[gnu::always_inline]]
#elif _MSC_VER
#define FORCE_INLINE __forceinline
#endif

}  // namespace base
}  // namespace principia
<|endoftext|>


<commit_before>#ifndef __Matrix__
#define __Matrix__

#define GETSIZE(array) (sizeof(array) / sizeof(*array))

namespace base
{
    namespace matrix
    {
        template < unsigned int Row, unsigned int Col, typename T >
        struct matrix
        {
        public:
            typedef T value_type;

            // since std::vector is absence in avr-gcc, I will use a plain
            // two-dimensional array to represent a matrix, e.g. mdata[row][col]
            matrix() : mrow(Row), mcol(Col)
            {
                mdata = new value_type*[mrow];
                for(int i = 0; i < mrow; i++)
                {
                    mdata[i] = new value_type[mcol];
                }
            }

            ~matrix()
            {
                for(int i = 0; i < mrow; i++)
                {
                    delete [] mdata[i];
                }
                delete [] mdata;
            }

            // a specific version of traverse. side-effect is everywhere!
            // traverse :: (a -> b) -> Matrix b
            template< typename UnaryFunction >
            void traverse(UnaryFunction f)
            {
                for(int i = 0; i < mrow; i++)
                {
                    for(int j = 0; j < mcol; j++)
                    {
                        f(mdata[i][j]);
                    }
                }
            }

            void fillwith(value_type* list)
            {
                auto len = GETSIZE(list);
                //static_assert((mrow * mcol) <= len, "matrix need more elements");

                unsigned int index = 0;
                traverse([&index, &list](value_type i){ i = list[index++]; });
            }

            inline value_type at(unsigned row, unsigned col)
            {
                //static_assert((row <= mrow && col <= mcol), "out of bound");
                return mdata[row][col];
            }

        private:
            unsigned int  mrow;
            unsigned int  mcol;
            value_type**  mdata;
        };

        int main()
        {
            matrix<3,3,float> m;
            float f[9] = {1,2,3,4,5,6,7,8,9};
            m.fillwith(f);
            return 0;
        }

    }
}

#endif
<commit_msg>daily update<commit_after>#ifndef __Matrix__
#define __Matrix__

#define GETSIZE(array) (sizeof(array) / sizeof(*array))

namespace base
{
    namespace matrix
    {
        template < unsigned int Row, unsigned int Col, typename T >
        struct matrix
        {
        public:
            typedef T value_type;

            // since std::vector is absence in avr-gcc, I will use a plain
            // two-dimensional array to represent a matrix, e.g. mdata[row][col]
            matrix() : mrow(Row), mcol(Col)
            {
                mdata = new value_type*[mrow];
                for(int i = 0; i < mrow; i++)
                {
                    mdata[i] = new value_type[mcol];
                }
            }

            ~matrix()
            {
                for(int i = 0; i < mrow; i++)
                {
                    delete [] mdata[i];
                }
                delete [] mdata;
            }

            // a specific version of traverse. side-effect is everywhere!
            // traverse :: (a -> b) -> Matrix b
            template< typename UnaryFunction >
            void traverse(UnaryFunction f)
            {
                for(int i = 0; i < mrow; i++)
                {
                    for(int j = 0; j < mcol; j++)
                    {
                        f(mdata[i][j]);
                    }
                }
            }

            void fillWithList(const value_type* list)
            {
                unsigned index = 0;
                traverse(
                    [&](value_type i)
                    {
                        i = list[index++];
                    }
                );
            }

            void fillWith(const value_type v)
            {
                traverse(
                    [=](value_type i)
                    {
                        i = v;
                    }
                );
            }

            template < unsigned row, unsigned col >
            inline value_type at()
            {
                return mdata[row][col];
            }

            template < unsigned row, unsigned col >
            inline void set(const value_type v)
            {
                mdata[row][col] = v;
            }

            auto operator * (const matrix& m) -> decltype(this)
            {
                for(int i = 0; i < mrow; i++)
                {
                    auto reminder = 0;
                    for(int j = 0; j < mcol; j++)
                    {
                        reminder += mdata[i][j] * m.at<j,i>();
                    }
                    // TODO!
                }
            }

        private:
            unsigned int  mrow;
            unsigned int  mcol;
            value_type** mdata;
        };
    }
}

// just for test.
int main()
{
    using namespace base::matrix;
    matrix<3,3,float> m;
    float f[9] = {1,2,3,4,5,6,7,8,9};
    m.fillWithList(f);
    m.set<2,2>(3);
    int d = m.at<2,3>();
    return 0;
}

#endif
<|endoftext|>


<commit_before>#include <assert.h>
#include <sstream>

#include <QtConcurrentRun>
#include <QDateTime>
#include <QDebug>
#include <QPair>
#include <QString>
#include <QStringList>
#include <QTextDocument>
#include <QTimer>

#include <algorithm>

#include <AlpinoCorpus/Error.hh>
#include "QueryModel.hh"

QString const QueryModel::MISSING_ATTRIBUTE("[missing attribute]");

QueryModel::HitsCompare::HitsCompare(QueryModel const &parent)
:
    d_parent(parent)
{}

inline bool QueryModel::HitsCompare::operator()(int one_idx, int other_idx)
{
    int oneHits = d_parent.d_results[one_idx].second;
    int twoHits = d_parent.d_results[other_idx].second;

    if (oneHits == twoHits)
        return d_parent.d_results[one_idx].first <
            d_parent.d_results[other_idx].first;
    else
        return oneHits > twoHits;
}

QueryModel::QueryModel(CorpusPtr corpus, QObject *parent)
:
    QAbstractTableModel(parent),
    d_corpus(corpus),
    d_entryCache(new EntryCache()),
    d_timer(new QTimer)
{
    connect(this, SIGNAL(queryEntryFound(QString)),
        SLOT(mapperEntryFound(QString)));
    connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),
        SLOT(finalizeQuery(int, int, QString, bool, bool)));

    // Timer for progress updates.
    connect(d_timer.data(), SIGNAL(timeout()),
        SLOT(updateProgress()));
    connect(this, SIGNAL(queryStopped(int, int)),
        SLOT(stopProgress()));
    connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),
        SLOT(stopProgress()));
    connect(this, SIGNAL(queryFailed(QString)),
        SLOT(stopProgress()));
}

QueryModel::~QueryModel()
{
    cancelQuery();
}

QString QueryModel::asXML() const
{
    int rows = rowCount(QModelIndex());

    // TODO: Remove selected attribute from the filter...

    QStringList outList;
    outList.append("<statistics>");
    outList.append("<statisticsinfo>");
    outList.append(QString("<corpus>%1</corpus>")
        .arg(QString::fromUtf8(d_corpus->name().c_str())));
    outList.append(QString("<filter>%1</filter>")
        .arg(d_query));
    outList.append(QString("<attribute>%1</attribute>")
        .arg(d_attribute));
    outList.append(QString("<variants>%1</variants>")
        .arg(rows));
    outList.append(QString("<hits>%1</hits>")
        .arg(totalHits()));
    QString date(QDateTime::currentDateTime().toLocalTime().toString());
    outList.append(QString("<date>%1</date>")
        .arg(date));
    outList.append("</statisticsinfo>");

    for (int i = 0; i < rows; ++i) {
        outList.append("<statistic>");
        outList.append(QString("<value>%1</value>")
            .arg(Qt::escape(data(index(i, 0)).toString())));
        outList.append(QString("<frequency>%1</frequency>")
            .arg(data(index(i, 1)).toString()));
        outList.append(QString("<percentage>%1</percentage>")
            .arg(data(index(i, 2)).toDouble() * 100.0, 0, 'f', 1));
        outList.append("</statistic>");
    }

    outList.append("</statistics>");

    return outList.join("\n");
}

int QueryModel::columnCount(QModelIndex const &index) const
{
    return 3;
}

int QueryModel::rowCount(QModelIndex const &index) const
{
    return d_results.size();
}

QVariant QueryModel::data(QModelIndex const &index, int role) const
{
    if (!index.isValid()
        || index.row() >= d_results.size()
        || index.row() < 0
        || index.column() > 2
        || index.column() < 0)
        return QVariant();

    switch (role)
    {
        case Qt::UserRole:
        case Qt::DisplayRole:
            switch (index.column())
            {
                case 0:
                    // map positions of the hits index to the positions in d_results
                    return d_results[d_hitsIndex[index.row()]].first;
                case 1:
                    return d_results[d_hitsIndex[index.row()]].second;
                case 2:
                    return static_cast<double>(d_results[d_hitsIndex[index.row()]].second)
                         / static_cast<double>(d_totalHits);
                default:
                    return QVariant();
            }

        case Qt::TextAlignmentRole:
            switch (index.column())
            {
                case 1:
                case 2:
                    return Qt::AlignRight;

                default:
                    return Qt::AlignLeft;
            }

        default:
            return QVariant();
    }
}

QString QueryModel::expandQuery(QString const &query,
    QString const &attribute) const
{
    QString expandedQuery = QString("%1/(@%2/string(), '%3')[1]")
        .arg(query)
        .arg(attribute)
        .arg(MISSING_ATTRIBUTE);

    // Not all corpus readers support this styntax.
    if (!validQuery(expandedQuery))
        expandedQuery = QString("%1/@%2")
            .arg(query)
            .arg(attribute);

    return expandedQuery;
}

void QueryModel::updateProgress()
{
    emit progressChanged(d_entryIterator.progress());
}

QVariant QueryModel::headerData(int column, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Vertical)
        return QVariant();

    switch (column)
    {
        case 0:
            return tr("Value");
        case 1:
            return tr("Nodes");
        case 2:
            return tr("Percentage");
        default:
            return QVariant();
    }
}

void QueryModel::mapperEntryFound(QString entry)
{
    if (d_cancelled)
        return;

    // find position in d_results using the word index
    int idx = d_valueIndex.value(entry, -1);

    if (idx == -1)
    {
        idx = d_results.size();
        d_results.append(QPair<QString,int>(entry, 1));
        d_valueIndex[entry] = idx;

        HitsCompare compare(*this);

        // find new position, just above the result with less hits.
        QList<int>::iterator insertPos = qLowerBound(
            d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);

        // insert at new position
        d_hitsIndex.insert(insertPos, idx);

        emit layoutChanged(); // notify tableview that we have new rows
    }
    else
    {
        HitsCompare compare(*this);

        // Find the current position to remove

        // Binary search: does not work? Why not? :(
        QList<int>::iterator current_pos = qBinaryFind(
            d_hitsIndex.begin(), d_hitsIndex.end(), idx,
            compare);

        // It is already in the words index, it has to be in the hits index as well!
        assert(current_pos != d_hitsIndex.end());

        // remove from current position in the index
        d_hitsIndex.erase(current_pos);

        // Update hits index
        int hits = d_results[idx].second;
        d_results[idx].second = hits + 1;

        // find new position, just above the result with less hits.
        QList<int>::iterator insertPos = qLowerBound(
            d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);

        // insert at new position
        d_hitsIndex.insert(insertPos, idx);
    }

    ++d_totalHits;

    emit dataChanged(index(idx, 0), index(idx + 1, 2));
}

void QueryModel::runQuery(QString const &query, QString const &attribute,
    bool yield)
{
    cancelQuery(); // just in case

    // clean results cache and notify the table of the loss of rows
    //int size = d_results.size();
    d_results.clear();
    d_hitsIndex.clear();
    emit layoutChanged();

    // clear cache and counter
    d_valueIndex.clear();
    d_totalHits = 0;

    d_query = query;
    d_attribute = attribute;

    // Do nothing if we where given a null-pointer
    if (!d_corpus)
        return;

    if (!query.isEmpty())
    {
        d_timer->setInterval(100);
        d_timer->setSingleShot(false);
        d_timer->start();

        if (yield)
          d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,
              query, attribute, yield);
        else
          d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,
              expandQuery(query, attribute), attribute, yield);
    }
    // If the query is empty, QueryModel is not supposed to do anything.
}

bool QueryModel::validQuery(QString const &query) const
{
    return d_corpus->isValidQuery(alpinocorpus::CorpusReader::XPATH,
        false, query.toUtf8().constData()).isRight();
}

void QueryModel::cancelQuery()
{
    d_cancelled = true;
    d_entryIterator.interrupt();
    d_entriesFuture.waitForFinished();
    d_timer->stop();
}

void QueryModel::finalizeQuery(int n, int totalEntries, QString query, bool cached, bool yield)
{
    // Just to make sure, otherwise data() will go completely crazy
    Q_ASSERT(d_hitsIndex.size() == d_results.size());

    layoutChanged(); // Please, don't do this. Let's copy FilterModel's implementation.

    if (!cached)
    {
        d_entryCache->insert(QueryYieldPair(query, yield), new CacheItem(d_totalHits, d_hitsIndex, d_results));

        // this index is no longer needed, as it is only used for constructing d_hitsIndex
        d_valueIndex.clear();
    }
}

// run async, because query() starts searching immediately
void QueryModel::getEntriesWithQuery(QString const &query,
    QString const &attribute, bool yield)
{
    try {
        if (d_entryCache->contains(QueryYieldPair(query, yield)))
        {
            {
              QMutexLocker locker(&d_resultsMutex);
              CacheItem *cachedResult = d_entryCache->object(QueryYieldPair(query, yield));
              d_totalHits = cachedResult->hits;
              d_hitsIndex = cachedResult->index;
              d_results   = cachedResult->entries;
            }

            emit queryFinished(d_results.size(), d_results.size(), query, true, yield);
            return;
        }

        QueryModel::getEntries(
            d_corpus->query(alpinocorpus::CorpusReader::XPATH, query.toUtf8().constData()),
            query.toUtf8().constData(), attribute.toUtf8().constData(), yield);
    } catch (std::exception const &e) {
        qDebug() << "Error in QueryModel::getEntries: " << e.what();
        emit queryFailed(e.what());
    }
}

// run async
void QueryModel::getEntries(EntryIterator const &i, std::string const &query,
    std::string const &attribute, bool yield)
{
    if (i.hasProgress())
      emit queryStarted(100);
    else
      emit queryStarted(0);

    try {
        d_cancelled = false;
        d_entryIterator = i;

        while (!d_cancelled && d_entryIterator.hasNext())
        {
            alpinocorpus::Entry e = d_entryIterator.next(*d_corpus);

            if (yield) {
                std::vector<alpinocorpus::LexItem> sent =
                  d_corpus->sentence(e.name, query, attribute);

                // Find all match ids.
                std::set<size_t> ids;
                foreach (alpinocorpus::LexItem const &lexItem, sent)
                  ids.insert(lexItem.matches.begin(), lexItem.matches.end());

                foreach (size_t id, ids) {
                    std::ostringstream oss;
                    bool firstToken = true;

                    foreach (alpinocorpus::LexItem const &lexItem, sent) {
                        if (lexItem.matches.find(id) != lexItem.matches.end()) {
                            if (firstToken)
                              firstToken = false;
                            else
                              oss << " ";

                            oss << lexItem.word;
                        }
                    }

                    std::string result = oss.str();
                    emit queryEntryFound(QString::fromUtf8(result.c_str()));
                }
                size_t prevDepth = 0;
            }
            else
              emit queryEntryFound(QString::fromUtf8(e.contents.c_str()));
        }

        if (d_cancelled)
            emit queryStopped(d_results.size(), d_results.size());
        else
            emit queryFinished(d_results.size(), d_results.size(), QString::fromUtf8(query.c_str()), false, yield);
    }
    // Catch d_entryIterator.interrupt()'s shockwaves of terror
    catch (alpinocorpus::IterationInterrupted const &e) {
        emit queryStopped(d_results.size(), d_results.size());
    }
    catch (alpinocorpus::Error const &e) {
        qDebug() << "Error in QueryModel::getEntries: " << e.what();
        emit queryFailed(e.what());
    }
}

void QueryModel::stopProgress()
{
    d_timer->stop();
}

<commit_msg>yield: don't double count multiple occurrences in a tree.<commit_after>#include <assert.h>
#include <sstream>

#include <QtConcurrentRun>
#include <QDateTime>
#include <QDebug>
#include <QPair>
#include <QString>
#include <QStringList>
#include <QTextDocument>
#include <QTimer>

#include <algorithm>
#include <set>

#include <AlpinoCorpus/Error.hh>
#include "QueryModel.hh"

QString const QueryModel::MISSING_ATTRIBUTE("[missing attribute]");

QueryModel::HitsCompare::HitsCompare(QueryModel const &parent)
:
    d_parent(parent)
{}

inline bool QueryModel::HitsCompare::operator()(int one_idx, int other_idx)
{
    int oneHits = d_parent.d_results[one_idx].second;
    int twoHits = d_parent.d_results[other_idx].second;

    if (oneHits == twoHits)
        return d_parent.d_results[one_idx].first <
            d_parent.d_results[other_idx].first;
    else
        return oneHits > twoHits;
}

QueryModel::QueryModel(CorpusPtr corpus, QObject *parent)
:
    QAbstractTableModel(parent),
    d_corpus(corpus),
    d_entryCache(new EntryCache()),
    d_timer(new QTimer)
{
    connect(this, SIGNAL(queryEntryFound(QString)),
        SLOT(mapperEntryFound(QString)));
    connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),
        SLOT(finalizeQuery(int, int, QString, bool, bool)));

    // Timer for progress updates.
    connect(d_timer.data(), SIGNAL(timeout()),
        SLOT(updateProgress()));
    connect(this, SIGNAL(queryStopped(int, int)),
        SLOT(stopProgress()));
    connect(this, SIGNAL(queryFinished(int, int, QString, bool, bool)),
        SLOT(stopProgress()));
    connect(this, SIGNAL(queryFailed(QString)),
        SLOT(stopProgress()));
}

QueryModel::~QueryModel()
{
    cancelQuery();
}

QString QueryModel::asXML() const
{
    int rows = rowCount(QModelIndex());

    // TODO: Remove selected attribute from the filter...

    QStringList outList;
    outList.append("<statistics>");
    outList.append("<statisticsinfo>");
    outList.append(QString("<corpus>%1</corpus>")
        .arg(QString::fromUtf8(d_corpus->name().c_str())));
    outList.append(QString("<filter>%1</filter>")
        .arg(d_query));
    outList.append(QString("<attribute>%1</attribute>")
        .arg(d_attribute));
    outList.append(QString("<variants>%1</variants>")
        .arg(rows));
    outList.append(QString("<hits>%1</hits>")
        .arg(totalHits()));
    QString date(QDateTime::currentDateTime().toLocalTime().toString());
    outList.append(QString("<date>%1</date>")
        .arg(date));
    outList.append("</statisticsinfo>");

    for (int i = 0; i < rows; ++i) {
        outList.append("<statistic>");
        outList.append(QString("<value>%1</value>")
            .arg(Qt::escape(data(index(i, 0)).toString())));
        outList.append(QString("<frequency>%1</frequency>")
            .arg(data(index(i, 1)).toString()));
        outList.append(QString("<percentage>%1</percentage>")
            .arg(data(index(i, 2)).toDouble() * 100.0, 0, 'f', 1));
        outList.append("</statistic>");
    }

    outList.append("</statistics>");

    return outList.join("\n");
}

int QueryModel::columnCount(QModelIndex const &index) const
{
    return 3;
}

int QueryModel::rowCount(QModelIndex const &index) const
{
    return d_results.size();
}

QVariant QueryModel::data(QModelIndex const &index, int role) const
{
    if (!index.isValid()
        || index.row() >= d_results.size()
        || index.row() < 0
        || index.column() > 2
        || index.column() < 0)
        return QVariant();

    switch (role)
    {
        case Qt::UserRole:
        case Qt::DisplayRole:
            switch (index.column())
            {
                case 0:
                    // map positions of the hits index to the positions in d_results
                    return d_results[d_hitsIndex[index.row()]].first;
                case 1:
                    return d_results[d_hitsIndex[index.row()]].second;
                case 2:
                    return static_cast<double>(d_results[d_hitsIndex[index.row()]].second)
                         / static_cast<double>(d_totalHits);
                default:
                    return QVariant();
            }

        case Qt::TextAlignmentRole:
            switch (index.column())
            {
                case 1:
                case 2:
                    return Qt::AlignRight;

                default:
                    return Qt::AlignLeft;
            }

        default:
            return QVariant();
    }
}

QString QueryModel::expandQuery(QString const &query,
    QString const &attribute) const
{
    QString expandedQuery = QString("%1/(@%2/string(), '%3')[1]")
        .arg(query)
        .arg(attribute)
        .arg(MISSING_ATTRIBUTE);

    // Not all corpus readers support this styntax.
    if (!validQuery(expandedQuery))
        expandedQuery = QString("%1/@%2")
            .arg(query)
            .arg(attribute);

    return expandedQuery;
}

void QueryModel::updateProgress()
{
    emit progressChanged(d_entryIterator.progress());
}

QVariant QueryModel::headerData(int column, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Vertical)
        return QVariant();

    switch (column)
    {
        case 0:
            return tr("Value");
        case 1:
            return tr("Nodes");
        case 2:
            return tr("Percentage");
        default:
            return QVariant();
    }
}

void QueryModel::mapperEntryFound(QString entry)
{
    if (d_cancelled)
        return;

    // find position in d_results using the word index
    int idx = d_valueIndex.value(entry, -1);

    if (idx == -1)
    {
        idx = d_results.size();
        d_results.append(QPair<QString,int>(entry, 1));
        d_valueIndex[entry] = idx;

        HitsCompare compare(*this);

        // find new position, just above the result with less hits.
        QList<int>::iterator insertPos = qLowerBound(
            d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);

        // insert at new position
        d_hitsIndex.insert(insertPos, idx);

        emit layoutChanged(); // notify tableview that we have new rows
    }
    else
    {
        HitsCompare compare(*this);

        // Find the current position to remove

        // Binary search: does not work? Why not? :(
        QList<int>::iterator current_pos = qBinaryFind(
            d_hitsIndex.begin(), d_hitsIndex.end(), idx,
            compare);

        // It is already in the words index, it has to be in the hits index as well!
        assert(current_pos != d_hitsIndex.end());

        // remove from current position in the index
        d_hitsIndex.erase(current_pos);

        // Update hits index
        int hits = d_results[idx].second;
        d_results[idx].second = hits + 1;

        // find new position, just above the result with less hits.
        QList<int>::iterator insertPos = qLowerBound(
            d_hitsIndex.begin(), d_hitsIndex.end(), idx, compare);

        // insert at new position
        d_hitsIndex.insert(insertPos, idx);
    }

    ++d_totalHits;

    emit dataChanged(index(idx, 0), index(idx + 1, 2));
}

void QueryModel::runQuery(QString const &query, QString const &attribute,
    bool yield)
{
    cancelQuery(); // just in case

    // clean results cache and notify the table of the loss of rows
    //int size = d_results.size();
    d_results.clear();
    d_hitsIndex.clear();
    emit layoutChanged();

    // clear cache and counter
    d_valueIndex.clear();
    d_totalHits = 0;

    d_query = query;
    d_attribute = attribute;

    // Do nothing if we where given a null-pointer
    if (!d_corpus)
        return;

    if (!query.isEmpty())
    {
        d_timer->setInterval(100);
        d_timer->setSingleShot(false);
        d_timer->start();

        if (yield)
          d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,
              query, attribute, yield);
        else
          d_entriesFuture = QtConcurrent::run(this, &QueryModel::getEntriesWithQuery,
              expandQuery(query, attribute), attribute, yield);
    }
    // If the query is empty, QueryModel is not supposed to do anything.
}

bool QueryModel::validQuery(QString const &query) const
{
    return d_corpus->isValidQuery(alpinocorpus::CorpusReader::XPATH,
        false, query.toUtf8().constData()).isRight();
}

void QueryModel::cancelQuery()
{
    d_cancelled = true;
    d_entryIterator.interrupt();
    d_entriesFuture.waitForFinished();
    d_timer->stop();
}

void QueryModel::finalizeQuery(int n, int totalEntries, QString query, bool cached, bool yield)
{
    // Just to make sure, otherwise data() will go completely crazy
    Q_ASSERT(d_hitsIndex.size() == d_results.size());

    layoutChanged(); // Please, don't do this. Let's copy FilterModel's implementation.

    if (!cached)
    {
        d_entryCache->insert(QueryYieldPair(query, yield), new CacheItem(d_totalHits, d_hitsIndex, d_results));

        // this index is no longer needed, as it is only used for constructing d_hitsIndex
        d_valueIndex.clear();
    }
}

// run async, because query() starts searching immediately
void QueryModel::getEntriesWithQuery(QString const &query,
    QString const &attribute, bool yield)
{
    try {
        if (d_entryCache->contains(QueryYieldPair(query, yield)))
        {
            {
              QMutexLocker locker(&d_resultsMutex);
              CacheItem *cachedResult = d_entryCache->object(QueryYieldPair(query, yield));
              d_totalHits = cachedResult->hits;
              d_hitsIndex = cachedResult->index;
              d_results   = cachedResult->entries;
            }

            emit queryFinished(d_results.size(), d_results.size(), query, true, yield);
            return;
        }

        QueryModel::getEntries(
            d_corpus->query(alpinocorpus::CorpusReader::XPATH, query.toUtf8().constData()),
            query.toUtf8().constData(), attribute.toUtf8().constData(), yield);
    } catch (std::exception const &e) {
        qDebug() << "Error in QueryModel::getEntries: " << e.what();
        emit queryFailed(e.what());
    }
}

// run async
void QueryModel::getEntries(EntryIterator const &i, std::string const &query,
    std::string const &attribute, bool yield)
{
    if (i.hasProgress())
      emit queryStarted(100);
    else
      emit queryStarted(0);

    try {
        d_cancelled = false;
        d_entryIterator = i;

        std::set<std::string> seen;

        while (!d_cancelled && d_entryIterator.hasNext())
        {
            alpinocorpus::Entry e = d_entryIterator.next(*d_corpus);

            if (yield) {
                // Check whether we have already processed this tree before.
                if (seen.find(e.name) != seen.end())
                  continue;
                seen.insert(e.name);

                std::vector<alpinocorpus::LexItem> sent =
                  d_corpus->sentence(e.name, query, attribute);

                // Find all match ids.
                std::set<size_t> ids;
                foreach (alpinocorpus::LexItem const &lexItem, sent)
                  ids.insert(lexItem.matches.begin(), lexItem.matches.end());

                foreach (size_t id, ids) {
                    std::ostringstream oss;
                    bool firstToken = true;

                    foreach (alpinocorpus::LexItem const &lexItem, sent) {
                        if (lexItem.matches.find(id) != lexItem.matches.end()) {
                            if (firstToken)
                              firstToken = false;
                            else
                              oss << " ";

                            oss << lexItem.word;
                        }
                    }

                    std::string result = oss.str();
                    emit queryEntryFound(QString::fromUtf8(result.c_str()));
                }
                size_t prevDepth = 0;
            }
            else
              emit queryEntryFound(QString::fromUtf8(e.contents.c_str()));
        }

        if (d_cancelled)
            emit queryStopped(d_results.size(), d_results.size());
        else
            emit queryFinished(d_results.size(), d_results.size(), QString::fromUtf8(query.c_str()), false, yield);
    }
    // Catch d_entryIterator.interrupt()'s shockwaves of terror
    catch (alpinocorpus::IterationInterrupted const &e) {
        emit queryStopped(d_results.size(), d_results.size());
    }
    catch (alpinocorpus::Error const &e) {
        qDebug() << "Error in QueryModel::getEntries: " << e.what();
        emit queryFailed(e.what());
    }
}

void QueryModel::stopProgress()
{
    d_timer->stop();
}

<|endoftext|>


<commit_before>#include "helpers.h"

#include <X11/extensions/XInput2.h>

void StartServer(std::string prefix, ::xorg::testing::XServer &server, XOrgConfig &config) {
    std::stringstream conf;
    conf << "/tmp/" << prefix << ".conf";

    std::stringstream logfile;
    logfile << "/tmp/Xorg-" << prefix << ".log";

    config.SetPath(conf.str());
    config.WriteConfig();
    server.SetOption("-config", config.GetPath());
    server.SetOption("-logfile", logfile.str());
    server.SetDisplayNumber(133);
    server.Start();
    server.WaitForConnections();
}

int FindInputDeviceByName(Display *dpy, const std::string &device_name, int *deviceid)
{
    int ndevices;
    XIDeviceInfo *info;

    info = XIQueryDevice(dpy, XIAllDevices, &ndevices);

    int found = 0;
    while(ndevices--) {
        if (strcmp(info[ndevices].name, device_name.c_str()) == 0) {
            if (deviceid)
                *deviceid = info[ndevices].deviceid;
            found++;
        }
    }

    XIFreeDeviceInfo(info);

    return found;
}
<commit_msg>helpers: always warn if more than one device with a given name was found<commit_after>#include "helpers.h"

#include <X11/extensions/XInput2.h>

void StartServer(std::string prefix, ::xorg::testing::XServer &server, XOrgConfig &config) {
    std::stringstream conf;
    conf << "/tmp/" << prefix << ".conf";

    std::stringstream logfile;
    logfile << "/tmp/Xorg-" << prefix << ".log";

    config.SetPath(conf.str());
    config.WriteConfig();
    server.SetOption("-config", config.GetPath());
    server.SetOption("-logfile", logfile.str());
    server.SetDisplayNumber(133);
    server.Start();
    server.WaitForConnections();
}

int FindInputDeviceByName(Display *dpy, const std::string &device_name, int *deviceid)
{
    int ndevices;
    XIDeviceInfo *info;

    info = XIQueryDevice(dpy, XIAllDevices, &ndevices);

    int found = 0;
    while(ndevices--) {
        if (strcmp(info[ndevices].name, device_name.c_str()) == 0) {
            if (deviceid)
                *deviceid = info[ndevices].deviceid;
            found++;
        }
    }

    if (found > 1) {
        SCOPED_TRACE("More than one device named '" + device_name +
                     "' found.\nThis may cause some tests to fail.\n");
    }

    XIFreeDeviceInfo(info);

    return found;
}
<|endoftext|>


<commit_before>#include "JPetSigCh.h"
#include <limits>

ClassImp(JPetSigCh);
/// @todo init is not complete
const float JPetSigCh::kTimeUnset = std::numeric_limits<float>::infinity();
void JPetSigCh::init()
{
  SetNameTitle("JPetSigCh", "Signal Channel Structure");
  fAmpl = 0;
  fIsSlow = false;
  fIsComplete = false;
}

JPetSigCh::JPetSigCh(const JPetSigCh& obj)
{
  init();
  if (this != &obj) {
    fAmpl = obj.fAmpl;
    fIsSlow = obj.fIsSlow;
    fIsComplete = obj.fIsComplete;
    fPM = obj.fPM;
    fTRB = obj.fTRB;
    fScin = obj.fScin;
    fBarrelSlot = obj.fBarrelSlot;
    fChannels = obj.fChannels;
  }
}

JPetSigCh& JPetSigCh::operator=(JPetSigCh obj)
{
  my_swap(*this, obj);
  return *this;
}

JPetSigCh::JPetSigCh(float edge_time, float fall_edge_time)
{
  init();
  if (fall_edge_time == 0) fIsSlow = true;
  addCh(edge_time, fall_edge_time);
}

float JPetSigCh::getTime(EdgeType type) const {
  assert ((type == kRising) || (type == kFalling));
  if (type == kRising) return fChannels.first;
  if (type == kFalling) {
    if (isSlow()) {
      ERROR("This instance of JPetSigCh is of slow type, hence has no falling edge data.");
      return 0;
    }
    return fChannels.second;
  }
  return 0;
}

template <class T>
void JPetSigCh::set(T** dest, const T& source) throw(std::bad_alloc)
{
  assert(dest != 0);

  if ( &source == 0 && *dest != 0 ) {
    delete *dest;
    *dest = 0;
    return;
  }

  if (&source != 0) {
    if (*dest == 0) {
      try {
        *dest = new T;
      } catch (std::bad_alloc& b_a) {
        ERROR("Could not allocate memory.");
        ERROR(b_a.what());
      }
    }
    ** dest = source;
  }
}

void JPetSigCh::addCh(float rise_edge_time, float fall_edge_time)
{
  fChannels.first = rise_edge_time;
  fChannels.second = fall_edge_time;
}

<commit_msg>Remove todo comment<commit_after>#include "JPetSigCh.h"
#include <limits>

ClassImp(JPetSigCh);

const float JPetSigCh::kTimeUnset = std::numeric_limits<float>::infinity();
void JPetSigCh::init()
{
  SetNameTitle("JPetSigCh", "Signal Channel Structure");
  fAmpl = 0;
  fIsSlow = false;
  fIsComplete = false;
}

JPetSigCh::JPetSigCh(const JPetSigCh& obj)
{
  init();
  if (this != &obj) {
    fAmpl = obj.fAmpl;
    fIsSlow = obj.fIsSlow;
    fIsComplete = obj.fIsComplete;
    fPM = obj.fPM;
    fTRB = obj.fTRB;
    fScin = obj.fScin;
    fBarrelSlot = obj.fBarrelSlot;
    fChannels = obj.fChannels;
  }
}

JPetSigCh& JPetSigCh::operator=(JPetSigCh obj)
{
  my_swap(*this, obj);
  return *this;
}

JPetSigCh::JPetSigCh(float edge_time, float fall_edge_time)
{
  init();
  if (fall_edge_time == 0) fIsSlow = true;
  addCh(edge_time, fall_edge_time);
}

float JPetSigCh::getTime(EdgeType type) const {
  assert ((type == kRising) || (type == kFalling));
  if (type == kRising) return fChannels.first;
  if (type == kFalling) {
    if (isSlow()) {
      ERROR("This instance of JPetSigCh is of slow type, hence has no falling edge data.");
      return 0;
    }
    return fChannels.second;
  }
  return 0;
}

template <class T>
void JPetSigCh::set(T** dest, const T& source) throw(std::bad_alloc)
{
  assert(dest != 0);

  if ( &source == 0 && *dest != 0 ) {
    delete *dest;
    *dest = 0;
    return;
  }

  if (&source != 0) {
    if (*dest == 0) {
      try {
        *dest = new T;
      } catch (std::bad_alloc& b_a) {
        ERROR("Could not allocate memory.");
        ERROR(b_a.what());
      }
    }
    ** dest = source;
  }
}

void JPetSigCh::addCh(float rise_edge_time, float fall_edge_time)
{
  fChannels.first = rise_edge_time;
  fChannels.second = fall_edge_time;
}

<|endoftext|>