text:
// Copyright Takatoshi Kondo 2020
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#if !defined(MQTT_BROKER_SHARED_TARGET_HPP)
#define MQTT_BROKER_SHARED_TARGET_HPP

#include <mqtt/config.hpp>

#include <set>

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>

#include <mqtt/buffer.hpp>
#include <mqtt/optional.hpp>
#include <mqtt/time_point_t.hpp>

#include <mqtt/broker/broker_namespace.hpp>
#include <mqtt/broker/session_state_fwd.hpp>
#include <mqtt/broker/tags.hpp>

MQTT_BROKER_NS_BEGIN

namespace mi = boost::multi_index;

class shared_target {
public:
    void insert(buffer share_name, buffer topic_filter, session_state& ss);
    void erase(buffer share_name, buffer topic_filter, session_state const& ss);
    void erase(session_state const& ss);
    optional<session_state_ref> get_target(buffer const& share_name, buffer const& topic_filter);

private:
    struct entry {
        entry(buffer share_name, session_state& ss, time_point_t tp);

        buffer const& client_id() const;
        buffer share_name;
        session_state_ref ssr;
        time_point_t tp;
        std::set<buffer> topic_filters;
    };

    using mi_shared_target = mi::multi_index_container<
        entry,
        mi::indexed_by<
            mi::ordered_unique<
                mi::tag<tag_cid_sn>,
                mi::composite_key<
                    entry,
                    BOOST_MULTI_INDEX_CONST_MEM_FUN(entry, buffer const&, client_id),
                    BOOST_MULTI_INDEX_MEMBER(entry, buffer, share_name)
                >
            >,
            mi::ordered_non_unique<
                mi::tag<tag_sn_tp>,
                mi::composite_key<
                    entry,
                    BOOST_MULTI_INDEX_MEMBER(entry, buffer, share_name),
                    BOOST_MULTI_INDEX_MEMBER(entry, time_point_t, tp)
                >
            >
        >
    >;

    mi_shared_target targets_;
};

MQTT_BROKER_NS_END

#endif // MQTT_BROKER_SHARED_TARGET_HPP

ext: hpp


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

// currently windows is not using latest boost.
#ifdef PLATFORM_UNIX
#define BOOST_TEST_MODULE My Test
#include <boost/test/included/unit_test.hpp>
#else
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#endif

ext: cpp

max_stars_repo_name: gridgentoo/ServiceFabricAzure

max_issues_repo_name: gridgentoo/ServiceFabricAzure

max_forks_repo_name: gridgentoo/ServiceFabricAzure


text: #include <boost/spirit/home/x3/support/traits/variant_has_substitute.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*!
 *
 * \file DLX/Core/parser.hpp
 *
 * \author Tristan Vanderbruggen
 *
 */

#ifndef __DLX_FRONTEND_PARSER_HPP__
#define __DLX_FRONTEND_PARSER_HPP__

#include "DLX/Core/directives.hpp"
#include "DLX/Core/clauses.hpp"
#include "DLX/Core/constructs.hpp"

#include <boost/filesystem.hpp>

#include <vector>
#include <utility>
#include <string>

namespace DLX {

namespace Frontend {

// Basic string manip

void skip_whitespace(std::string & directive_str);
void skip_parenthesis(std::string & directive_str);

bool consume_label(std::string & directive_str, const std::string & label);

// Builtin types for clause's arguments

struct section_t {
  SgExpression * lower_bound;
  SgExpression * size;
  SgExpression * stride;
};

typedef std::vector<section_t> section_list_t;

typedef std::pair<SgVariableSymbol *, section_list_t> data_sections_t;

// Template for parsing of clause's arguments

class Parser {
  static bool s_singleton;

  public:
    Parser(std::string & directive_str, SgLocatedNode * directive_node);
    ~Parser();

    std::string getDirectiveString() const;

    template <typename A>
    bool parse(A &) const;

    template <typename A>
    bool parse_singleton(A & singleton, char start, char stop) const;

    template <typename A, typename B>
    bool parse_pair(std::pair<A, B> & pair, char start, char stop, char sep) const;

    template <typename A>
    bool parse_list(std::vector<A> & vect, char start, char stop, char sep) const;

    void skip_whitespace() const;
    bool consume(const char) const;
    bool consume(const std::string &) const;
};

// Builtin clause's argument types parsing

template <>
bool Parser::parse<size_t>(size_t &) const;

template <>
bool Parser::parse<SgExpression *>(SgExpression * & expr) const;

template <>
bool Parser::parse<SgValueExp *>(SgValueExp * & expr) const;

template <>
bool Parser::parse<std::string>(std::string & str) const;

template <>
bool Parser::parse<std::pair<SgExpression *, SgExpression *> >(std::pair<SgExpression *, SgExpression *> &) const;

template <>
bool Parser::parse<SgVariableSymbol *>(SgVariableSymbol * &) const;

template <>
bool Parser::parse<data_sections_t>(data_sections_t &) const;

template <>
bool Parser::parse<section_list_t>(section_list_t &) const;

template <>
bool Parser::parse<section_t>(section_t &) const;

template <>
bool Parser::parse<boost::filesystem::path>(boost::filesystem::path &) const;

// Template for singleton parsing

template <typename A>
bool Parser::parse_singleton(A & singleton, char start, char stop) const {
  if (!consume(start)) return false;
  if (!parse<A>(singleton)) return false;
  return consume(stop);
}

// Template for pair parsing

template <typename A, typename B>
bool Parser::parse_pair(std::pair<A, B> & pair, char start, char stop, char sep) const {
  if (!consume(start))        return false;
  if (!parse<A>(pair.first))  return false;
  if (!consume(sep))          return false;
  if (!parse<B>(pair.second)) return false;
  return consume(stop);
}

// Template for list parsing

template <typename A>
bool Parser::parse_list(std::vector<A> & vect, char start, char stop, char sep) const {
  skip_whitespace();

  if (!consume(start)) return false;

  skip_whitespace();
  do {
    A a;
    if (!parse<A>(a)) {
      if (sep == '\0') break;
      else return false;
    }
    vect.push_back(a);
    skip_whitespace();
  } while (consume(sep));

  if (!consume(stop)) return false;

  return true;
}

}

}

#endif /* __DLX_FRONTEND_PARSER_HPP__ */

max_stars_repo_name: ouankou/rose

max_issues_repo_name: sujankh/rose-matlab

max_forks_repo_name: sujankh/rose-matlab


text: #include <boost/serialization/throw_exception.hpp>


text:
/*
 * Copyright (c) 2021 The Foundation for Research on Information Technologies in Society (IT'IS).
 *
 * This file is part of iSEG
 * (see https://github.com/ITISFoundation/osparc-iseg).
 *
 * This software is released under the MIT License.
 *  https://opensource.org/licenses/MIT
 */
#include "Precompiled.h"

#define cimg_display 0
#include "CImg.h"
#include "LoaderWidgets.h"
#include "XdmfImageReader.h"

#include "Interface/LayoutTools.h"
#include "Interface/RecentPlaces.h"

#include "Data/Point.h"
#include "Data/ScopedTimer.h"

#include "Core/ColorLookupTable.h"
#include "Core/ImageReader.h"
#include "Core/ImageWriter.h"

#include "Thirdparty/nanoflann/nanoflann.hpp"

#include <q3hbox.h>
#include <q3vbox.h>
#include <QButtonGroup>
#include <QGridLayout>
#include <QGroupBox>
#include <QLabel>
#include <QMessageBox>
#include <QPushButton>
#include <QRadioButton>
#include <QString>

#include <QMouseEvent>
#include <QPainter>

#include <boost/algorithm/string.hpp>
#include <boost/dll.hpp>
#include <boost/filesystem.hpp>

namespace {
template<class VectorOfVectorsType, typename num_t = double, int DIM = -1, class Distance = nanoflann::metric_L2, typename IndexType = size_t>
struct KDTreeVectorOfVectorsAdaptor
{
	using self_t = KDTreeVectorOfVectorsAdaptor<VectorOfVectorsType, num_t, DIM, Distance>;
	using metric_t = typename Distance::template traits<num_t, self_t>::distance_t;
	using index_t = nanoflann::KDTreeSingleIndexAdaptor<metric_t, self_t, DIM, IndexType>;

	index_t* m_Index; //! The kd-tree index for the user to call its methods as usual with any other FLANN index.

	/// Constructor: takes a const ref to the vector of vectors object with the data points
	KDTreeVectorOfVectorsAdaptor(const size_t /* dimensionality */, const VectorOfVectorsType& mat, const int leaf_max_size = 10) : m_MData(mat)
	{
		assert(!mat.empty() && !mat[0].empty());
		const size_t dims = mat[0].size();
		if (DIM > 0 && static_cast<int>(dims) != DIM)
			throw std::runtime_error("Data set dimensionality does not match the 'DIM' template argument");
		m_Index = new index_t(static_cast<int>(dims), *this /* adaptor */, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size));
		m_Index->buildIndex();
	}

	~KDTreeVectorOfVectorsAdaptor()
	{
		delete m_Index;
	}

	const VectorOfVectorsType& m_MData;

	inline void Query(const num_t* query_point, const size_t num_closest, IndexType* out_indices, num_t* out_distances_sq, const int nChecks_IGNORED = 10) const
	{
		nanoflann::KNNResultSet<num_t, IndexType> result_set(num_closest);
		result_set.init(out_indices, out_distances_sq);
		m_Index->findNeighbors(result_set, query_point, nanoflann::SearchParams());
	}

	const self_t& derived() const { return *this; } // NOLINT
	self_t& derived() { return *this; }							// NOLINT

	inline size_t kdtree_get_point_count() const { return m_MData.size(); } // NOLINT

	inline num_t kdtree_get_pt(const size_t idx, const size_t dim) const // NOLINT
	{
		return m_MData[idx][dim];
	}

	template<class BBOX>
	bool kdtree_get_bbox(BBOX&) const // NOLINT
	{
		return false;
	}
};
} // namespace

namespace iseg {

namespace algo = boost::algorithm;
namespace fs = boost::filesystem;

ExportImg::ExportImg(SlicesHandler* h, QWidget* p, Qt::WindowFlags f)
		: QDialog(p, f), m_Handler3D(h)
{
	auto img_selection_hbox = new QHBoxLayout;
	m_ImgSelectionGroup = make_button_group({"Source", "Target", "Tissue"}, 0);
	for (auto b : m_ImgSelectionGroup->buttons())
	{
		img_selection_hbox->addWidget(b);
	}

	auto slice_selection_hbox = new QHBoxLayout;
	m_SliceSelectionGroup = make_button_group({"Current Slice", "Active Slices"}, 0);
	for (auto b : m_SliceSelectionGroup->buttons())
	{
		slice_selection_hbox->addWidget(b);
	}

	auto button_hbox = new QHBoxLayout;
	button_hbox->addWidget(m_PbSave = new QPushButton("OK"));
	button_hbox->addWidget(m_PbCancel = new QPushButton("Cancel"));

	auto top_layout = new QVBoxLayout;
	top_layout->addLayout(img_selection_hbox);
	top_layout->addLayout(slice_selection_hbox);
	top_layout->addLayout(button_hbox);
	setLayout(top_layout);

	QObject_connect(m_PbSave, SIGNAL(clicked()), this, SLOT(SavePushed()));
	QObject_connect(m_PbCancel, SIGNAL(clicked()), this, SLOT(close()));
}

void ExportImg::SavePushed()
{
	// todo: what to do about file series, e.g. select with some option (including base name), select directory (or save file name without extension, then append)
	QString filter =
			"Nifty file (*.nii.gz *nii.gz)\n"
			"Analyze file (*.hdr *.img)\n"
			"Nrrd file (*.nrrd)\n"
			"VTK file (*.vtk *vti)\n"
			"BMP file (*.bmp)\n"
			"PNG file (*.png)\n"
			"JPG file (*.jpg *.jpeg)";

	std::string file_path = RecentPlaces::GetSaveFileName(this, "Save As", QString::null, filter).toStdString();
	auto img_selection = static_cast<ImageWriter::eImageSelection>(m_ImgSelectionGroup->checkedId());
	auto slice_selection = static_cast<ImageWriter::eSliceSelection>(m_SliceSelectionGroup->checkedId());

	ImageWriter w(true);
	w.WriteVolume(file_path, m_Handler3D, img_selection, slice_selection);

	close();
}

LoaderDicom::LoaderDicom(SlicesHandler* hand3D, QStringList* lname, bool breload, QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags), m_Handler3D(hand3D), m_Reload(breload), m_Lnames(lname)
{
	setModal(true);

	m_Vbox1 = new Q3VBox(this);
	m_Hbox1 = new Q3HBox(m_Vbox1);
	m_CbSubsect = new QCheckBox(QString("Subsection "), m_Hbox1);
	m_CbSubsect->setChecked(false);
	m_CbSubsect->show();
	m_Hbox2 = new Q3HBox(m_Hbox1);

	m_Vbox2 = new Q3VBox(m_Hbox2);
	m_Vbox3 = new Q3VBox(m_Hbox2);
	m_Xoffs = new QLabel(QString("x-Offset: "), m_Vbox2);
	m_Xoffset = new QSpinBox(0, 2000, 1, m_Vbox3);
	m_Xoffset->setValue(0);
	m_Xoffset->show();
	m_Yoffs = new QLabel(QString("y-Offset: "), m_Vbox2);
	m_Yoffset = new QSpinBox(0, 2000, 1, m_Vbox3);
	m_Yoffset->show();
	m_Xoffset->setValue(0);
	m_Vbox2->show();
	m_Vbox3->show();

	m_Vbox4 = new Q3VBox(m_Hbox2);
	m_Vbox5 = new Q3VBox(m_Hbox2);
	m_Xl = new QLabel(QString("x-Length: "), m_Vbox4);
	m_Xlength = new QSpinBox(0, 2000, 1, m_Vbox5);
	m_Xlength->show();
	m_Xlength->setValue(512);
	m_Yl = new QLabel(QString("y-Length: "), m_Vbox4);
	m_Ylength = new QSpinBox(0, 2000, 1, m_Vbox5);
	m_Ylength->show();
	m_Ylength->setValue(512);
	m_Vbox4->show();
	m_Vbox5->show();

	m_Hbox2->show();
	m_Hbox1->show();

	m_Hbox3 = new Q3HBox(m_Vbox1);
	m_CbCt = new QCheckBox(QString("CT weight "), m_Hbox3);
	m_CbCt->setChecked(false);
	m_CbCt->show();
	m_Vbox6 = new Q3VBox(m_Hbox3);
	m_Hbox4 = new Q3HBox(m_Vbox6);
	m_BgWeight = new QButtonGroup(this);
	//	bg_weight->hide();
	m_RbBone = new QRadioButton(QString("Bone"), m_Hbox4);
	m_RbMuscle = new QRadioButton(QString("Muscle"), m_Hbox4);
	m_BgWeight->insert(m_RbBone);
	m_BgWeight->insert(m_RbMuscle);
	m_RbMuscle->setChecked(TRUE);
	m_RbMuscle->show();
	m_RbBone->show();
	m_Hbox4->show();
	m_CbCrop = new QCheckBox(QString("crop "), m_Vbox6);
	m_CbCrop->setChecked(true);
	m_CbCrop->show();
	m_Vbox6->show();
	m_Hbox3->show();
	//	hbox3->hide();

	if (!m_Lnames->empty())
	{
		std::vector<const char*> vnames;
		for (auto it = m_Lnames->begin(); it != m_Lnames->end(); it++)
		{
			vnames.push_back((*it).ascii());
		}
		m_Dicomseriesnr.clear();
		m_Handler3D->GetDICOMseriesnr(&vnames, &m_Dicomseriesnr, &m_Dicomseriesnrlist);
		if (m_Dicomseriesnr.size() > 1)
		{
			m_Hbox6 = new Q3HBox(m_Vbox1);

			m_LbTitle = new QLabel(QString("Series-Nr.: "), m_Hbox6);
			m_Seriesnrselection = new QComboBox(m_Hbox6);
			for (unsigned i = 0; i < (unsigned)m_Dicomseriesnr.size(); i++)
			{
				QString str;
				m_Seriesnrselection->addItem(str = str.setNum((int)m_Dicomseriesnr.at(i)));
			}
			m_Seriesnrselection->setCurrentIndex(0);
			m_Hbox6->show();
		}
	}

	m_Hbox5 = new Q3HBox(m_Vbox1);
	m_LoadFile = new QPushButton("Open", m_Hbox5);
	m_CancelBut = new QPushButton("Cancel", m_Hbox5);
	m_Hbox5->show();
	m_Vbox1->show();

	/*	vbox1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	vbox2->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox2->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox3->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox4->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox5->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));*/
	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
	m_Vbox1->setFixedSize(m_Vbox1->sizeHint());

	SubsectToggled();
	CtToggled();

	QObject_connect(m_LoadFile, SIGNAL(clicked()), this, SLOT(LoadPushed()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(close()));
	QObject_connect(m_CbSubsect, SIGNAL(clicked()), this, SLOT(SubsectToggled()));
	QObject_connect(m_CbCt, SIGNAL(clicked()), this, SLOT(CtToggled()));
}

LoaderDicom::~LoaderDicom()
{
	delete m_Vbox1;
	delete m_BgWeight;
}

void LoaderDicom::SubsectToggled()
{
	if (m_CbSubsect->isChecked())
	{
		m_Hbox2->show();
	}
	else
	{
		m_Hbox2->hide();
	}
}

void LoaderDicom::CtToggled()
{
	if (m_CbCt->isChecked())
	{
		m_Vbox6->show();
	}
	else
	{
		m_Vbox6->hide();
	}
}

void LoaderDicom::LoadPushed()
{
	if (!m_Lnames->empty())
	{
		std::vector<const char*> vnames;
		if (m_Dicomseriesnr.size() > 1)
		{
			unsigned pos = 0;
			for (const auto& name : *m_Lnames)
			{
				if (m_Dicomseriesnrlist[pos++] == m_Dicomseriesnr[m_Seriesnrselection->currentIndex()])
				{
					vnames.push_back(name.ascii());
				}
			}
		}
		else
		{
			for (const auto& name : *m_Lnames)
			{
				vnames.push_back(name.ascii());
			}
		}

		if (m_CbSubsect->isChecked())
		{
			Point p;
			p.px = m_Xoffset->value();
			p.py = m_Yoffset->value();
			if (m_Reload)
				m_Handler3D->ReloadDICOM(vnames, p);
			else
				m_Handler3D->LoadDICOM(vnames, p, m_Xlength->value(), m_Ylength->value());
		}
		else
		{
			if (m_Reload)
				m_Handler3D->ReloadDICOM(vnames);
			else
				m_Handler3D->LoadDICOM(vnames);
		}

		if (m_CbCt->isChecked())
		{
			Pair p;
			if (m_RbMuscle->isChecked())
			{
				p.high = 1190;
				p.low = 890;
			}
			else if (m_RbBone->isChecked())
			{
				m_Handler3D->GetRange(&p);
			}
			m_Handler3D->ScaleColors(p);
			if (m_CbCrop->isChecked())
			{
				m_Handler3D->CropColors();
			}
			m_Handler3D->Work2bmpall();
		}

		close();
	}
	else
	{
		close();
	}
}

LoaderRaw::LoaderRaw(SlicesHandler* hand3D, QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags), m_Handler3D(hand3D)
{
	setModal(true);

	m_Vbox1 = new Q3VBox(this);
	m_Hbox1 = new Q3HBox(m_Vbox1);
	m_FileName = new QLabel(QString("File Name: "), m_Hbox1);
	m_NameEdit = new QLineEdit(m_Hbox1);
	m_NameEdit->show();
	m_SelectFile = new QPushButton("Select", m_Hbox1);
	m_SelectFile->show();
	m_Hbox1->show();
	m_Hbox6 = new Q3HBox(m_Vbox1);
	m_Xl1 = new QLabel(QString("Total x-Length: "), m_Hbox6);
	m_Xlength1 = new QSpinBox(0, 9999, 1, m_Hbox6);
	m_Xlength1->show();
	m_Xlength1->setValue(512);
	m_Yl1 = new QLabel(QString("Total y-Length: "), m_Hbox6);
	m_Ylength1 = new QSpinBox(0, 9999, 1, m_Hbox6);
	m_Ylength1->show();
	m_Ylength1->setValue(512);
	/*	nrslice = new QLabel(QString("Slice Nr.: "),hbox6);
	slicenrbox=new QSpinBox(0,200,1,hbox6);
	slicenrbox->show();
	slicenrbox->setValue(0);*/
	m_Hbox6->show();
	m_Hbox8 = new Q3HBox(m_Vbox1);
	m_Nrslice = new QLabel(QString("Start Nr.: "), m_Hbox8);
	m_Slicenrbox = new QSpinBox(0, 9999, 1, m_Hbox8);
	m_Slicenrbox->show();
	m_Slicenrbox->setValue(0);
	m_LbNrslices = new QLabel("#Slices: ", m_Hbox8);
	m_SbNrslices = new QSpinBox(1, 9999, 1, m_Hbox8);
	m_SbNrslices->show();
	m_SbNrslices->setValue(10);
	m_Hbox8->show();
	m_Hbox2 = new Q3HBox(m_Vbox1);
	m_Subsect = new QCheckBox(QString("Subsection "), m_Hbox2);
	m_Subsect->setChecked(false);
	m_Subsect->show();
	m_Vbox2 = new Q3VBox(m_Hbox2);
	m_Hbox3 = new Q3HBox(m_Vbox2);
	m_Xoffs = new QLabel(QString("x-Offset: "), m_Hbox3);
	m_Xoffset = new QSpinBox(0, 2000, 1, m_Hbox3);
	m_Xoffset->setValue(0);
	m_Xoffset->show();
	m_Yoffs = new QLabel(QString("y-Offset: "), m_Hbox3);
	m_Yoffset = new QSpinBox(0, 2000, 1, m_Hbox3);
	m_Yoffset->show();
	m_Xoffset->setValue(0);
	m_Hbox3->show();
	m_Hbox4 = new Q3HBox(m_Vbox2);
	m_Xl = new QLabel(QString("x-Length: "), m_Hbox4);
	m_Xlength = new QSpinBox(0, 2000, 1, m_Hbox4);
	m_Xlength->show();
	m_Xlength->setValue(256);
	m_Yl = new QLabel(QString("y-Length: "), m_Hbox4);
	m_Ylength = new QSpinBox(0, 2000, 1, m_Hbox4);
	m_Ylength->show();
	m_Ylength->setValue(256);
	m_Hbox4->show();
	m_Vbox2->show();
	m_Hbox2->show();
	m_Hbox7 = new Q3HBox(m_Vbox1);
	m_Bitselect = new QButtonGroup(this);
	//	bitselect->hide();
	/*	bit8=new QRadioButton(QString("8-bit"),bitselect);
	bit16=new QRadioButton(QString("16-bit"),bitselect);*/
	m_Bit8 = new QRadioButton(QString("8-bit"), m_Hbox7);
	m_Bit16 = new QRadioButton(QString("16-bit"), m_Hbox7);
	m_Bitselect->insert(m_Bit8);
	m_Bitselect->insert(m_Bit16);
	m_Bit16->show();
	m_Bit8->setChecked(TRUE);
	m_Bit8->show();
	m_Hbox7->show();
	/*	bitselect->insert(bit8);
	bitselect->insert(bit16);*/

	m_Hbox5 = new Q3HBox(m_Vbox1);
	m_LoadFile = new QPushButton("Open", m_Hbox5);
	m_CancelBut = new QPushButton("Cancel", m_Hbox5);
	m_Hbox5->show();

	/*	vbox1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	vbox2->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox2->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox3->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox4->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox5->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));*/
	m_Vbox1->show();
	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

	m_Vbox1->setFixedSize(m_Vbox1->sizeHint());

	QObject_connect(m_SelectFile, SIGNAL(clicked()), this, SLOT(SelectPushed()));
	QObject_connect(m_LoadFile, SIGNAL(clicked()), this, SLOT(LoadPushed()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(close()));
	//	QObject_connect(subsect,SIGNAL(toggled(bool on)),this,SLOT(SubsectToggled(bool on)));
	QObject_connect(m_Subsect, SIGNAL(clicked()), this, SLOT(SubsectToggled()));
	//	QObject_connect(subsect,SIGNAL(toggled(bool on)),vbox2,SLOT(setShown(bool on)));

	SubsectToggled();
}

LoaderRaw::~LoaderRaw()
{
	delete m_Vbox1;
	delete m_Bitselect;
}

QString LoaderRaw::GetFileName() const { return m_NameEdit->text(); }

std::array<unsigned int, 2> LoaderRaw::GetDimensions() const
{
	return {
			static_cast<unsigned>(m_Xlength1->value()), static_cast<unsigned>(m_Ylength1->value())};
}

std::array<unsigned int, 3> LoaderRaw::GetSubregionStart() const
{
	return {
			static_cast<unsigned>(m_Xoffset->value()), static_cast<unsigned>(m_Yoffset->value()), static_cast<unsigned>(m_Slicenrbox->value())};
}

std::array<unsigned int, 3> LoaderRaw::GetSubregionSize() const
{
	return {
			static_cast<unsigned>(m_Subsect->isChecked() ? m_Xlength->value() : m_Xlength1->value()), static_cast<unsigned>(m_Subsect->isChecked() ? m_Ylength->value() : m_Ylength1->value()), static_cast<unsigned>(m_SbNrslices->value())};
}

int LoaderRaw::GetBits() const
{
	return (m_Bit8->isChecked() ? 8 : 16);
}

void LoaderRaw::SubsectToggled()
{
	bool isset = m_Subsect->isChecked();
	;
	if (isset)
	{
		m_Vbox2->show();
		//		nameEdit->setText(QString("ABC"));
	}
	else
	{
		m_Vbox2->hide();
		//		nameEdit->setText(QString("DEF"));
	}

	//	vbox1->setFixedSize(vbox1->sizeHint());
}

void LoaderRaw::LoadPushed()
{
	unsigned bitdepth;
	if (m_Bit8->isChecked())
		bitdepth = 8;
	else
		bitdepth = 16;
	if (!(m_NameEdit->text()).isEmpty())
	{
		if (m_SkipReading)
		{
			// do nothing
		}
		else if (m_Subsect->isOn())
		{
			Point p;
			p.px = m_Xoffset->value();
			p.py = m_Yoffset->value();
			m_Handler3D->ReadRaw(m_NameEdit->text().ascii(), (unsigned short)m_Xlength1->value(), (unsigned short)m_Ylength1->value(), (unsigned)bitdepth, (unsigned short)m_Slicenrbox->value(), (unsigned short)m_SbNrslices->value(), p, (unsigned short)m_Xlength->value(), (unsigned short)m_Ylength->value());
		}
		else
		{
			m_Handler3D->ReadRaw(m_NameEdit->text().ascii(), (unsigned short)m_Xlength1->value(), (unsigned short)m_Ylength1->value(), (unsigned)bitdepth, (unsigned short)m_Slicenrbox->value(), (unsigned short)m_SbNrslices->value());
		}
		close();
		return;
	}
}

void LoaderRaw::SelectPushed()
{
	QString loadfilename = RecentPlaces::GetOpenFileName(this, "Open file", QString::null, QString::null);
	m_NameEdit->setText(loadfilename);
}

ReloaderRaw::ReloaderRaw(SlicesHandler* hand3D, QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags), m_Handler3D(hand3D)
{
	setModal(true);

	m_Vbox1 = new Q3VBox(this);
	m_Hbox1 = new Q3HBox(m_Vbox1);
	m_FileName = new QLabel(QString("File Name: "), m_Hbox1);
	m_NameEdit = new QLineEdit(m_Hbox1);
	m_NameEdit->show();
	m_SelectFile = new QPushButton("Select", m_Hbox1);
	m_SelectFile->show();
	m_Hbox1->show();
	m_Hbox2 = new Q3HBox(m_Vbox1);
	m_Bitselect = new QButtonGroup(this);
	//	bitselect->hide();
	m_Bit8 = new QRadioButton(QString("8-bit"), m_Hbox2);
	m_Bit16 = new QRadioButton(QString("16-bit"), m_Hbox2);
	m_Bitselect->insert(m_Bit8);
	m_Bitselect->insert(m_Bit16);
	m_Bit16->show();
	m_Bit8->setChecked(TRUE);
	m_Bit8->show();
	m_Nrslice = new QLabel(QString("Slice Nr.: "), m_Hbox2);
	m_Slicenrbox = new QSpinBox(0, 200, 1, m_Hbox2);
	m_Slicenrbox->show();
	m_Slicenrbox->setValue(0);
	m_Hbox2->show();
	m_Hbox5 = new Q3HBox(m_Vbox1);
	m_Subsect = new QCheckBox(QString("Subsection "), m_Hbox5);
	m_Subsect->setChecked(false);
	m_Subsect->show();
	m_Vbox2 = new Q3VBox(m_Hbox5);
	m_Hbox4 = new Q3HBox(m_Vbox2);
	m_Xl1 = new QLabel(QString("Total x-Length: "), m_Hbox4);
	m_Xlength1 = new QSpinBox(0, 2000, 1, m_Hbox4);
	m_Xlength1->show();
	m_Xlength1->setValue(512);
	m_Yl1 = new QLabel(QString("Total  y-Length: "), m_Hbox4);
	m_Ylength1 = new QSpinBox(0, 2000, 1, m_Hbox4);
	m_Ylength1->show();
	m_Ylength1->setValue(512);
	m_Hbox4->show();
	m_Hbox3 = new Q3HBox(m_Vbox2);
	m_Xoffs = new QLabel(QString("x-Offset: "), m_Hbox3);
	m_Xoffset = new QSpinBox(0, 2000, 1, m_Hbox3);
	m_Xoffset->setValue(0);
	m_Xoffset->show();
	m_Yoffs = new QLabel(QString("y-Offset: "), m_Hbox3);
	m_Yoffset = new QSpinBox(0, 2000, 1, m_Hbox3);
	m_Yoffset->show();
	m_Xoffset->setValue(0);
	m_Hbox3->show();
	m_Vbox2->show();
	m_Hbox5->show();

	/*	bitselect->insert(bit8);
	bitselect->insert(bit16);*/

	/*	hbox7=new QHBox(vbox1);
	lb_startnr = new QLabel(QString("Start Nr.: "),hbox7);
	sb_startnr=new QSpinBox(0,2000,1,hbox7);
	sb_startnr->setValue(0);
	sb_startnr->show();
	hbox7->show();*/

	m_Hbox6 = new Q3HBox(m_Vbox1);
	m_LoadFile = new QPushButton("Open", m_Hbox6);
	m_CancelBut = new QPushButton("Cancel", m_Hbox6);
	m_Hbox6->show();

	/*	vbox1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	vbox2->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox2->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox3->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox4->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));
	hbox5->setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed));*/
	m_Vbox1->show();
	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

	m_Vbox1->setFixedSize(m_Vbox1->sizeHint());

	SubsectToggled();

	QObject_connect(m_SelectFile, SIGNAL(clicked()), this, SLOT(SelectPushed()));
	QObject_connect(m_LoadFile, SIGNAL(clicked()), this, SLOT(LoadPushed()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(close()));
	QObject_connect(m_Subsect, SIGNAL(clicked()), this, SLOT(SubsectToggled()));
}

ReloaderRaw::~ReloaderRaw()
{
	delete m_Vbox1;
	delete m_Bitselect;
}

void ReloaderRaw::SubsectToggled()
{
	bool isset = m_Subsect->isChecked();
	;
	if (isset)
	{
		m_Vbox2->show();
		//		nameEdit->setText(QString("ABC"));
	}
	else
	{
		m_Vbox2->hide();
		//		nameEdit->setText(QString("DEF"));
	}

	//	vbox1->setFixedSize(vbox1->sizeHint());
}

void ReloaderRaw::LoadPushed()
{
	unsigned bitdepth;
	if (m_Bit8->isChecked())
		bitdepth = 8;
	else
		bitdepth = 16;

	if (!(m_NameEdit->text()).isEmpty())
	{
		if (m_Subsect->isChecked())
		{
			Point p;
			p.px = m_Xoffset->value();
			p.py = m_Yoffset->value();
			m_Handler3D->ReloadRaw(m_NameEdit->text().ascii(), m_Xlength1->value(), m_Ylength1->value(), bitdepth, m_Slicenrbox->value(), p);
		}
		else
		{
			m_Handler3D->ReloadRaw(m_NameEdit->text().ascii(), bitdepth, m_Slicenrbox->value());
		}
		close();
	}
}

void ReloaderRaw::SelectPushed()
{
	// null filter?
	QString loadfilename = RecentPlaces::GetOpenFileName(this, QString::null, QString::null, QString::null);
	m_NameEdit->setText(loadfilename);
}

NewImg::NewImg(SlicesHandler* hand3D, QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags), m_Handler3D(hand3D)
{
	setModal(true);

	m_Vbox1 = new Q3VBox(this);
	m_Hbox2 = new Q3HBox(m_Vbox1);
	m_Xl = new QLabel(QString("Total x-Length: "), m_Hbox2);
	m_Xlength = new QSpinBox(1, 2000, 1, m_Hbox2);
	m_Xlength->show();
	m_Xlength->setValue(512);
	m_Yl = new QLabel(QString("Total  y-Length: "), m_Hbox2);
	m_Ylength = new QSpinBox(1, 2000, 1, m_Hbox2);
	m_Ylength->show();
	m_Ylength->setValue(512);
	m_Hbox2->show();
	m_Hbox1 = new Q3HBox(m_Vbox1);
	m_LbNrslices = new QLabel(QString("# Slices: "), m_Hbox1);
	m_SbNrslices = new QSpinBox(1, 2000, 1, m_Hbox1);
	m_SbNrslices->show();
	m_SbNrslices->setValue(10);
	m_Hbox1->show();
	m_Hbox3 = new Q3HBox(m_Vbox1);
	m_NewFile = new QPushButton("New", m_Hbox3);
	m_CancelBut = new QPushButton("Cancel", m_Hbox3);
	m_Hbox3->show();

	m_Vbox1->show();
	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

	m_Vbox1->setFixedSize(m_Vbox1->sizeHint());

	QObject_connect(m_NewFile, SIGNAL(clicked()), this, SLOT(NewPushed()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(OnClose()));

	m_NewPressed = false;
}

NewImg::~NewImg() { delete m_Vbox1; }

bool NewImg::NewPressed() const { return m_NewPressed; }

void NewImg::NewPushed()
{
	m_Handler3D->UpdateColorLookupTable(nullptr);

	m_Handler3D->Newbmp((unsigned short)m_Xlength->value(), (unsigned short)m_Ylength->value(), (unsigned short)m_SbNrslices->value());
	m_NewPressed = true;
	close();
}

void NewImg::OnClose()
{
	m_NewPressed = false;
	close();
}

LoaderColorImages::LoaderColorImages(SlicesHandler* hand3D, eImageType typ, std::vector<const char*> filenames, QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags), m_Handler3D(hand3D), m_Type(typ), m_MFilenames(filenames)
{
	setModal(true);

	m_MapToLut = new QCheckBox(QString("Map colors to lookup table"));
	m_MapToLut->setChecked(true);
	if (typ == LoaderColorImages::kTIF)
	{
		m_MapToLut->setEnabled(false);
	}

	m_Subsect = new QCheckBox(QString("Subsection"));
	m_Subsect->setChecked(false);

	auto xoffs = new QLabel(QString("x-Offset: "));
	m_Xoffset = new QSpinBox(0, 2000, 1, nullptr);
	m_Xoffset->setValue(0);

	auto yoffs = new QLabel(QString("y-Offset: "));
	m_Yoffset = new QSpinBox(0, 2000, 1, nullptr);
	m_Xoffset->setValue(0);

	auto xl = new QLabel(QString("x-Length: "));
	m_Xlength = new QSpinBox(0, 2000, 1, nullptr);
	m_Xlength->setValue(256);

	auto yl = new QLabel(QString("y-Length: "));
	m_Ylength = new QSpinBox(0, 2000, 1, nullptr);
	m_Ylength->setValue(256);

	auto subsect_layout = new QGridLayout(2, 4);
	subsect_layout->addWidget(xoffs);
	subsect_layout->addWidget(m_Xoffset);
	subsect_layout->addWidget(xl);
	subsect_layout->addWidget(m_Xlength);
	subsect_layout->addWidget(yoffs);
	subsect_layout->addWidget(m_Yoffset);
	subsect_layout->addWidget(yl);
	subsect_layout->addWidget(m_Ylength);
	auto subsect_options = new QWidget;
	subsect_options->setLayout(subsect_layout);

	m_LoadFile = new QPushButton("Open");
	m_CancelBut = new QPushButton("Cancel");
	auto button_layout = new QHBoxLayout;
	button_layout->addWidget(m_LoadFile);
	button_layout->addWidget(m_CancelBut);
	auto button_row = new QWidget;
	button_row->setLayout(button_layout);

	auto top_layout = new QVBoxLayout;
	top_layout->addWidget(m_MapToLut);
	top_layout->addWidget(m_Subsect);
	top_layout->addWidget(subsect_options);
	top_layout->addWidget(button_row);
	setLayout(top_layout);
	setMinimumSize(150, 200);

	MapToLutToggled();

	QObject_connect(m_LoadFile, SIGNAL(clicked()), this, SLOT(LoadPushed()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(close()));
	QObject_connect(m_MapToLut, SIGNAL(clicked()), this, SLOT(MapToLutToggled()));
}

LoaderColorImages::~LoaderColorImages() = default;

void LoaderColorImages::MapToLutToggled()
{
	// enable/disable
	m_Subsect->setEnabled(!m_MapToLut->isChecked());
}

void LoaderColorImages::LoadPushed()
{
	if (m_MapToLut->isChecked())
	{
		LoadQuantize();
	}
	else
	{
		LoadMixer();
	}
}

void LoaderColorImages::LoadQuantize()
{
	QString initial_dir = QString::null;

	auto lut_path = boost::dll::program_location().parent_path() / fs::path("lut");
	if (fs::exists(lut_path))
	{
		fs::directory_iterator dir_itr(lut_path);
		fs::directory_iterator end_iter;
		for (; dir_itr != end_iter; ++dir_itr)
		{
			fs::path lut_file(dir_itr->path());
			if (algo::iends_with(lut_file.string(), ".lut"))
			{
				initial_dir = QString::fromStdString(lut_file.parent_path().string());
				break;
			}
		}
	}

	QString filename = RecentPlaces::GetOpenFileName(this, "Open Lookup Table", initial_dir, "iSEG Color Lookup Table (*.lut *.h5)\nAll (*.*)");
	if (!filename.isEmpty())
	{
		XdmfImageReader reader;
		reader.SetFileName(filename.toStdString().c_str());
		std::shared_ptr<ColorLookupTable> lut;
		{
			ScopedTimer t("Load LUT");
			lut = reader.ReadColorLookup();
		}
		if (lut)
		{
			const auto n = lut->NumberOfColors();

			using color_type = std::array<unsigned char, 3>;
			using color_vector_type = std::vector<color_type>;

			color_vector_type points(n);
			for (size_t i = 0; i < n; ++i)
			{
				lut->GetColor(i, points[i].data());
			}

			using distance_type = float;
			using kd_tree_type = KDTreeVectorOfVectorsAdaptor<color_vector_type, distance_type>;
			kd_tree_type tree(3, points, 10 /* max leaf */);
			{
				ScopedTimer t("Build kd-tree for colors");
				tree.m_Index->buildIndex();
			}

			unsigned w, h;
			if (ImageReader::GetInfo2D(m_MFilenames[0], w, h))
			{
				const auto map_colors = [&tree](unsigned char r, unsigned char g, unsigned char b) -> float {
					size_t id;
					distance_type sqr_dist;
					std::array<distance_type, 3> query_pt = {
							static_cast<distance_type>(r), static_cast<distance_type>(g), static_cast<distance_type>(b)};
					tree.Query(&query_pt[0], 1, &id, &sqr_dist);
					return static_cast<float>(id);
				};

				auto load = [&, this](float** slices) {
					ScopedTimer t("Load and map image stack");
					ImageReader::GetImageStack(m_MFilenames, slices, w, h, map_colors);
				};

				m_Handler3D->Newbmp(w, h, static_cast<unsigned short>(m_MFilenames.size()), load);
				m_Handler3D->UpdateColorLookupTable(lut);
			}
		}
		else
		{
			QMessageBox::warning(this, "iSeg", "ERROR: occurred while reading color lookup table\n", QMessageBox::Ok | QMessageBox::Default);
		}
	}

	close();
}

void LoaderColorImages::LoadMixer()
{
	if ((m_Type == eImageType::kBMP && Bmphandler::CheckBMPDepth(m_MFilenames[0]) > 8) ||
			(m_Type == eImageType::kPNG && Bmphandler::CheckPNGDepth(m_MFilenames[0]) > 8))
	{
		ChannelMixer channel_mixer(m_MFilenames, nullptr);
		channel_mixer.move(QCursor::pos());
		if (!channel_mixer.exec())
		{
			close();
			return;
		}

		int red_factor = channel_mixer.GetRedFactor();
		int green_factor = channel_mixer.GetGreenFactor();
		int blue_factor = channel_mixer.GetBlueFactor();
		m_Handler3D->SetRgbFactors(red_factor, green_factor, blue_factor);
	}
	else
	{
		m_Handler3D->SetRgbFactors(33, 33, 33);
	}

	if (m_Subsect->isChecked())
	{
		Point p;
		p.px = m_Xoffset->value();
		p.py = m_Yoffset->value();

		switch (m_Type)
		{
		case eImageType::kPNG:
			m_Handler3D->LoadPng(m_MFilenames, p, m_Xlength->value(), m_Ylength->value());
			break;
		case eImageType::kBMP:
			m_Handler3D->LoadDIBitmap(m_MFilenames, p, m_Xlength->value(), m_Ylength->value());
			break;
		case eImageType::kJPG:
			m_Handler3D->LoadDIJpg(m_MFilenames, p, m_Xlength->value(), m_Ylength->value());
			break;
		}
	}
	else
	{
		switch (m_Type)
		{
		case eImageType::kPNG:
			m_Handler3D->LoadPng(m_MFilenames);
			break;
		case eImageType::kBMP:
			m_Handler3D->LoadDIBitmap(m_MFilenames);
			break;
		case eImageType::kJPG:
			m_Handler3D->LoadDIJpg(m_MFilenames);
			break;
		}
	}
	close();
}

ClickableLabel::ClickableLabel(QWidget* parent, Qt::WindowFlags f)
		: QLabel(parent, f)
{
	m_CenterX = width() / 2;
	m_CenterY = height() / 2;
	m_SquareWidth = 24;
	m_SquareHeight = 24;
}

ClickableLabel::ClickableLabel(const QString& text, QWidget* parent, Qt::WindowFlags f)
		: QLabel(text, parent, f)
{
}

void ClickableLabel::SetSquareWidth(int width) { m_SquareWidth = width; }

void ClickableLabel::SetSquareHeight(int height) { m_SquareHeight = height; }

void ClickableLabel::SetCenter(QPoint newCenter)
{
	m_CenterX = newCenter.x();
	m_CenterY = newCenter.y();
	emit NewCenterPreview(QPoint(m_CenterX, m_CenterY));
}

void ClickableLabel::mousePressEvent(QMouseEvent* ev)
{
	m_CenterX = ev->pos().x();
	m_CenterY = ev->pos().y();
	emit NewCenterPreview(QPoint(m_CenterX, m_CenterY));
}

void ClickableLabel::paintEvent(QPaintEvent* e)
{
	QLabel::paintEvent(e);

	QPainter painter(this);

	QPen paintpen(Qt::yellow);
	paintpen.setWidth(1);
	painter.setPen(paintpen);

	QPainterPath square;
	square.addRect(m_CenterX - m_SquareHeight / 2, m_CenterY - m_SquareHeight / 2, m_SquareWidth, m_SquareHeight);
	painter.drawPath(square);
}

ChannelMixer::ChannelMixer(std::vector<const char*> filenames, QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags), m_MFilenames(filenames)
{
	setModal(true);

	m_PreviewCenter.setX(0);
	m_PreviewCenter.setY(0);
	QString file_name = QString::fromUtf8(m_MFilenames[0]);
	if (!file_name.isEmpty())
	{
		m_SourceImage = QImage(file_name);
		if (m_SourceImage.isNull())
		{
			QMessageBox::information(this, tr("Image Viewer"), tr("Cannot load %1.").arg(file_name));
			return;
		}
		m_PreviewCenter.setX(m_SourceImage.width());
		m_PreviewCenter.setY(m_SourceImage.height());
	}

	m_RedFactorPv = 30;
	m_GreenFactorPv = 59;
	m_BlueFactorPv = 11;

	m_RedFactor = 30;
	m_GreenFactor = 59;
	m_BlueFactor = 11;

	m_ScaleX = 400;
	m_ScaleY = 500;

	m_VboxMain = new Q3VBox(this);

	m_HboxImageAndControl = new Q3HBox(m_VboxMain);

	QSize standard_box_size;
	standard_box_size.setWidth(m_ScaleX);
	standard_box_size.setHeight(m_ScaleY);

	m_HboxImageSource = new Q3HBox(m_HboxImageAndControl);
	m_HboxImageSource->setFixedSize(standard_box_size);
	m_HboxImageSource->show();
	m_ImageSourceLabel = new ClickableLabel(m_HboxImageSource);
	m_ImageSourceLabel->setFixedSize(standard_box_size);
	m_ImageSourceLabel->SetSquareWidth(25);
	m_ImageSourceLabel->SetSquareHeight(25);
	m_ImageSourceLabel->setAlignment(Qt::AlignCenter);

	m_HboxImage = new Q3HBox(m_HboxImageAndControl);
	m_HboxImage->setFixedSize(standard_box_size);
	m_HboxImage->show();
	m_ImageLabel = new QLabel(m_HboxImage);
	m_ImageLabel->setFixedSize(standard_box_size);

	m_HboxControl = new Q3VBox(m_HboxImageAndControl);

	QSize control_size;
	control_size.setHeight(m_ScaleY);
	control_size.setWidth(m_ScaleX / 2);
	m_HboxControl->setFixedSize(control_size);

	m_HboxChannelOptions = new Q3VBox(m_HboxControl);

	m_VboxRed = new Q3HBox(m_HboxChannelOptions);
	m_VboxGreen = new Q3HBox(m_HboxChannelOptions);
	m_VboxBlue = new Q3HBox(m_HboxChannelOptions);
	m_LabelPreviewAlgorithm = new QLabel(m_HboxChannelOptions);
	m_VboxSlice = new Q3HBox(m_HboxChannelOptions);
	m_HboxButtons = new Q3HBox(m_HboxChannelOptions);

	m_LabelRed = new QLabel(m_VboxRed);
	m_LabelRed->setText("Red");
	m_LabelRed->setFixedWidth(40);
	m_SliderRed = new QSlider(Qt::Horizontal, m_VboxRed);
	m_SliderRed->setMinValue(0);
	m_SliderRed->setMaxValue(100);
	m_SliderRed->setValue(m_RedFactor);
	m_SliderRed->setFixedWidth(80);
	m_LabelRedValue = new QLineEdit(m_VboxRed);
	m_LabelRedValue->setText(QString::number(m_SliderRed->value()));
	m_LabelRedValue->setFixedWidth(30);
	QLabel* label_pure_red = new QLabel(m_VboxRed);
	label_pure_red->setText(" Pure");
	label_pure_red->setFixedWidth(30);
	m_ButtonRed = new QRadioButton(m_VboxRed);
	m_ButtonRed->setChecked(false);

	m_LabelGreen = new QLabel(m_VboxGreen);
	m_LabelGreen->setText("Green");
	m_LabelGreen->setFixedWidth(40);
	m_SliderGreen = new QSlider(Qt::Horizontal, m_VboxGreen);
	m_SliderGreen->setMinValue(0);
	m_SliderGreen->setMaxValue(100);
	m_SliderGreen->setValue(m_GreenFactor);
	m_SliderGreen->setFixedWidth(80);
	m_LabelGreenValue = new QLineEdit(m_VboxGreen);
	m_LabelGreenValue->setText(QString::number(m_SliderGreen->value()));
	m_LabelGreenValue->setFixedWidth(30);
	QLabel* label_pure_green = new QLabel(m_VboxGreen);
	label_pure_green->setText(" Pure");
	label_pure_green->setFixedWidth(30);
	m_ButtonGreen = new QRadioButton(m_VboxGreen);
	m_ButtonGreen->setChecked(false);

	m_LabelBlue = new QLabel(m_VboxBlue);
	m_LabelBlue->setText("Blue");
	m_LabelBlue->setFixedWidth(40);
	m_SliderBlue = new QSlider(Qt::Horizontal, m_VboxBlue);
	m_SliderBlue->setMinValue(0);
	m_SliderBlue->setMaxValue(100);
	m_SliderBlue->setValue(m_BlueFactor);
	m_SliderBlue->setFixedWidth(80);
	m_LabelBlueValue = new QLineEdit(m_VboxBlue);
	m_LabelBlueValue->setText(QString::number(m_SliderBlue->value()));
	m_LabelBlueValue->setFixedWidth(30);
	QLabel* label_pure_blue = new QLabel(m_VboxBlue);
	label_pure_blue->setText(" Pure");
	label_pure_blue->setFixedWidth(30);
	m_ButtonBlue = new QRadioButton(m_VboxBlue);
	m_ButtonBlue->setChecked(false);

	m_LabelSliceValue = new QLabel(m_VboxSlice);
	m_LabelSliceValue->setText("Slice");
	m_LabelSliceValue->setFixedWidth(40);
	m_SpinSlice = new QSpinBox(m_VboxSlice);
	m_SpinSlice->setMinimum(0);
	m_SpinSlice->setMaximum(static_cast<int>(filenames.size()) - 1);
	m_SpinSlice->setValue(0);
	m_SelectedSlice = m_SpinSlice->value();

	m_LoadFile = new QPushButton("Open", m_HboxButtons);
	m_CancelBut = new QPushButton("Cancel", m_HboxButtons);

	m_HboxControl->show();
	m_HboxButtons->show();
	m_VboxMain->show();

	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
	m_VboxMain->setFixedSize(m_VboxMain->sizeHint());

	QObject_connect(m_SliderRed, SIGNAL(valueChanged(int)), this, SLOT(SliderRedValueChanged(int)));
	QObject_connect(m_SliderGreen, SIGNAL(valueChanged(int)), this, SLOT(SliderGreenValueChanged(int)));
	QObject_connect(m_SliderBlue, SIGNAL(valueChanged(int)), this, SLOT(SliderBlueValueChanged(int)));

	QObject_connect(m_LabelRedValue, SIGNAL(textEdited(QString)), this, SLOT(LabelRedValueChanged(QString)));
	QObject_connect(m_LabelGreenValue, SIGNAL(textEdited(QString)), this, SLOT(LabelGreenValueChanged(QString)));
	QObject_connect(m_LabelBlueValue, SIGNAL(textEdited(QString)), this, SLOT(LabelBlueValueChanged(QString)));

	QObject_connect(m_ButtonRed, SIGNAL(toggled(bool)), this, SLOT(ButtonRedPushed(bool)));
	QObject_connect(m_ButtonGreen, SIGNAL(toggled(bool)), this, SLOT(ButtonGreenPushed(bool)));
	QObject_connect(m_ButtonBlue, SIGNAL(toggled(bool)), this, SLOT(ButtonBluePushed(bool)));

	QObject_connect(m_SpinSlice, SIGNAL(valueChanged(int)), this, SLOT(SliceValueChanged(int)));

	QObject_connect(m_LoadFile, SIGNAL(clicked()), this, SLOT(LoadPushed()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(close()));

	QObject_connect(m_ImageSourceLabel, SIGNAL(newCenterPreview(QPoint)), this, SLOT(NewCenterPreview(QPoint)));

	m_FirstTime = true;

	RefreshSourceImage();
	ChangePreview();
}

ChannelMixer::~ChannelMixer() { delete m_VboxMain; }

void ChannelMixer::SliderRedValueChanged(int value)
{
	m_RedFactor = value;
	m_LabelRedValue->setText(QString::number(value));

	ChangePreview();
}

void ChannelMixer::SliderGreenValueChanged(int value)
{
	m_GreenFactor = value;
	m_LabelGreenValue->setText(QString::number(value));

	ChangePreview();
}

void ChannelMixer::SliderBlueValueChanged(int value)
{
	m_BlueFactor = value;
	m_LabelBlueValue->setText(QString::number(value));

	ChangePreview();
}

void ChannelMixer::LabelRedValueChanged(QString text)
{
	m_RedFactor = text.toInt();
	m_SliderRed->setValue(m_RedFactor);

	ChangePreview();
}

void ChannelMixer::LabelGreenValueChanged(QString text)
{
	m_GreenFactor = text.toInt();
	m_SliderGreen->setValue(m_GreenFactor);

	ChangePreview();
}

void ChannelMixer::LabelBlueValueChanged(QString text)
{
	m_BlueFactor = text.toInt();
	m_SliderBlue->setValue(m_BlueFactor);

	ChangePreview();
}

void ChannelMixer::ButtonRedPushed(bool checked)
{
	if (checked)
	{
		m_SliderRed->setValue(100);
		m_SliderGreen->setValue(0);
		m_SliderBlue->setValue(0);

		m_ButtonGreen->setChecked(false);
		m_ButtonBlue->setChecked(false);
	}
}

void ChannelMixer::ButtonGreenPushed(bool checked)
{
	if (checked)
	{
		m_SliderRed->setValue(0);
		m_SliderGreen->setValue(100);
		m_SliderBlue->setValue(0);

		m_ButtonRed->setChecked(false);
		m_ButtonBlue->setChecked(false);
	}
}
void ChannelMixer::ButtonBluePushed(bool checked)
{
	if (checked)
	{
		m_SliderRed->setValue(0);
		m_SliderGreen->setValue(0);
		m_SliderBlue->setValue(100);

		m_ButtonRed->setChecked(false);
		m_ButtonGreen->setChecked(false);
	}
}

void ChannelMixer::SliceValueChanged(int value)
{
	m_SelectedSlice = value;

	RefreshSourceImage();
}

void ChannelMixer::NewCenterPreview(QPoint newCenter)
{
	double image_width = m_SourceImage.width();
	double image_height = m_SourceImage.height();

	bool fixed_in_height = true;
	double scaled_factor = 1;
	if (image_height / image_width < m_ScaleY / m_ScaleX)
		fixed_in_height = false;

	int correction_x = 0;
	int correction_y = 0;
	if (fixed_in_height)
	{
		scaled_factor = image_height / m_ScaleY;
		correction_x = (image_width - m_ScaleX * scaled_factor) / 2;
	}
	else
	{
		scaled_factor = image_width / m_ScaleX;
		correction_y = (m_ScaleY * scaled_factor - image_height) / 2;
	}

	m_PreviewCenter.setX(scaled_factor * newCenter.x() + correction_x);
	m_PreviewCenter.setY(image_height -
											 (scaled_factor * newCenter.y() - correction_y));

	RefreshSourceImage();
	//RefreshImage();
}

void ChannelMixer::ChangePreview()
{
	if ((m_RedFactor != 0) + (m_GreenFactor != 0) + (m_BlueFactor != 0) > 1)
	{
		m_ButtonRed->setChecked(false);
		m_ButtonGreen->setChecked(false);
		m_ButtonBlue->setChecked(false);
	}

	int total_factor = m_RedFactor + m_GreenFactor + m_BlueFactor;
	double normalize = total_factor / 100.0;

	if (normalize == 0)
	{
		m_RedFactorPv = 33;
		m_GreenFactorPv = 33;
		m_BlueFactorPv = 33;
	}
	else
	{
		m_RedFactorPv = m_RedFactor / normalize;
		m_GreenFactorPv = m_GreenFactor / normalize;
		m_BlueFactorPv = m_BlueFactor / normalize;
	}

	UpdateText();
	RefreshImage();
}

void ChannelMixer::RefreshSourceImage()
{
	QString file_name = QString::fromUtf8(m_MFilenames[m_SelectedSlice]);
	QImage small_image;
	if (!file_name.isEmpty())
	{
		m_SourceImage = QImage(file_name);
		if (m_SourceImage.isNull())
		{
			QMessageBox::information(this, tr("Image Viewer"), tr("Cannot load %1.").arg(file_name));
			return;
		}

		small_image = m_SourceImage.scaled(m_ScaleX, m_ScaleY, Qt::KeepAspectRatio);

		m_ImageSourceLabel->setPixmap(QPixmap::fromImage(small_image));
		m_ImageSourceLabel->update();
	}
	m_HboxImageSource->update();

	if (m_FirstTime)
	{
		m_FirstTime = false;

		double image_source_width = m_SourceImage.width();
		double image_source_height = m_SourceImage.height();

		m_PreviewCenter.setX(image_source_width / 2);
		m_PreviewCenter.setY(image_source_height / 2);

		double small_image_width = small_image.width();
		double small_image_height = small_image.height();

		bool fixed_in_height = true;
		double scaled_factor = 1;
		if (image_source_height / image_source_width < m_ScaleY / m_ScaleX)
			fixed_in_height = false;

		if (fixed_in_height)
			scaled_factor = image_source_height / m_ScaleY;
		else
			scaled_factor = image_source_width / m_ScaleX;

		int square_width;
		if (image_source_width > 900 || image_source_height > 900)
			square_width = 300;
		else
		{
			square_width = std::min(image_source_width / 3, image_source_height / 3);
		}

		m_WidthPv = m_HeightPv = square_width;

		m_ImageSourceLabel->SetSquareWidth(square_width / scaled_factor);
		m_ImageSourceLabel->SetSquareHeight(square_width / scaled_factor);

		int small_image_center_x = small_image_width / 2;
		int small_image_center_y = small_image_height / 2;
		int small_image_center_square_half_side = square_width / scaled_factor / 2;
		small_image_center_square_half_side = 0;
		m_ImageSourceLabel->SetCenter(QPoint(small_image_center_x, small_image_center_y + small_image_center_square_half_side));
	}

	RefreshImage();
}

void ChannelMixer::RefreshImage()
{
	QString file_name = QString::fromUtf8(m_MFilenames[m_SelectedSlice]);
	if (!file_name.isEmpty())
	{
		QImage image(file_name);
		if (image.isNull())
		{
			QMessageBox::information(this, tr("Image Viewer"), tr("Cannot load %1.").arg(file_name));
			return;
		}

		QImage converted = ConvertImageTo8BitBMP(image, m_WidthPv, m_HeightPv);
		m_ImageLabel->clear();
		m_ImageLabel->setPixmap(QPixmap::fromImage(converted.scaled(m_ScaleX, m_ScaleY, Qt::KeepAspectRatio)));
		m_ImageLabel->update();
	}
	m_HboxImage->update();
}

QImage ChannelMixer::ConvertImageTo8BitBMP(QImage image, int width, int height)
{
	/* Convert RGB image to grayscale image */
	QImage converted_image(width, height, QImage::Format::Format_Indexed8);

	QVector<QRgb> table(256);
	for (int h = 0; h < 256; ++h)
	{
		table[h] = qRgb(h, h, h);
	}
	converted_image.setColorTable(table);

	int start_x = m_PreviewCenter.x() - (width / 2);
	int start_y = m_SourceImage.height() - (m_PreviewCenter.y() + (height / 2));

	QRect rect(start_x, start_y, width, height);
	QImage cropped = image.copy(rect);

	for (int j = 2; j < height - 2; j++)
	{
		for (int i = 2; i < width - 2; i++)
		{
			QRgb rgb = cropped.pixel(i, j);
			int gray_value = qRed(rgb) * (m_RedFactorPv / 100.00) +
											 qGreen(rgb) * (m_GreenFactorPv / 100.00) +
											 qBlue(rgb) * (m_BlueFactorPv / 100.00);
			converted_image.setPixel(i, j, gray_value);
		}
	}

	return converted_image;
}

void ChannelMixer::UpdateText()
{
	m_LabelPreviewAlgorithm->setText("GrayScale = " + QString::number(m_RedFactorPv) + "*R + " +
																	 QString::number(m_GreenFactorPv) + "*G + " +
																	 QString::number(m_BlueFactorPv) + "*B");
}

void ChannelMixer::CancelToggled()
{
	m_RedFactorPv = 30;
	m_GreenFactorPv = 59;
	m_BlueFactorPv = 11;

	m_VboxMain->hide();
}

int ChannelMixer::GetRedFactor() const { return m_RedFactorPv; }

int ChannelMixer::GetGreenFactor() const { return m_GreenFactorPv; }

int ChannelMixer::GetBlueFactor() const { return m_BlueFactorPv; }

void ChannelMixer::LoadPushed()
{
	close();
}

ReloaderBmp2::ReloaderBmp2(SlicesHandler* hand3D, std::vector<const char*> filenames, QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags), m_Handler3D(hand3D), m_MFilenames(filenames)
{
	setModal(true);

	m_Vbox1 = new Q3VBox(this);
	m_Hbox2 = new Q3HBox(m_Vbox1);
	m_Subsect = new QCheckBox(QString("Subsection "), m_Hbox2);
	m_Subsect->setChecked(false);
	m_Subsect->show();
	m_Xoffs = new QLabel(QString("x-Offset: "), m_Hbox2);
	m_Xoffset = new QSpinBox(0, 2000, 1, m_Hbox2);
	m_Xoffset->setValue(0);
	m_Xoffset->show();
	m_Yoffs = new QLabel(QString("y-Offset: "), m_Hbox2);
	m_Yoffset = new QSpinBox(0, 2000, 1, m_Hbox2);
	m_Yoffset->show();
	m_Xoffset->setValue(0);
	m_Hbox2->show();
	m_Hbox3 = new Q3HBox(m_Vbox1);
	m_LoadFile = new QPushButton("Open", m_Hbox3);
	m_CancelBut = new QPushButton("Cancel", m_Hbox3);
	m_Hbox3->show();

	m_Vbox1->show();
	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

	m_Vbox1->setFixedSize(m_Vbox1->sizeHint());

	SubsectToggled();

	QObject_connect(m_LoadFile, SIGNAL(clicked()), this, SLOT(LoadPushed()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(close()));
	QObject_connect(m_Subsect, SIGNAL(clicked()), this, SLOT(SubsectToggled()));
}

ReloaderBmp2::~ReloaderBmp2() { delete m_Vbox1; }

void ReloaderBmp2::SubsectToggled()
{
	bool isset = m_Subsect->isChecked();
	;
	if (isset)
	{
		m_Xoffset->show();
		m_Yoffs->show();
		m_Yoffset->show();
		m_Yoffs->show();
	}
	else
	{
		m_Xoffset->hide();
		m_Xoffs->hide();
		m_Yoffset->hide();
		m_Yoffs->hide();
	}
}

void ReloaderBmp2::LoadPushed()
{
	if (m_Subsect->isChecked())
	{
		Point p;
		p.px = m_Xoffset->value();
		p.py = m_Yoffset->value();
		m_Handler3D->ReloadDIBitmap(m_MFilenames, p);
	}
	else
	{
		m_Handler3D->ReloadDIBitmap(m_MFilenames);
	}
	close();
}

EditText::EditText(QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags)
{
	setModal(true);

	m_Vbox1 = new Q3VBox(this);

	m_Hbox1 = new Q3HBox(m_Vbox1);
	m_TextEdit = new QLineEdit(m_Hbox1);

	m_Hbox2 = new Q3HBox(m_Vbox1);
	m_SaveBut = new QPushButton("Save", m_Hbox2);
	m_CancelBut = new QPushButton("Cancel", m_Hbox2);

	setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

	m_Vbox1->setFixedSize(200, 50);

	QObject_connect(m_SaveBut, SIGNAL(clicked()), this, SLOT(accept()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(reject()));
}

EditText::~EditText() { delete m_Vbox1; }

void EditText::SetEditableText(QString editable_text)
{
	m_TextEdit->setText(editable_text);
}

QString EditText::GetEditableText() { return m_TextEdit->text(); }

SupportedMultiDatasetTypes::SupportedMultiDatasetTypes(QWidget* parent, Qt::WindowFlags wFlags)
		: QDialog(parent, wFlags)
{
	setModal(true);

	// widgets
	auto radio_group_box = new QGroupBox("Supported types");
	for (int i = 0; i < eSupportedTypes::keSupportedTypesSize; i++)
	{
		m_RadioButs.push_back(new QRadioButton(ToQString(eSupportedTypes(i))));
	}

	m_SelectBut = new QPushButton("Select");
	m_CancelBut = new QPushButton("Cancel");

	// layout
	auto radio_layout = new QVBoxLayout;
	for (auto rb : m_RadioButs)
	{
		radio_layout->addWidget(rb);
	}
	radio_group_box->setLayout(radio_layout);

	auto buttons_layout = new QHBoxLayout;
	buttons_layout->addWidget(m_SelectBut);
	buttons_layout->addWidget(m_CancelBut);

	auto vbox_overall = new QVBoxLayout;
	vbox_overall->addWidget(radio_group_box);
	vbox_overall->addLayout(buttons_layout);

	setLayout(vbox_overall);

	setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);

	// connections
	QObject_connect(m_SelectBut, SIGNAL(clicked()), this, SLOT(accept()));
	QObject_connect(m_CancelBut, SIGNAL(clicked()), this, SLOT(reject()));
}

int SupportedMultiDatasetTypes::GetSelectedType()
{
	for (int i = 0; i < m_RadioButs.size(); i++)
	{
		if (m_RadioButs.at(i)->isChecked())
		{
			return i;
		}
	}
	return -1;
}

} // namespace iseg

max_stars_repo_name: ITISFoundation/osparc-iseg

max_issues_repo_name: dyollb/osparc-iseg

max_forks_repo_name: dyollb/osparc-iseg


text:
#include <rows/csv.h>
#include <rows/tuple_utils.h>
#include <rows/tuple_utils.h>
#include <boost/iterator/iterator_facade.hpp>
#include <memory>
#include <stdexcept>
#include <iostream>

using namespace std;
using namespace rows;

struct Foo{
  template<typename T>
  void operator()(size_t ind,T&&t){
    cout<<"["<<ind<<", "<<std::forward<T>(t)<<"]";
  }
};
template<typename T>
struct Bar{
  template<size_t Ind>
  void apply(size_t size){
    cout<<"["<<Ind<<", "<<size<<"]";
  }
};
// main test program
int main(){
  // test2
  auto db=make_shared<csv::stream_db>(cin,',');
  auto stmt=db->createInputStatement(":3:2:1",1);
  auto rs=stmt->execute();
  int cnt=0;
  size_t ncols=rs->ncols();
  while(rs->next()){
    cout<<"row: "<<cnt<<": [";
    for(size_t i=0;i<ncols;++i){
      auto const&v=rs->get<optional<int>>(i);
      if(v)cout<<rs->get<optional<int>>(i).value();
      else cout<<"null";
      if(i<ncols-1)cout<<", ";
    }
    cout<<"]"<<endl;
  }
}

ext: cc

max_stars_repo_name: hansewetz/rows

max_issues_repo_name: hansewetz/rows

max_forks_repo_name: hansewetz/rows


text:
// Open Close Principle

/*
   The system must be open for extention, and close for modification

    * avoid to jump in to code we already written
*/

#include <boost/lexical_cast.hpp>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;
using namespace boost;

enum class Color { red, green, blue };
enum class Size { small, medium, large };

struct Product {
  string name;
  Color color;
  Size size;
};

/*
    This kind of approach does no scale
    You have to keep modifying the Productfilter to add new filters
*/
struct Productfilter {
  vector<Product *> by_color(vector<Product *> &items, Color color) {
    vector<Product *> result;
    for (auto &i : items)
      if (i->color == color)
        result.push_back(i);
    return result;
  }

  vector<Product *> by_size(vector<Product *> &items, Size size) {
    vector<Product *> result;
    for (auto &i : items)
      if (i->size == size)
        result.push_back(i);
    return result;
  }

  vector<Product *> by_size_and_color(vector<Product *> &items, Size size,
                                      Color color) {
    vector<Product *> result;
    for (auto &i : items)
      if (i->color == color && i->size == size)
        result.push_back(i);
    return result;
  }
};

/*
   The goal is to make the code easy to extend

   implementation of a better filter using the specification pattern
*/

// base specification interface, can be used with any type of item
template <typename T> struct Specification {
  virtual bool is_satisfied(T *item) = 0;
};

// base filter interface, can be used with any type of item and specification
template <typename T> struct Filter {
  virtual vector<T *> filter(vector<T *> items, Specification<T> &spec) = 0;
};

/*
    the Filter implementation is a filter of Product named of BetterFilter

*/
struct BetterFilter : Filter<Product> {
  vector<Product *> filter(vector<Product *> items,
                           Specification<Product> &spec) override {
    vector<Product *> result;
    for (auto &item : items)
      if (spec.is_satisfied(item))
        result.push_back(item);

    return result;
  }
};

struct ColorSpecification : Specification<Product> {
  Color color;
  explicit ColorSpecification(Color color) : color(color) {}

  bool is_satisfied(Product *item) override { return item->color == color; }
};

struct SizeSpecification : Specification<Product> {
  Size size;
  explicit SizeSpecification(Size size) : size(size) {}

  bool is_satisfied(Product *item) override { return item->size == size; }
};

/*
    combinators to combine different Specifications
*/
template <typename T> struct AndSpecification : Specification<T> {
  Specification<T> &first;
  Specification<T> &second;

  AndSpecification(Specification<T> &first, Specification<T> &second)
      : first(first), second(second) {}

  bool is_satisfied(T *item) override {
    return first.is_satisfied(item) && second.is_satisfied(item);
  }
};

int main() {
  Product apple{"Apple", Color::green, Size::small};
  Product tree{"Tree", Color::green, Size::large};
  Product house{"House", Color::blue, Size::large};

  vector<Product *> items{&apple, &tree, &house};

  //   Productfilter pf;
  //   auto green_things = pf.by_color(items, Color::green);
  //   for (auto item : green_things)
  //     cout << item->name << " is green\n";

  BetterFilter bf;
  ColorSpecification green(Color::green);

  for (auto &item : bf.filter(items, green))
    cout << item->name << " is green\n";

  SizeSpecification large(Size::large);
  AndSpecification<Product> green_and_large(green, large);

  for (auto &item : bf.filter(items, green_and_large))
    cout << item->name << " is green and large\n";

  return 0;
}


text:
//
// Created by int3 on 14.02.19.
//

#include "config.h"

#include <src/util/encoding.h>

#include <fstream>
#include <cassert>
#include <sstream>
#include <iostream>
#include <limits>
#include <regex>
#include <map>
#include <cctype>

#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>

#include <fmt/format.h>

// raw enums
enum ID_SPACE {
	ID_SPACE_ESSENCE	= 0,
	ID_SPACE_ADDON		= 1,
	ID_SPACE_TALK		= 2,
	ID_SPACE_FACE		= 3,
	ID_SPACE_RECIPE		= 4,
	ID_SPACE_CONFIG		= 5,
};

enum DATA_TYPE {
	DT_INVALID					= 0,
	DT_EQUIPMENT_ADDON			,
	DT_WEAPON_MAJOR_TYPE		,
	DT_WEAPON_SUB_TYPE			,
	DT_WEAPON_ESSENCE			,

	DT_ARMOR_MAJOR_TYPE			,
	DT_ARMOR_SUB_TYPE			,
	DT_ARMOR_ESSENCE			,
	DT_DECORATION_MAJOR_TYPE	,
	DT_DECORATION_SUB_TYPE		,

	DT_DECORATION_ESSENCE		= 10,
	DT_MEDICINE_MAJOR_TYPE		,
	DT_MEDICINE_SUB_TYPE		,
	DT_MEDICINE_ESSENCE			,
	DT_MATERIAL_MAJOR_TYPE		,

	DT_MATERIAL_SUB_TYPE		,
	DT_MATERIAL_ESSENCE			,
	DT_DAMAGERUNE_SUB_TYPE		,
	DT_DAMAGERUNE_ESSENCE		,
	DT_ARMORRUNE_SUB_TYPE		,

	DT_ARMORRUNE_ESSENCE		= 20,
	DT_SKILLTOME_SUB_TYPE		,
	DT_SKILLTOME_ESSENCE		,
	DT_FLYSWORD_ESSENCE			,
	DT_WINGMANWING_ESSENCE		,

	DT_TOWNSCROLL_ESSENCE		,
	DT_UNIONSCROLL_ESSENCE		,
	DT_REVIVESCROLL_ESSENCE		,
	DT_ELEMENT_ESSENCE			,
	DT_TASKMATTER_ESSENCE		,

	DT_TOSSMATTER_ESSENCE		= 30,
	DT_PROJECTILE_TYPE			,
	DT_PROJECTILE_ESSENCE		,
	DT_QUIVER_SUB_TYPE			,
	DT_QUIVER_ESSENCE			,

	DT_STONE_SUB_TYPE			,
	DT_STONE_ESSENCE			,
	DT_MONSTER_ADDON			,
	DT_MONSTER_TYPE				,
	DT_MONSTER_ESSENCE			,

	DT_NPC_TALK_SERVICE			= 40,
	DT_NPC_SELL_SERVICE			,
	DT_NPC_BUY_SERVICE			,
	DT_NPC_REPAIR_SERVICE		,
	DT_NPC_INSTALL_SERVICE		,

	DT_NPC_UNINSTALL_SERVICE	,
	DT_NPC_TASK_IN_SERVICE		,
	DT_NPC_TASK_OUT_SERVICE		,
	DT_NPC_TASK_MATTER_SERVICE	,
	DT_NPC_SKILL_SERVICE		,

	DT_NPC_HEAL_SERVICE			= 50,
	DT_NPC_TRANSMIT_SERVICE		,
	DT_NPC_TRANSPORT_SERVICE	,
	DT_NPC_PROXY_SERVICE		,
	DT_NPC_STORAGE_SERVICE		,

	DT_NPC_MAKE_SERVICE			,
	DT_NPC_DECOMPOSE_SERVICE	,
	DT_NPC_TYPE					,
	DT_NPC_ESSENCE				,
	DT_TALK_PROC				,

	DT_FACE_TEXTURE_ESSENCE		= 60,
	DT_FACE_SHAPE_ESSENCE		,
	DT_FACE_EMOTION_TYPE		,
	DT_FACE_EXPRESSION_ESSENCE	,
	DT_FACE_HAIR_ESSENCE		,

	DT_FACE_MOUSTACHE_ESSENCE	,
	DT_COLORPICKER_ESSENCE		,
	DT_CUSTOMIZEDATA_ESSENCE	,
	DT_RECIPE_MAJOR_TYPE		,
	DT_RECIPE_SUB_TYPE			,

	DT_RECIPE_ESSENCE			= 70,
	DT_ENEMY_FACTION_CONFIG		,
	DT_CHARRACTER_CLASS_CONFIG	,
	DT_PARAM_ADJUST_CONFIG		,
	DT_PLAYER_ACTION_INFO_CONFIG,

	DT_TASKDICE_ESSENCE			= 75,
	DT_TASKNORMALMATTER_ESSENCE	,
	DT_FACE_FALING_ESSENCE		,
	DT_PLAYER_LEVELEXP_CONFIG	,
	DT_MINE_TYPE,

	DT_MINE_ESSENCE				= 80,
	DT_NPC_IDENTIFY_SERVICE		,
	DT_FASHION_MAJOR_TYPE		,
	DT_FASHION_SUB_TYPE			,
	DT_FASHION_ESSENCE			,

	DT_FACETICKET_MAJOR_TYPE	= 85,
	DT_FACETICKET_SUB_TYPE,
	DT_FACETICKET_ESSENCE,
	DT_FACEPILL_MAJOR_TYPE,
	DT_FACEPILL_SUB_TYPE,

	DT_FACEPILL_ESSENCE			= 90,
	DT_SUITE_ESSENCE,
	DT_GM_GENERATOR_TYPE,
	DT_GM_GENERATOR_ESSENCE,
	DT_PET_TYPE,

	DT_PET_ESSENCE				= 95,
	DT_PET_EGG_ESSENCE,
	DT_PET_FOOD_ESSENCE,
	DT_PET_FACETICKET_ESSENCE,
	DT_FIREWORKS_ESSENCE,

	DT_WAR_TANKCALLIN_ESSENCE	= 100,
	DT_NPC_WAR_TOWERBUILD_SERVICE,
	DT_PLAYER_SECONDLEVEL_CONFIG,
	DT_NPC_RESETPROP_SERVICE,
	DT_NPC_PETNAME_SERVICE,

	DT_NPC_PETLEARNSKILL_SERVICE  = 105,
	DT_NPC_PETFORGETSKILL_SERVICE,
	DT_SKILLMATTER_ESSENCE,
	DT_REFINE_TICKET_ESSENCE,
	DT_DESTROYING_ESSENCE,

	DT_NPC_EQUIPBIND_SERVICE	  = 110,
	DT_NPC_EQUIPDESTROY_SERVICE,
	DT_NPC_EQUIPUNDESTROY_SERVICE,
	DT_BIBLE_ESSENCE,
	DT_SPEAKER_ESSENCE,

	DT_AUTOHP_ESSENCE			  = 115,
	DT_AUTOMP_ESSENCE,
	DT_DOUBLE_EXP_ESSENCE,
	DT_TRANSMITSCROLL_ESSENCE,
	DT_DYE_TICKET_ESSENCE,

	DT_GOBLIN_ESSENCE			= 120,
	DT_GOBLIN_EQUIP_TYPE,
	DT_GOBLIN_EQUIP_ESSENCE,
	DT_GOBLIN_EXPPILL_ESSENCE,
	DT_SELL_CERTIFICATE_ESSENCE,

	DT_TARGET_ITEM_ESSENCE		= 125,
	DT_LOOK_INFO_ESSENCE,
	DT_UPGRADE_PRODUCTION_CONFIG,
	DT_ACC_STORAGE_BLACKLIST_CONFIG,
	DT_FACE_HAIR_TEXTURE_MAP,

	DT_MULTI_EXP_CONFIG         = 130,
	DT_INC_SKILL_ABILITY_ESSENCE,
	DT_GOD_EVIL_CONVERT_CONFIG,
	DT_WEDDING_CONFIG,
	DT_WEDDING_BOOKCARD_ESSENCE,

	DT_WEDDING_INVITECARD_ESSENCE	=	135,
	DT_SHARPENER_ESSENCE,
	DT_FACE_THIRDEYE_ESSENCE,
	DT_FACTION_FORTRESS_CONFIG,
	DT_FACTION_BUILDING_SUB_TYPE,

	DT_FACTION_BUILDING_ESSENCE	=	140,
	DT_FACTION_MATERIAL_ESSENCE,
	DT_CONGREGATE_ESSENCE,
	DT_ENGRAVE_MAJOR_TYPE,
	DT_ENGRAVE_SUB_TYPE,

	DT_ENGRAVE_ESSENCE	= 145,
	DT_NPC_ENGRAVE_SERVICE,
	DT_NPC_RANDPROP_SERVICE,
	DT_RANDPROP_TYPE,
	DT_RANDPROP_ESSENCE,

	DT_WIKI_TABOO_CONFIG = 150,
	DT_FORCE_CONFIG,
	DT_FORCE_TOKEN_ESSENCE,
	DT_NPC_FORCE_SERVICE,
	DT_PLAYER_DEATH_DROP_CONFIG,

	DT_DYNSKILLEQUIP_ESSENCE = 155,
	DT_CONSUME_POINTS_CONFIG,
	DT_ONLINE_AWARDS_CONFIG,
	DT_COUNTRY_CONFIG,
	DT_GM_ACTIVITY_CONFIG,

	DT_FASHION_WEAPON_CONFIG = 160,
	DT_PET_EVOLVE_CONFIG,
	DT_PET_EVOLVED_SKILL_CONFIG,
	DT_MONEY_CONVERTIBLE_ESSENCE,
	DT_STONE_CHANGE_RECIPE_TYPE,

	DT_STONE_CHANGE_RECIPE = 165,
	DT_MERIDIAN_CONFIG,
	DT_PET_EVOLVED_SKILL_RAND_CONFIG,
	DT_AUTOTASK_DISPLAY_CONFIG,
	DT_TOUCH_SHOP_CONFIG,

	DT_TITLE_CONFIG,
	DT_COMPLEX_TITLE_CONFIG,
	DT_MONSTER_SPIRIT_ESSENCE,
	DT_PLAYER_SPIRIT_CONFIG,
	DT_PLAYER_REINCARNATION_CONFIG,

	DT_HISTORY_STAGE_CONFIG,
	DT_HISTORY_ADVANCE_CONFIG,
	DT_AUTOTEAM_CONFIG,
	DT_PLAYER_REALM_CONFIG,
	DT_CHARIOT_CONFIG,

	DT_CHARIOT_WAR_CONFIG,
	DT_POKER_LEVELEXP_CONFIG,
	DT_POKER_SUITE_ESSENCE,
	DT_POKER_DICE_ESSENCE,
	DT_POKER_SUB_TYPE,

	DT_POKER_ESSENCE,
	DT_TOKEN_SHOP_CONFIG,
	DT_SHOP_TOKEN_ESSENCE,
	DT_GT_CONFIG,
	DT_RAND_SHOP_CONFIG,

	DT_PROFIT_TIME_CONFIG,
	DT_FACTION_PVP_CONFIG,
	DT_UNIVERSAL_TOKEN_ESSENCE,
	DT_TASK_LIST_CONFIG,
	DT_TASK_DICE_BY_WEIGHT_CONFIG,

	DT_FASHION_SUITE_ESSENCE,
	DT_FASHION_BEST_COLOR_CONFIG,
	DT_SIGN_AWARD_CONFIG,
	DT_ASTROLABE_ESSENCE,
	DT_ASTROLABE_RANDOM_ADDON_ESSENCE,

	DT_ASTROLABE_INC_INNER_POINT_VALUE_ESSENCE,
	DT_ASTROLABE_INC_EXP_ESSENCE,
	DT_ITEM_PACKAGE_BY_PROFESSION_ESSENCE,
	DT_ASTROLABE_LEVELEXP_CONFIG,
	DT_ASTROLABE_ADDON_RANDOM_CONFIG,

	DT_ASTROLABE_APPEARANCE_CONFIG,
	DT_EQUIP_MAKE_HOLE_CONFIG,
	DT_SOLO_TOWER_CHALLENGE_LEVEL_CONFIG,
	DT_SOLO_TOWER_CHALLENGE_AWARD_PAGE_CONFIG,
	DT_SOLO_TOWER_CHALLENGE_AWARD_LIST_CONFIG,

	DT_SOLO_TOWER_CHALLENGE_SCORE_COST_CONFIG,
	DT_MNFACTION_WAR_CONFIG,
	DT_NPC_CROSS_SERVER_SERVICE,
	DT_FIREWORKS2_ESSENCE,
	DT_FIX_POSITION_TRANSMIT_ESSENCE,

	DT_MAX,

};

elements::space_id dt_to_space(elements::data_type dt) {
	static const std::map<DATA_TYPE, ID_SPACE> _ {
		{ DT_EQUIPMENT_ADDON, ID_SPACE_ADDON },
		{ DT_WEAPON_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_WEAPON_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_WEAPON_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ARMOR_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_ARMOR_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_ARMOR_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_DECORATION_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_DECORATION_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_DECORATION_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_MEDICINE_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_MEDICINE_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_MEDICINE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_MATERIAL_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_MATERIAL_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_MATERIAL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_DAMAGERUNE_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_DAMAGERUNE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ARMORRUNE_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_ARMORRUNE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_SKILLTOME_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_SKILLTOME_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_SHOP_TOKEN_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_UNIVERSAL_TOKEN_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FASHION_SUITE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ASTROLABE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ASTROLABE_RANDOM_ADDON_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ASTROLABE_INC_INNER_POINT_VALUE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ASTROLABE_INC_EXP_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ITEM_PACKAGE_BY_PROFESSION_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FACTION_BUILDING_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_FACTION_BUILDING_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FACTION_MATERIAL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FLYSWORD_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_WINGMANWING_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_TOWNSCROLL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_TRANSMITSCROLL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_UNIONSCROLL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_REVIVESCROLL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_ELEMENT_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_TASKMATTER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_TOSSMATTER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_PROJECTILE_TYPE, ID_SPACE_ESSENCE },
		{ DT_PROJECTILE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_QUIVER_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_QUIVER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_STONE_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_STONE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_MONSTER_ADDON, ID_SPACE_ADDON },
		{ DT_MONSTER_TYPE, ID_SPACE_ESSENCE },
		{ DT_MONSTER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_NPC_TALK_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_SELL_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_BUY_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_REPAIR_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_INSTALL_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_UNINSTALL_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_TASK_IN_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_TASK_OUT_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_TASK_MATTER_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_SKILL_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_HEAL_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_TRANSMIT_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_TRANSPORT_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_PROXY_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_STORAGE_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_MAKE_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_DECOMPOSE_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_TYPE, ID_SPACE_ESSENCE },
		{ DT_NPC_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_TALK_PROC, ID_SPACE_TALK },
		{ DT_FACE_TEXTURE_ESSENCE, ID_SPACE_FACE },
		{ DT_FACE_SHAPE_ESSENCE, ID_SPACE_FACE },
		{ DT_FACE_EMOTION_TYPE, ID_SPACE_FACE },
		{ DT_FACE_EXPRESSION_ESSENCE, ID_SPACE_FACE },
		{ DT_FACE_HAIR_ESSENCE, ID_SPACE_FACE },
		{ DT_FACE_MOUSTACHE_ESSENCE, ID_SPACE_FACE },
		{ DT_COLORPICKER_ESSENCE, ID_SPACE_FACE },
		{ DT_CUSTOMIZEDATA_ESSENCE, ID_SPACE_FACE },
		{ DT_RECIPE_MAJOR_TYPE, ID_SPACE_RECIPE },
		{ DT_RECIPE_SUB_TYPE, ID_SPACE_RECIPE },
		{ DT_RECIPE_ESSENCE, ID_SPACE_RECIPE },
		{ DT_ENGRAVE_MAJOR_TYPE, ID_SPACE_RECIPE },
		{ DT_ENGRAVE_SUB_TYPE, ID_SPACE_RECIPE },
		{ DT_ENGRAVE_ESSENCE, ID_SPACE_RECIPE },
		{ DT_RANDPROP_TYPE, ID_SPACE_RECIPE },
		{ DT_RANDPROP_ESSENCE, ID_SPACE_RECIPE },
		{ DT_STONE_CHANGE_RECIPE_TYPE, ID_SPACE_RECIPE },
		{ DT_STONE_CHANGE_RECIPE, ID_SPACE_RECIPE },
		{ DT_ENEMY_FACTION_CONFIG, ID_SPACE_CONFIG },
		{ DT_CHARRACTER_CLASS_CONFIG, ID_SPACE_CONFIG },
		{ DT_PARAM_ADJUST_CONFIG, ID_SPACE_CONFIG },
		{ DT_PLAYER_ACTION_INFO_CONFIG, ID_SPACE_CONFIG },
		{ DT_UPGRADE_PRODUCTION_CONFIG, ID_SPACE_CONFIG },
		{ DT_ACC_STORAGE_BLACKLIST_CONFIG, ID_SPACE_CONFIG },
		{ DT_PLAYER_DEATH_DROP_CONFIG, ID_SPACE_CONFIG },
		{ DT_CONSUME_POINTS_CONFIG, ID_SPACE_CONFIG },
		{ DT_ONLINE_AWARDS_CONFIG, ID_SPACE_CONFIG },
		{ DT_PET_EVOLVE_CONFIG, ID_SPACE_CONFIG },
		{ DT_PET_EVOLVED_SKILL_CONFIG, ID_SPACE_CONFIG },
		{ DT_PET_EVOLVED_SKILL_RAND_CONFIG, ID_SPACE_CONFIG },
		{ DT_AUTOTASK_DISPLAY_CONFIG, ID_SPACE_CONFIG },
		{ DT_PLAYER_SPIRIT_CONFIG, ID_SPACE_CONFIG },
		{ DT_HISTORY_STAGE_CONFIG, ID_SPACE_CONFIG },
		{ DT_HISTORY_ADVANCE_CONFIG, ID_SPACE_CONFIG },
		{ DT_AUTOTEAM_CONFIG, ID_SPACE_CONFIG },
		{ DT_CHARIOT_CONFIG, ID_SPACE_CONFIG },
		{ DT_CHARIOT_WAR_CONFIG, ID_SPACE_CONFIG },
		{ DT_POKER_LEVELEXP_CONFIG, ID_SPACE_CONFIG },
		{ DT_GT_CONFIG, ID_SPACE_CONFIG },
		{ DT_MERIDIAN_CONFIG, ID_SPACE_CONFIG },
		{ DT_MONEY_CONVERTIBLE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FASHION_WEAPON_CONFIG, ID_SPACE_CONFIG },
		{ DT_MULTI_EXP_CONFIG, ID_SPACE_CONFIG },
		{ DT_WEDDING_CONFIG, ID_SPACE_CONFIG },
		{ DT_GOD_EVIL_CONVERT_CONFIG, ID_SPACE_CONFIG },
		{ DT_WIKI_TABOO_CONFIG, ID_SPACE_CONFIG },
		{ DT_TASKDICE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_POKER_DICE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_TASKNORMALMATTER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FACE_FALING_ESSENCE, ID_SPACE_FACE },
		{ DT_FACE_THIRDEYE_ESSENCE, ID_SPACE_FACE },
		{ DT_PLAYER_LEVELEXP_CONFIG, ID_SPACE_CONFIG },
		{ DT_ASTROLABE_LEVELEXP_CONFIG, ID_SPACE_CONFIG },
		{ DT_ASTROLABE_ADDON_RANDOM_CONFIG, ID_SPACE_CONFIG },
		{ DT_ASTROLABE_APPEARANCE_CONFIG, ID_SPACE_CONFIG },
		{ DT_EQUIP_MAKE_HOLE_CONFIG, ID_SPACE_CONFIG },
		{ DT_SOLO_TOWER_CHALLENGE_LEVEL_CONFIG, ID_SPACE_CONFIG },
		{ DT_SOLO_TOWER_CHALLENGE_AWARD_PAGE_CONFIG, ID_SPACE_CONFIG },
		{ DT_SOLO_TOWER_CHALLENGE_AWARD_LIST_CONFIG, ID_SPACE_CONFIG },
		{ DT_SOLO_TOWER_CHALLENGE_SCORE_COST_CONFIG, ID_SPACE_CONFIG },
		{ DT_MNFACTION_WAR_CONFIG, ID_SPACE_CONFIG },
		{ DT_FACTION_FORTRESS_CONFIG, ID_SPACE_CONFIG },
		{ DT_FORCE_CONFIG, ID_SPACE_CONFIG },
		{ DT_COUNTRY_CONFIG, ID_SPACE_CONFIG },
		{ DT_GM_ACTIVITY_CONFIG, ID_SPACE_CONFIG },
		{ DT_TOUCH_SHOP_CONFIG, ID_SPACE_CONFIG },
		{ DT_TOKEN_SHOP_CONFIG, ID_SPACE_CONFIG },
		{ DT_RAND_SHOP_CONFIG, ID_SPACE_CONFIG },
		{ DT_PROFIT_TIME_CONFIG, ID_SPACE_CONFIG },
		{ DT_FACTION_PVP_CONFIG, ID_SPACE_CONFIG },
		{ DT_TASK_LIST_CONFIG, ID_SPACE_CONFIG },
		{ DT_TASK_DICE_BY_WEIGHT_CONFIG, ID_SPACE_CONFIG },
		{ DT_FASHION_BEST_COLOR_CONFIG, ID_SPACE_CONFIG },
		{ DT_SIGN_AWARD_CONFIG, ID_SPACE_CONFIG },
		{ DT_TITLE_CONFIG, ID_SPACE_CONFIG },
		{ DT_COMPLEX_TITLE_CONFIG, ID_SPACE_CONFIG },
		{ DT_MINE_TYPE, ID_SPACE_ESSENCE },
		{ DT_MINE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_NPC_IDENTIFY_SERVICE, ID_SPACE_ESSENCE },
		{ DT_FASHION_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_FASHION_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_FASHION_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_POKER_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_POKER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FACETICKET_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_FACETICKET_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_FACETICKET_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FACEPILL_MAJOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_FACEPILL_SUB_TYPE, ID_SPACE_ESSENCE },
		{ DT_FACEPILL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_SUITE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_POKER_SUITE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_GM_GENERATOR_TYPE, ID_SPACE_ESSENCE },
		{ DT_GM_GENERATOR_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_PET_TYPE, ID_SPACE_ESSENCE },
		{ DT_PET_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_PET_EGG_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_PET_FOOD_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_PET_FACETICKET_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FIREWORKS_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FIREWORKS2_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FIX_POSITION_TRANSMIT_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_GOBLIN_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_GOBLIN_EQUIP_TYPE, ID_SPACE_ESSENCE },
		{ DT_GOBLIN_EQUIP_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_GOBLIN_EXPPILL_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_SELL_CERTIFICATE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_TARGET_ITEM_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_LOOK_INFO_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_WAR_TANKCALLIN_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_NPC_WAR_TOWERBUILD_SERVICE, ID_SPACE_ESSENCE },
		{ DT_PLAYER_SECONDLEVEL_CONFIG, ID_SPACE_CONFIG },
		{ DT_PLAYER_REINCARNATION_CONFIG, ID_SPACE_CONFIG },
		{ DT_PLAYER_REALM_CONFIG, ID_SPACE_CONFIG },
		{ DT_NPC_RESETPROP_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_PETNAME_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_PETLEARNSKILL_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_PETFORGETSKILL_SERVICE, ID_SPACE_ESSENCE },
		{ DT_SKILLMATTER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_DYNSKILLEQUIP_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_INC_SKILL_ABILITY_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_WEDDING_BOOKCARD_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_WEDDING_INVITECARD_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_SHARPENER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_CONGREGATE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_MONSTER_SPIRIT_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_DESTROYING_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_DOUBLE_EXP_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_DYE_TICKET_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_REFINE_TICKET_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_NPC_EQUIPBIND_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_EQUIPDESTROY_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_EQUIPUNDESTROY_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_ENGRAVE_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_RANDPROP_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_FORCE_SERVICE, ID_SPACE_ESSENCE },
		{ DT_NPC_CROSS_SERVER_SERVICE, ID_SPACE_ESSENCE },
		{ DT_BIBLE_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_SPEAKER_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_AUTOHP_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_AUTOMP_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FORCE_TOKEN_ESSENCE, ID_SPACE_ESSENCE },
		{ DT_FACE_HAIR_TEXTURE_MAP, ID_SPACE_FACE },
	};

	auto it = _.find(static_cast<DATA_TYPE>(dt)) ;
	if (it != _.end()) {
		return static_cast<elements::space_id>(it->second);
	}
	else {
		// default
		return elements::space_id::essence;
	}
}

bool starts_with(const std::string& full, const std::string& prefix) {
	if (full.length() >= prefix.length()) {
		return (0 == full.compare(0, prefix.length(), prefix));
	} else {
		return false;
	}
}

namespace elements {

meta_type meta_type::parse(const std::string& str) {
	if (str == "int32") {
		return fundamental_meta_type<int32_t>{};
	}
	else if (str == "int64") {
		return fundamental_meta_type<int64_t>{};
	}
	else if (str == "float") {
		return fundamental_meta_type<float>{};
	}
	else if (str == "byte:AUTO") {
		return raw_meta_type{};
	}
	else if (starts_with(str, "string:")) {
		return string_meta_type<char>(std::stoi(str.substr(7)));
	}
	else if (starts_with(str, "wstring:")) {
		return string_meta_type<char16_t>(std::stoi(str.substr(8)));
	}
	else {
		throw std::runtime_error("unknown type in cfg: " + str);
	}
}

std::shared_ptr<list_config> list_config::parse(std::istream& is) {
	/*
		001 - EQUIPMENT_ADDON
		0
		ID;Name;num_params;param1;param2;param3
		int32;wstring:64;int32;int32;int32;int32
	 */
	auto config = std::make_shared<list_config>();

	auto read_line = [](std::istream& is, std::string& out, char delim = '\n') -> std::istream& {
		auto& result = std::getline(is, out, delim);
		if (result) {
			while (!out.empty() && std::isspace(out.back())) {
				out.pop_back();
			}
		}
		return result;
	};

	read_line(is >> std::ws, config->caption, '\r');

	std::string offset, field_names, field_types;

	is >> std::ws >> offset;
	read_line(is >> std::ws, field_names);
	read_line(is >> std::ws, field_types);

	static const std::map<std::string, std::size_t> known_offsets {
			{ "AUTO", static_cast<std::size_t>(-1) },
			{ "0", 0 },
			{ "4", 4 }
	};

	auto it = known_offsets.find(offset);
	if (it == known_offsets.end()) {
		throw std::runtime_error("unknown offset: " + offset + " (list " + config->caption + ")");
	}
	config->offset = it->second;

	std::istringstream sfield_names{ field_names }, sfield_types{ field_types };
	std::string field_name, field_type;
	while (read_line(sfield_names, field_name, ';') && read_line(sfield_types, field_type, ';')) {
		config->fields.emplace_back(std::move(field_name), meta_type::parse(field_type));
	}

	static constexpr auto STRING_OUTPUT_LIMIT = 128;
	auto make_short_str = [](std::string s) {
		if (s.length() >= STRING_OUTPUT_LIMIT) {
			s.resize(STRING_OUTPUT_LIMIT);
			s.append("... (truncated)");
		}
		return s;
	};

	if (!sfield_names.eof()) {
		throw std::runtime_error(fmt::format("elements::list_config::load: cannot parse all field names from '{}' (list: {})",
				make_short_str(field_names), config->caption
		));
	}

	if (!sfield_types.eof()) {
		throw std::runtime_error(fmt::format("elements::list_config::load: cannot parse all field types from '{}' (list: {})",
				make_short_str(field_names), config->caption
		));
	}

	int idt = -1;
	char sdt[256]{};
	if (sscanf(config->caption.c_str(), "%d - %255s", &idt, sdt) != 2) {
		throw std::runtime_error(fmt::format("elements::list_config::load: cannot parse data_type from caption (list: {})", config->caption));
	}
	config->dt = static_cast<data_type>(idt);
	config->sdt = sdt;
	config->space = dt_to_space(config->dt);

	return config;
}

config::ptr config::load(const std::string& path, uint16_t version) {
	try {
		std::ifstream ifs;
		ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);

		ifs.open(path);

		size_t list_count{}, unknown{};
		ifs >> list_count >> unknown;

		assert(unknown == 58);

		auto pconfig = std::make_shared<elements::config>();

		pconfig->_file_path = path;
		pconfig->_version = version;
		for (std::size_t i = 0; i < list_count; i++) {
			auto list = list_config::parse(ifs);

			std::size_t list_index = static_cast<std::size_t>(list->dt) - 1;
			if (list_index > 10'000) {
				throw std::runtime_error(fmt::format("unexpected dt: {}", static_cast<int>(list->dt)));
			}

			pconfig->_list_names[list->sdt] = list->dt;
			if (pconfig->_lists.size() <= list_index) {
				pconfig->_lists.resize(list_index + 1);
			}
			pconfig->_lists[list_index] = std::move(list);
		}

		for (std::size_t i = 0; i < pconfig->_lists.size(); i++) {
			if (!pconfig->_lists[i]) {
				auto dt = i + 1;
				throw std::runtime_error(fmt::format("missing list {:03d}", dt));
			}
		}

		return pconfig;
	}
	catch (std::exception& e) {
		throw std::runtime_error(fmt::format("elements::config::load: cannot parse '{}' ({})", path, e.what()));
	}
}

std::vector<config::ptr> config::load_folder(std::string folder) {
	static const std::regex re{ R"re(PW_(\d\.\d.\d)_v(\d*)\.cfg)re" };

	std::vector<elements::config::ptr> out;

	using namespace boost::filesystem;
	for(path p : boost::make_iterator_range(directory_iterator(folder), {})) {
		if (!is_regular_file(p)) continue;

		auto name = p.filename().string();
		std::smatch match;
		if (std::regex_search(name, match, re) && match.size() == 3) {
			auto version = std::stoi(match[2]);
			if (0 <= version && version <= std::numeric_limits<uint16_t>::max()) {
				try {
					out.emplace_back(elements::config::load(p.string(), static_cast<uint16_t>(version)));
				}
				catch (std::exception& e) {
					std::cerr << e.what() << std::endl;
				}
			}
		}
	}

	return out;
}

data_type config::get_dt_by_name(const std::string& name) const {
	auto it = _list_names.find(name);
	if (it == _list_names.end()) {
		throw std::invalid_argument(fmt::format("no data_type with name '{}' in config v{} (path: '{}')", name, _version, _file_path));
	}
	return it->second;
}

}

max_stars_repo_name: Smertig/autoangel

max_issues_repo_name: Smertig/autoangel

max_forks_repo_name: Smertig/autoangel


text:
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.

#ifdef _WIN32
#include <ws2tcpip.h>
#define close closesocket
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <unistd.h>
#endif

#include <string.h>
#include <fstream>
#include <vector>
#include <thread>
#include <stdlib.h>

#include <openenclave/host.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>

#include <grpcpp/grpcpp.h>

//#include <boost/thread.hpp>

#include "../common/common.h"
#include "../common/block.h"
#include "../common/json.hpp"

#include "../build/common/oram.grpc.pb.h"

#include "log.h"

using grpc::Channel;
using grpc::ClientContext;
using grpc::ClientAsyncResponseReader;
using grpc::CompletionQueue;
using grpc::Status;
using oram::OramRequest;
using oram::OramResponse;
using oram::Oram;

using json = nlohmann::json;

using namespace std;

/*
typedef boost::shared_mutex Lock;
typedef boost::unique_lock<Lock> UniqueLock;
typedef boost::shared_lock<Lock> SharedLock;
*/

class OramClient {
    public:
        OramClient(std::shared_ptr<Channel> channel, uint32_t id)
            : stub_(Oram::NewStub(channel)) {
            comm_key_ = (unsigned char *) "01234567891234567891234567891234";
            replay_ctr_in_ = 0;
            replay_ctr_out_ = 1;
            id_ = id;
        }

        int MakeReq(uint32_t key, uint8_t *in_data, uint8_t *out_data, int batchSz, int numBlocks) {
            OramRequest req;
            int ct_len = get_key_val_buf_sz();
            uint8_t *buf = (uint8_t *)malloc(ct_len);
            uint8_t iv[IV_LEN];
            uint8_t tag[TAG_LEN];
            for (int i = 0; i < batchSz; i++) {
                int reqKey = rand() % (numBlocks - 1) + 1;
                int isRead = (rand() % 2) == 0;
                if (isRead) {
                    encrypt_read_key(comm_key_, buf, iv, tag, reqKey, &replay_ctr_out_, false);
                } else {
                    encrypt_key_val(comm_key_, buf, iv, tag, reqKey, in_data, &replay_ctr_out_, false);
                }
                req.add_ct(buf, ct_len);
                req.add_iv(iv, IV_LEN);
                req.add_tag(tag, TAG_LEN);
            }
            replay_ctr_out_++;
            req.set_client_id(id_);
            OramResponse resp;
            ClientContext ctx;
            Status status;

            //printf("[C] Sending request for key %d\n", key);
            std::unique_ptr<ClientAsyncResponseReader<OramResponse>> rpc(stub_->AsyncAccessKey(&ctx, req, &cq_));
            rpc->Finish(&resp, &status, (void *) 1);
            void *got_tag;
            bool ok = false;
            cq_.Next(&got_tag, &ok);
            if (ok && got_tag == (void *) 1) {
                if (status.ok()) {
                    uint8_t tag[TAG_LEN];
                    //memcpy(tag, resp.tag(0).c_str(), TAG_LEN);
                    for (int i = 0; i < batchSz; i++) {
                        memcpy(tag, resp.tag(i).c_str(), TAG_LEN);
                        decrypt_key_val(comm_key_, &key, out_data, (const uint8_t *)resp.ct(i).c_str(), (const uint8_t *)resp.iv(i).c_str(), tag, &replay_ctr_in_, false);
                    }
                    replay_ctr_in_++;
                    //printf("[C] Received answer for key %d\n", key);
                    //print_bytes("Client receiving data", out_data, BLOCK_LEN);
                    return OKAY;
                } else {
                    printf("[C] ERROR sending req");
                    printf(" (error code: %d, error message: %s)\n", status.error_code(), status.error_message().c_str());
                }
            }
            return ERROR;
        }
    private:
        std::unique_ptr<Oram::Stub> stub_;
        CompletionQueue cq_;
        unsigned char *comm_key_;
        uint32_t replay_ctr_in_;
        uint32_t replay_ctr_out_;
        uint32_t id_;
};

void requestThread(string target_str, int id, uint32_t secToRun, vector<vector<uint32_t>> *msLatencyLists, int batchSz, int numBlocks, chrono::steady_clock::time_point *begin_exp) {
    uint8_t block_bytes[BLOCK_LEN];
    OramClient *client = new OramClient(grpc::CreateChannel(
                target_str, grpc::InsecureChannelCredentials()), id);
    memset(block_bytes, 0xff, BLOCK_LEN);

    // TODO: locking for begin_exp
    //SharedLock r_lock(*lock);
    while (*begin_exp == chrono::steady_clock::time_point::max() || chrono::duration_cast<chrono::seconds>(chrono::steady_clock::now() - *begin_exp).count() < secToRun) {
        //r_lock.unlock();
        chrono::steady_clock::time_point begin = chrono::steady_clock::now();
        client->MakeReq(id, block_bytes, block_bytes, batchSz, numBlocks);
        chrono::steady_clock::time_point end = chrono::steady_clock::now();
        //r_lock.lock();
        if (*begin_exp != chrono::steady_clock::time_point::max() && chrono::duration_cast<chrono::seconds>(chrono::steady_clock::now() - *begin_exp).count() < secToRun) {
            (*msLatencyLists)[id].push_back(chrono::duration_cast<chrono::milliseconds>(end - begin).count());
        }
    }
    //r_lock.unlock();
}

int main(int argc, char** argv)
{
    debug_log::set_name("client");
    int ret = 1;
    X509* cert = nullptr;
    SSL_CTX* ctx = nullptr;
    SSL* ssl = nullptr;
    int serversocket = 0;
    int error = 0;
    uint8_t block_bytes[BLOCK_LEN];
    //std::string target_str = "localhost:12345";
    OramClient *client;
    ifstream config_stream(argv[1]);
    json config;
    config_stream >> config;
    vector<thread *>threads;
    string experiment_dir = config[EXP_DIR];
    int num_balancers = config[NUM_BALANCERS];
    //ofstream file(experiment_dir + "/results.dat");
    ofstream file(experiment_dir + "/results_" + string(config[IP_ADDR]) + ".dat");
    cout << "Writing to " << experiment_dir << "/results.dat" << endl;
    vector<uint32_t> tmp;
    vector<vector<uint32_t>> msLatencyLists(config[THREADS], tmp);
    int client_id = config[CLIENT_ID];
    int num_threads = config[THREADS];

    // initialize openssl library and register algorithms
    OpenSSL_add_all_algorithms();
    ERR_load_BIO_strings();
    ERR_load_crypto_strings();
    SSL_load_error_strings();

    chrono::steady_clock::time_point begin_exp = chrono::steady_clock::time_point::max();
    //Lock lock;
    //UniqueLock w_lock(lock);
    //w_lock.unlock();

    if (SSL_library_init() < 0)
    {
        debug_log::error(TLS_CLIENT
               "TLS client: could not initialize the OpenSSL library !\n");
        goto done;
    }

    ret = 0;

    for (int i = 0; i < num_threads; i++) {
        //msLatencyLists.push_back(new vector<uint32_t>);
        int index = rand() % num_balancers;
        thread *t = new thread(requestThread, config[LB_ADDRS][index], client_id * num_threads + i, config[EXP_SEC], &msLatencyLists, config[BATCH_SZ], config[NUM_BLOCKS], &begin_exp);
        threads.push_back(t);
        printf("started thread %d for balancer %d\n", i, index);
        this_thread::sleep_for(std::chrono::milliseconds(5));
    }

    /* Start experiment. */
    //w_lock.lock();
    begin_exp = chrono::steady_clock::now();
    //w_lock.unlock();

    for (int i = 0; i < config[THREADS]; i++) {
        threads[i]->join();
    }

    if (file.is_open()) {
        for (int i = 0; i < msLatencyLists.size(); i++) {
            for (int j = 0; j < msLatencyLists[i].size(); j++) {
                file << "1 " << to_string(msLatencyLists[i][j]) << endl;
            }
        }
    }
    file.close();

    printf("Finished client\n");

   /* client = new OramClient(grpc::CreateChannel(
                target_str, grpc::InsecureChannelCredentials()), 0);
    memset(block_bytes, 0xff, BLOCK_LEN);
    client->MakeReq(9, block_bytes, block_bytes, false);
    printf("----- starting second request ----- \n");
    memset(block_bytes, 0, BLOCK_LEN);
    client->MakeReq(9, block_bytes, block_bytes, true);*/
done:
    debug_log::info(TLS_CLIENT " %s\n", (ret == 0) ? "success" : "failed");
    return (ret);
}

max_stars_repo_name: ucbrise/snoopy

max_issues_repo_name: ucbrise/snoopy

max_forks_repo_name: ucbrise/snoopy


text:
#include "args-parser.hpp"

#include <iostream>
#include <fstream>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

ParseResult parseCommandLine(int argc, char *argv[], Options &options) {
  try {
    std::string configFile;
    // Declare a group of options that will be
    // allowed only on command line
    po::options_description generic("Generic options");
    generic.add_options()
        (OPT_W_ALIAS(VERSION), "print version string")
        (OPT_W_ALIAS(HELP), "produce help message")
        (OPT_W_ALIAS(CONFIG), po::value<std::string>(&configFile),//->default_value("multiple_sources.cfg"),
                    "name of a file of a configuration.")
        ;

    // std::cout << "generic options\n" << generic << std::endl;

    // Declare a group of options that will be
    // allowed both on command line and in
    // config file
    po::options_description config("Configuration");
    config.add_options()
        // ("optimization", po::value<int>(&options.optimization)->default_value(10),
        //       "optimization level")
        (OPT_W_ALIAS(TEMP_FILE_DIR), po::value<std::string>(&options.tempFileDir)->composing(),
              "temporary file output directory")
        (OPT_W_ALIAS(OUTPUT), po::value<std::string>(&options.outputPath),
              "output file path")
        // ("include-path,I",
        //     po::value< vector<string> >()->composing(),
        //     "include path")
        ;

    // std::cout << "config options\n" << config << std::endl;

    // Hidden options, will be allowed both on command line and
    // in config file, but will not be shown to the user.
    po::options_description hidden("Hidden options");
    hidden.add_options()
        (OPT_W_ALIAS(INPUT_FILE), po::value<std::string>(&options.sourceFile), "input file")
        ;

    // std::cout << "hidden options\n" << hidden << std::endl;

    po::options_description cmdline_options;
    cmdline_options.add(generic).add(config).add(hidden);

    // std::cout << "cmd options\n" << cmdline_options << std::endl;

    po::options_description config_file_options;
    config_file_options.add(config).add(hidden);

    // std::cout << "config file options\n" << config_file_options << std::endl;

    po::options_description visible("Allowed options");
    visible.add(generic).add(config);

    // std::cout << "visible options\n" << visible << std::endl;

    po::positional_options_description p;
    p.add(INPUT_FILE, 1); // max of 1 input file

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
    po::notify(vm);

    // std::cout << cmdline_options << std::endl;

    if (vm.count(CONFIG)) {
      std::ifstream ifs(configFile.c_str());
      if (!ifs) {
        std::cout << "can not open config file: " << configFile << std::endl;
        return ParseResult::EXIT_COMPILATION;
      } else {
        po::store(po::parse_config_file(ifs, config_file_options), vm);
        po::notify(vm);
      }
    }

    if (vm.count(HELP)) {
      std::cout << visible<< std::endl;
      return ParseResult::EXIT_COMPILATION;
    }

    if (vm.count(VERSION)) {
      std::cout << "Bokay CPP Compiler, version 0.0.1\n";
      return ParseResult::EXIT_COMPILATION;
    }

    if (!vm.count(INPUT_FILE)) {
      std::cout << "Must provide a file to be compiled!" << std::endl;
      return ParseResult::INVALID_ARGUMENTS;
    }
    std::cout << "Input source file: " << options.sourceFile << std::endl;

    if ((options.customOutputPath = vm.count(OUTPUT))) {
      std::cout << "Output path: " << options.outputPath << std::endl;
    } else {
      std::cout << "No output path provided." << std::endl;
      // options.outputPath = options.sourceFile + ".out";
    }

    if ((options.outputTemps = vm.count(TEMP_FILE_DIR))) {
      std::cout << "Temp file output to: " << options.tempFileDir << std::endl;
    }

  } catch (std::exception &e) {
    std::cout << e.what() << std::endl;
    return ParseResult::INVALID_ARGUMENTS;
  }
  return ParseResult::PARSING_SUCCESS;
}


text: #include <boost/hana/any_of.hpp>


text:
//  Copyright (c) 2013 Agustin Berge
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(HPX_TRAITS_IS_BIND_EXPRESSION_AUG_28_2013_0603PM)
#define HPX_TRAITS_IS_BIND_EXPRESSION_AUG_28_2013_0603PM

#include <hpx/config.hpp>

#include <boost/mpl/bool.hpp>

#ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL
#   include <functional>
#endif

namespace hpx { namespace traits
{
    template <typename T>
    struct is_bind_expression
#   ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL
      : std::is_bind_expression<T>
#   else
      : boost::mpl::false_
#   endif
    {};
}}

#endif

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx