text:
/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file State.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "State.h"

#include <secp256k1.h>
#include <boost/filesystem.hpp>
#include <time.h>
#include <random>
#include "BlockChain.h"
#include "Instruction.h"
#include "Exceptions.h"
#include "Dagger.h"
#include "Defaults.h"
#include "VM.h"
using namespace std;
using namespace eth;

u256 eth::c_genesisDifficulty = (u256)1 << 22;

std::map<Address, AddressState> const& eth::genesisState()
{
	static std::map<Address, AddressState> s_ret;
	if (s_ret.empty())
	{
		// Initialise.
		s_ret[Address(fromUserHex("8a40bfaa73256b60764c1bf40675a99083efb075"))] = AddressState(u256(1) << 200, 0, AddressType::Normal);
		s_ret[Address(fromUserHex("e6716f9544a56c530d868e4bfbacb172315bdead"))] = AddressState(u256(1) << 200, 0, AddressType::Normal);
		s_ret[Address(fromUserHex("1e12515ce3e0f817a4ddef9ca55788a1d66bd2df"))] = AddressState(u256(1) << 200, 0, AddressType::Normal);
		s_ret[Address(fromUserHex("1a26338f0d905e295fccb71fa9ea849ffa12aaf4"))] = AddressState(u256(1) << 200, 0, AddressType::Normal);
	}
	return s_ret;
}

Overlay State::openDB(std::string _path, bool _killExisting)
{
	if (_path.empty())
		_path = Defaults::get()->m_dbPath;
	boost::filesystem::create_directory(_path);

	ldb::Options o;
	o.create_if_missing = true;
	ldb::DB* db = nullptr;
	ldb::DB::Open(o, _path + "/state", &db);
	return Overlay(db);
}

State::State(Address _coinbaseAddress, Overlay const& _db):
	m_db(_db),
	m_state(&m_db),
	m_ourAddress(_coinbaseAddress)
{
	m_blockReward = 1500 * finney;
	m_fees.setMultiplier(100 * szabo);

	secp256k1_start();

	// Initialise to the state entailed by the genesis block; this guarantees the trie is built correctly.
	m_state.init();
	eth::commit(genesisState(), m_db, m_state);
//	cnote << "State root: " << m_state.root();

	m_previousBlock = BlockInfo::genesis();
//	cnote << "Genesis hash:" << m_previousBlock.hash;
	resetCurrent();

	assert(m_state.root() == m_previousBlock.stateRoot);
}

State::State(State const& _s):
	m_db(_s.m_db),
	m_state(&m_db, _s.m_state.root()),
	m_transactions(_s.m_transactions),
	m_transactionSet(_s.m_transactionSet),
	m_cache(_s.m_cache),
	m_previousBlock(_s.m_previousBlock),
	m_currentBlock(_s.m_currentBlock),
	m_currentNumber(_s.m_currentNumber),
	m_ourAddress(_s.m_ourAddress),
	m_fees(_s.m_fees),
	m_blockReward(_s.m_blockReward)
{
}

State& State::operator=(State const& _s)
{
	m_db = _s.m_db;
	m_state.open(&m_db, _s.m_state.root());
	m_transactions = _s.m_transactions;
	m_transactionSet = _s.m_transactionSet;
	m_cache = _s.m_cache;
	m_previousBlock = _s.m_previousBlock;
	m_currentBlock = _s.m_currentBlock;
	m_currentNumber = _s.m_currentNumber;
	m_ourAddress = _s.m_ourAddress;
	m_fees = _s.m_fees;
	m_blockReward = _s.m_blockReward;
	return *this;
}

void State::ensureCached(Address _a, bool _requireMemory, bool _forceCreate) const
{
	auto it = m_cache.find(_a);
	if (it == m_cache.end())
	{
		// populate basic info.
		string stateBack = m_state.at(_a);
		if (stateBack.empty() && !_forceCreate)
			return;
		RLP state(stateBack);
		AddressState s;
		if (state.isNull())
			s = AddressState(0, 0);
		else if (state.itemCount() == 2)
			s = AddressState(state[0].toInt<u256>(), state[1].toInt<u256>());
		else
			s = AddressState(state[0].toInt<u256>(), state[1].toInt<u256>(), state[2].toHash<h256>());
		bool ok;
		tie(it, ok) = m_cache.insert(make_pair(_a, s));
	}
	if (_requireMemory && !it->second.haveMemory())
	{
		// Populate memory.
		assert(it->second.type() == AddressType::Contract);
		TrieDB<h256, Overlay> memdb(const_cast<Overlay*>(&m_db), it->second.oldRoot());		// promise we won't alter the overlay! :)
		map<u256, u256>& mem = it->second.setHaveMemory();
		for (auto const& i: memdb)
#ifdef __clang__
			if (mem.find(i.first) == mem.end())
				mem.insert(make_pair(i.first, RLP(i.second).toInt<u256>()));
			else
				mem.at(i.first) = RLP(i.second).toInt<u256>();
#else
			mem[i.first] = RLP(i.second).toInt<u256>();
#endif
	}
}

void State::commit()
{
	eth::commit(m_cache, m_db, m_state);
	m_cache.clear();
}

bool State::sync(BlockChain const& _bc)
{
return sync(_bc, _bc.currentHash());
}

bool State::sync(BlockChain const& _bc, h256 _block)
{
	bool ret = false;
	// BLOCK
	BlockInfo bi;
	try
	{
		auto b = _bc.block(_block);
		bi.populate(b);
		bi.verifyInternals(_bc.block(_block));
	}
	catch (...)
	{
		// TODO: Slightly nicer handling? :-)
		cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
		exit(1);
	}

	if (bi == m_currentBlock)
	{
		// We mined the last block.
		// Our state is good - we just need to move on to next.
		m_previousBlock = m_currentBlock;
		resetCurrent();
		m_currentNumber++;
		ret = true;
	}
	else if (bi == m_previousBlock)
	{
		// No change since last sync.
		// Carry on as we were.
	}
	else
	{
		// New blocks available, or we've switched to a different branch. All change.
		// Find most recent state dump and replay what's left.
		// (Most recent state dump might end up being genesis.)

		std::vector<h256> chain;
		while (bi.stateRoot != BlockInfo::genesis().hash && m_db.lookup(bi.stateRoot).empty())	// while we don't have the state root of the latest block...
		{
			chain.push_back(bi.hash);				// push back for later replay.
			bi.populate(_bc.block(bi.parentHash));	// move to parent.
		}

		m_previousBlock = bi;
		resetCurrent();

		// Iterate through in reverse, playing back each of the blocks.
		for (auto it = chain.rbegin(); it != chain.rend(); ++it)
			playback(_bc.block(*it), true);

		m_currentNumber = _bc.details(_block).number + 1;
		resetCurrent();
		ret = true;
	}
	return ret;
}

map<Address, u256> State::addresses() const
{
	map<Address, u256> ret;
	for (auto i: m_cache)
		if (i.second.type() != AddressType::Dead)
			ret[i.first] = i.second.balance();
	for (auto const& i: m_state)
		if (m_cache.find(i.first) == m_cache.end())
			ret[i.first] = RLP(i.second)[0].toInt<u256>();
	return ret;
}

void State::resetCurrent()
{
	m_transactions.clear();
	m_transactionSet.clear();
	m_cache.clear();
	m_currentBlock = BlockInfo();
	m_currentBlock.coinbaseAddress = m_ourAddress;
	m_currentBlock.stateRoot = m_previousBlock.stateRoot;
	m_currentBlock.parentHash = m_previousBlock.hash;
	m_currentBlock.sha3Transactions = h256();
	m_currentBlock.sha3Uncles = h256();

	// Update timestamp according to clock.
	m_currentBlock.timestamp = time(0);

	m_state.setRoot(m_currentBlock.stateRoot);
}

bool State::cull(TransactionQueue& _tq) const
{
	bool ret = false;
	auto ts = _tq.transactions();
	for (auto const& i: ts)
	{
		if (!m_transactionSet.count(i.first))
		{
			try
			{
				Transaction t(i.second);
				if (t.nonce <= transactionsFrom(t.sender()))
				{
					_tq.drop(i.first);
					ret = true;
				}
			}
			catch (...)
			{
				_tq.drop(i.first);
				ret = true;
			}
		}
	}
	return ret;
}

bool State::sync(TransactionQueue& _tq)
{
	// TRANSACTIONS
	bool ret = false;
	auto ts = _tq.transactions();
	vector<pair<h256, bytes>> futures;

	for (int goodTxs = 1; goodTxs;)
	{
		goodTxs = 0;
		for (auto const& i: ts)
		{
			if (!m_transactionSet.count(i.first))
			{
				// don't have it yet! Execute it now.
				try
				{
					execute(i.second);
					ret = true;
					_tq.noteGood(i);
					++goodTxs;
				}
				catch (InvalidNonce const& in)
				{
					if (in.required > in.candidate)
					{
						// too old
						_tq.drop(i.first);
						ret = true;
					}
					else
						_tq.setFuture(i);
				}
				catch (std::exception const&)
				{
					// Something else went wrong - drop it.
					_tq.drop(i.first);
					ret = true;
				}
			}
		}
	}
	return ret;
}

u256 State::playback(bytesConstRef _block, bool _fullCommit)
{
	try
	{
		m_currentBlock.populate(_block);
		m_currentBlock.verifyInternals(_block);
		return playback(_block, BlockInfo(), _fullCommit);
	}
	catch (...)
	{
		// TODO: Slightly nicer handling? :-)
		cerr << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
		exit(1);
	}
}

u256 State::playback(bytesConstRef _block, BlockInfo const& _bi, BlockInfo const& _parent, BlockInfo const& _grandParent, bool _fullCommit)
{
	m_currentBlock = _bi;
	m_previousBlock = _parent;
	return playback(_block, _grandParent, _fullCommit);
}

u256 State::playback(bytesConstRef _block, BlockInfo const& _grandParent, bool _fullCommit)
{
	if (m_currentBlock.parentHash != m_previousBlock.hash)
		throw InvalidParentHash();

//	cnote << "playback begins:" << m_state.root();
//	cnote << m_state;

	// All ok with the block generally. Play back the transactions now...
	for (auto const& i: RLP(_block)[1])
		execute(i.data());

	// Initialise total difficulty calculation.
	u256 tdIncrease = m_currentBlock.difficulty;

	// Check uncles & apply their rewards to state.
	Addresses rewarded;
	for (auto const& i: RLP(_block)[2])
	{
		BlockInfo uncle = BlockInfo::fromHeader(i.data());
		if (m_previousBlock.parentHash != uncle.parentHash)
			throw InvalidUncle();
		if (_grandParent)
			uncle.verifyParent(_grandParent);
		tdIncrease += uncle.difficulty;
		rewarded.push_back(uncle.coinbaseAddress);
	}
	applyRewards(rewarded);

	// Commit all cached state changes to the state trie.
	commit();

	// Hash the state trie and check against the state_root hash in m_currentBlock.
	if (m_currentBlock.stateRoot != rootHash())
	{
		cwarn << "Bad state root!";
		cnote << "Given to be:" << m_currentBlock.stateRoot;
		cnote << TrieDB<Address, Overlay>(&m_db, m_currentBlock.stateRoot);
		cnote << "Calculated to be:" << rootHash();
		cnote << m_state;
		cnote << *this;
		// Rollback the trie.
		m_db.rollback();
		throw InvalidStateRoot();
	}

	if (_fullCommit)
	{
		// Commit the new trie to disk.
		m_db.commit();

		m_previousBlock = m_currentBlock;
		resetCurrent();
	}
	else
	{
		m_db.rollback();
		resetCurrent();
	}

	return tdIncrease;
}

// @returns the block that represents the difference between m_previousBlock and m_currentBlock.
// (i.e. all the transactions we executed).
void State::commitToMine(BlockChain const& _bc)
{
	if (m_currentBlock.sha3Transactions != h256() || m_currentBlock.sha3Uncles != h256())
	{
		Addresses uncleAddresses;
		for (auto i: RLP(m_currentUncles))
			uncleAddresses.push_back(i[2].toHash<Address>());
		unapplyRewards(uncleAddresses);
	}

	cnote << "Commiting to mine on" << m_previousBlock.hash;

	RLPStream uncles;
	Addresses uncleAddresses;

	if (m_previousBlock != BlockInfo::genesis())
	{
		// Find uncles if we're not a direct child of the genesis.
//		cout << "Checking " << m_previousBlock.hash << ", parent=" << m_previousBlock.parentHash << endl;
		auto us = _bc.details(m_previousBlock.parentHash).children;
		assert(us.size() >= 1);	// must be at least 1 child of our grandparent - it's our own parent!
		uncles.appendList(us.size() - 1);	// one fewer - uncles precludes our parent from the list of grandparent's children.
		for (auto const& u: us)
			if (u != m_previousBlock.hash)	// ignore our own parent - it's not an uncle.
			{
				BlockInfo ubi(_bc.block(u));
				ubi.fillStream(uncles, true);
				uncleAddresses.push_back(ubi.coinbaseAddress);
			}
	}
	else
		uncles.appendList(0);

	applyRewards(uncleAddresses);

	RLPStream txs(m_transactions.size());
	for (auto const& i: m_transactions)
		i.fillStream(txs);

	txs.swapOut(m_currentTxs);
	uncles.swapOut(m_currentUncles);

	m_currentBlock.sha3Transactions = sha3(m_currentTxs);
	m_currentBlock.sha3Uncles = sha3(m_currentUncles);

	// Commit any and all changes to the trie that are in the cache, then update the state root accordingly.
	commit();

	cnote << "stateRoot:" << m_state.root();
//	cnote << m_state;
//	cnote << *this;

	m_currentBlock.stateRoot = m_state.root();
	m_currentBlock.parentHash = m_previousBlock.hash;
}

MineInfo State::mine(uint _msTimeout)
{
	// Update difficulty according to timestamp.
	m_currentBlock.difficulty = m_currentBlock.calculateDifficulty(m_previousBlock);

	// TODO: Miner class that keeps dagger between mine calls (or just non-polling mining).
	MineInfo ret = m_dagger.mine(/*out*/m_currentBlock.nonce, m_currentBlock.headerHashWithoutNonce(), m_currentBlock.difficulty, _msTimeout);
	if (ret.completed)
	{
		// Got it!

		// Commit to disk.
		m_db.commit();

		// Compile block:
		RLPStream ret;
		ret.appendList(3);
		m_currentBlock.fillStream(ret, true);
		ret.appendRaw(m_currentTxs);
		ret.appendRaw(m_currentUncles);
		ret.swapOut(m_currentBytes);
		m_currentBlock.hash = sha3(m_currentBytes);
		cnote << "Mined " << m_currentBlock.hash << "(parent: " << m_currentBlock.parentHash << ")";
	}
	else
		m_currentBytes.clear();

	return ret;
}

bool State::isNormalAddress(Address _id) const
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end())
		return false;
	return it->second.type() == AddressType::Normal;
}

bool State::isContractAddress(Address _id) const
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end())
		return false;
	return it->second.type() == AddressType::Contract;
}

u256 State::balance(Address _id) const
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end())
		return 0;
	return it->second.balance();
}

void State::noteSending(Address _id)
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end())
		m_cache[_id] = AddressState(0, 1);
	else
		it->second.incNonce();
}

void State::addBalance(Address _id, u256 _amount)
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end())
		m_cache[_id] = AddressState(_amount, 0);
	else
		it->second.addBalance(_amount);
}

void State::subBalance(Address _id, bigint _amount)
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end() || (bigint)it->second.balance() < _amount)
		throw NotEnoughCash();
	else
		it->second.addBalance(-_amount);
}

u256 State::transactionsFrom(Address _id) const
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end())
		return 0;
	else
		return it->second.nonce();
}

u256 State::contractMemory(Address _id, u256 _memory) const
{
	ensureCached(_id, false, false);
	auto it = m_cache.find(_id);
	if (it == m_cache.end() || it->second.type() != AddressType::Contract)
		return 0;
	else if (it->second.haveMemory())
	{
		auto mit = it->second.memory().find(_memory);
		if (mit == it->second.memory().end())
			return 0;
		return mit->second;
	}
	// Memory not cached - just grab one item from the DB rather than cache the lot.
	TrieDB<h256, Overlay> memdb(const_cast<Overlay*>(&m_db), it->second.oldRoot());			// promise we won't change the overlay! :)
	string ret = memdb.at(_memory);
	return ret.size() ? RLP(ret).toInt<u256>() : 0;
}

map<u256, u256> const& State::contractMemory(Address _contract) const
{
	if (!isContractAddress(_contract))
		return EmptyMapU256U256;
	ensureCached(_contract, true, true);
	return m_cache[_contract].memory();
}

void State::execute(bytesConstRef _rlp)
{
	// Entry point for a user-executed transaction.
	Transaction t(_rlp);
	executeBare(t, t.sender());

	// Add to the user-originated transactions that we've executed.
	// NOTE: Here, contract-originated transactions will not get added to the transaction list.
	// If this is wrong, move this line into execute(Transaction const& _t, Address _sender) and
	// don't forget to allow unsigned transactions in the tx list if they concur with the script execution.
	m_transactions.push_back(t);
	m_transactionSet.insert(t.sha3());
}

void State::applyRewards(Addresses const& _uncleAddresses)
{
	u256 r = m_blockReward;
	for (auto const& i: _uncleAddresses)
	{
		addBalance(i, m_blockReward * 3 / 4);
		r += m_blockReward / 8;
	}
	addBalance(m_currentBlock.coinbaseAddress, r);
}

void State::unapplyRewards(Addresses const& _uncleAddresses)
{
	u256 r = m_blockReward;
	for (auto const& i: _uncleAddresses)
	{
		subBalance(i, m_blockReward * 3 / 4);
		r += m_blockReward / 8;
	}
	subBalance(m_currentBlock.coinbaseAddress, r);
}

void State::executeBare(Transaction const& _t, Address _sender)
{
#if ETH_DEBUG
	commit();
	clog(StateChat) << "State:" << rootHash();
	clog(StateChat) << "Executing TX:" << _t;
#endif

	// Entry point for a contract-originated transaction.

	// Ignore invalid transactions.
	auto nonceReq = transactionsFrom(_sender);
	if (_t.nonce != nonceReq)
	{
		clog(StateChat) << "Invalid Nonce.";
		throw InvalidNonce(nonceReq, _t.nonce);
	}

	unsigned nonZeroData = 0;
	for (auto i: _t.data)
		if (i)
			nonZeroData++;
	u256 fee = _t.receiveAddress ? m_fees.m_txFee : (nonZeroData * m_fees.m_memoryFee + m_fees.m_newContractFee);

	// Not considered invalid - just pointless.
	if (balance(_sender) < _t.value + fee)
	{
		clog(StateChat) << "Not enough cash.";
		throw NotEnoughCash();
	}

	if (_t.receiveAddress)
	{
		// Increment associated nonce for sender.
		noteSending(_sender);

		// Pay...
		subBalance(_sender, _t.value + fee);
		addBalance(_t.receiveAddress, _t.value);

		if (isContractAddress(_t.receiveAddress))
		{
			// Once we get here, there's no going back.
			try
			{
				MinerFeeAdder feeAdder({this, 0});	// will add fee on destruction.
				execute(_t.receiveAddress, _sender, _t.value, _t.data, &feeAdder.fee);
			}
			catch (VMException const& _e)
			{
				clog(StateChat) << "VM Exception: " << _e.description();
			}
			catch (Exception const& _e)
			{
				clog(StateChat) << "Exception in VM: " << _e.description();
			}
			catch (std::exception const& _e)
			{
				clog(StateChat) << "std::exception in VM: " << _e.what();
			}
		}
	}
	else
	{
		Address newAddress = right160(_t.sha3());

		if (isContractAddress(newAddress) || isNormalAddress(newAddress))
		{
			clog(StateChat) << "Contract address collision.";
			throw ContractAddressCollision();
		}

		// Increment associated nonce for sender.
		noteSending(_sender);

		// Pay out of sender...
		subBalance(_sender, _t.value + fee);

		// Set up new account...
		m_cache[newAddress] = AddressState(_t.value, 0, AddressType::Contract);
		auto& mem = m_cache[newAddress].memory();
		for (uint i = 0; i < _t.data.size(); ++i)
#ifdef __clang__
			if (mem.find(i) == mem.end())
				mem.insert(make_pair(i, _t.data[i]));
			else
				mem.at(i) = _t.data[i];
#else
			mem[i] = _t.data[i];
#endif
	}

#if ETH_DEBUG
	commit();
	clog(StateChat) << "New state:" << rootHash();
#endif
}

void State::execute(Address _myAddress, Address _txSender, u256 _txValue, u256s const& _txData, u256* _totalFee)
{
	VM vm;
	ExtVM evm(*this, _myAddress, _txSender, _txValue, _txData);
	vm.go(evm);
	*_totalFee = vm.runFee();
}

max_stars_repo_name: aantonop/cpp-ethereum

max_issues_repo_name: programmerTim/cpp-ethereum

max_forks_repo_name: programmerTim/cpp-ethereum


text:
#include <cstdio>
#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/property_tree/exceptions.hpp>
#include <boost/property_tree/info_parser.hpp>

#include <Magick++.h>

#include <DefaultConfig.h>
#include <ScreenCapture.h>

namespace pt = boost::property_tree;

void makePip(Magick::Image& screen,
             const pt::ptree& config,
             const Magick::Geometry& pipGeom,
             const float sigma)
{
  Magick::Geometry rPip(pipGeom.width(),
                        pipGeom.height(),
                        0, 0);
  const int w = config.get<int>("pip.border.width");

  // Resize image and add border
  const Magick::Geometry border(w, w, 0, 0);
  screen.backgroundColor("none");
  screen.filterType(Magick::LanczosFilter);
  screen.resize(rPip);
  screen.borderColor(config.get<std::string>("pip.border.color"));
  screen.border(border);

  // Add shadow
  Magick::Image shadow = screen;
  shadow.backgroundColor(config.get<std::string>("pip.shadow.color"));
  shadow.shadow(config.get<int>("pip.shadow.opacity"),
                sigma, 0, 0);
  shadow.composite(screen,
                   pipGeom.xOff(), pipGeom.yOff(),
                   Magick::OverCompositeOp);
  screen = std::move(shadow);
}

bool writeConfigFile(const std::string& outfile)
{
  std::ofstream conffile(outfile, std::ofstream::out);
  if (conffile.good()) {
    std::cout << "Config file '" << outfile << "' created." << std::endl;
    conffile << pipfiles::defaultConfig;
    conffile.close();
  } else {
    std::cerr << "Failed to create config file: "
              << outfile << std::endl;
    return false;
  }
  return true;
}

void displayUsage(std::ostream& out, const std::string& argv0) {
  out << " Usage: \n"
      << " " << argv0 << " --help\n"
      << " " << argv0 << " --createconfig [CONFIG.info]\n"
      << " " << argv0 << " OUTFILE.FMT [CONFIG.info]\n"
      << pipfiles::helpOutupt << std::endl;
}

void parseParameters(int argc, char* argv[],
                     std::string& output,
                     std::string& config) {
  (void) argc;
  if (argc < 2) {
    std::cerr << "Invalid parameters." << std::endl;
    displayUsage(std::cerr, argv[0]);
    exit(EXIT_FAILURE);
  }

  // Check if --createconfig flag set.
  if (std::string(argv[1]) == std::string("--createconfig")) {
    if (argc > 2)
      config = argv[2];
    else
      config = "pip-screenshot-config.info";

    if (boost::filesystem::exists(config)) {
      std::cerr << "Specified config file already exists! Aborting."
                << std::endl;
      exit(EXIT_FAILURE);
    } else {
      if (writeConfigFile(config))
        exit(EXIT_SUCCESS);
      else
        exit(EXIT_FAILURE);
    }
  } else if (std::string(argv[1]) == std::string("--help")) {
    displayUsage(std::cout, argv[0]);
    exit(EXIT_SUCCESS);
  } else {
    if (argc > 1)
      output = argv[1];
    if (argc > 2)
      config = argv[2];
    else
      config = "pip-screenshot-config.info";
  }
}

int main(int argc, char* argv[])
{
  // Parameter parsing
  std::string configFile;
  std::string outputFile;
  parseParameters(argc, argv, outputFile, configFile);

  // Check if config file or create default
  if (!boost::filesystem::exists(configFile)) {
    std::cerr << "Couldn't find config file" << std::endl;
    return EXIT_FAILURE;
  }

  // Load configuration from config file
  pt::ptree config;
  boost::property_tree::read_info(configFile, config);

  // Read config values
  const int prinW = config.get<int>("monitor.principal.w");
  const int prinH = config.get<int>("monitor.principal.h");
  const int prinX = config.get<int>("monitor.principal.x");
  const int prinY = config.get<int>("monitor.principal.y");

  const int secW = config.get<int>("monitor.secondary.w");
  const int secH = config.get<int>("monitor.secondary.h");
  const int secX = config.get<int>("monitor.secondary.x");
  const int secY = config.get<int>("monitor.secondary.y");

  // How many pixels to offset the PiP, from bottom right
  const float sigma = config.get<float>("pip.shadow.sigma");
  const float pipShadowX = config.get<float>("pip.shadow.pos.x");
  const float pipShadowY = config.get<float>("pip.shadow.pos.y");
  const int pipPosX = config.get<int>("pip.pos.x");
  const int pipPosY = config.get<int>("pip.pos.y");
  const int pipW = config.get<int>("pip.size.w");
  const int pipH = config.get<int>("pip.size.h");

  // Where to overlay the PiP relative to shadow
  const int pipPosXShadow = static_cast<int>((-pipShadowX + 1.0f) *
                                             2.0f * sigma);
  const int pipPosYShadow = static_cast<int>((-pipShadowY + 1.0f) *
                                             2.0f * sigma);

  // Adjustment offset for change in PiP position within the pip image,
  // caused by the drop-shadow
  const int pipPosXShadowOff = static_cast<int>(2.0f * sigma *
                                                (1.0f + pipShadowX));
  const int pipPosYShadowOff = static_cast<int>(2.0f * sigma *
                                                (1.0f + pipShadowY));

  // Initalize image magick
  Magick::InitializeMagick(*argv);
  Magick::Geometry prinGeom(prinW, prinH, prinX, prinY);
  Magick::Geometry secGeom(secW, secH, secX, secY);
  Magick::Geometry pipGeom(pipW, pipH, pipPosXShadow, pipPosYShadow);

  // Get screen capture from X11
  ScreenCapture sc;
  Magick::Image principal = sc.getScreenShot(prinGeom);
  Magick::Image secondary = sc.getScreenShot(secGeom);

  // Convert secondary screen to PiP thumbnail
  makePip(secondary, config, pipGeom, sigma);
  principal.composite(secondary,
                      (prinGeom.width() - secondary.size().width() -
                       pipPosX + pipPosXShadowOff),
                      (prinGeom.height() - secondary.size().height() -
                       pipPosY + pipPosYShadowOff),
                      Magick::OverCompositeOp);

  // Write frame to file
  // Removes alpha channe
  principal.matte(false);
  principal.depth(8);
  principal.compressType(Magick::RunlengthEncodedCompression);
  principal.write(outputFile);

  return EXIT_SUCCESS;
}

ext: cpp

max_stars_repo_name: swarminglogic/pip-screenshot

max_issues_repo_name: swarminglogic/pip-screenshot

max_forks_repo_name: swarminglogic/pip-screenshot


text:
#ifdef STAN_OPENCL

#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/copy.hpp>
#include <test/unit/math/opencl/kernel_generator/reference_kernel.hpp>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include <string>

using Eigen::Matrix;
using Eigen::MatrixXd;
using Eigen::MatrixXi;
using stan::math::matrix_cl;

#define EXPECT_MATRIX_NEAR(A, B, DELTA) \
  for (int i = 0; i < A.size(); i++)    \
    EXPECT_NEAR(A(i), B(i), DELTA);

TEST(KernelGenerator, select_errors) {
  using stan::math::select;

  matrix_cl<double> m_double(2, 3);
  matrix_cl<double> m_rows(3, 3);
  matrix_cl<double> m_cols(2, 4);
  matrix_cl<int> m_int(2, 3);
  matrix_cl<bool> m_bool(2, 3);

  EXPECT_NO_THROW(select(m_bool, m_double, m_double));
  EXPECT_NO_THROW(select(m_bool, m_double, m_int));
  EXPECT_NO_THROW(select(m_bool, m_int, m_double));
  EXPECT_NO_THROW(select(m_int, m_double, m_double));
  EXPECT_THROW(select(m_rows, m_double, m_double), std::invalid_argument);
  EXPECT_THROW(select(m_cols, m_double, m_double), std::invalid_argument);
  EXPECT_THROW(select(m_bool, m_rows, m_double), std::invalid_argument);
  EXPECT_THROW(select(m_bool, m_cols, m_double), std::invalid_argument);
  EXPECT_THROW(select(m_bool, m_double, m_rows), std::invalid_argument);
  EXPECT_THROW(select(m_bool, m_double, m_cols), std::invalid_argument);
}

TEST(KernelGenerator, select_zero_size) {
  matrix_cl<double> m_bool_zero(0, 0);
  matrix_cl<double> m_double_zero(0, 0);
  matrix_cl<int> m_int_zero(0, 0);
  matrix_cl<int> m_int_zero_rows(0, 1);

  EXPECT_NO_THROW(select(m_bool_zero, m_double_zero, m_double_zero));
  EXPECT_NO_THROW(select(m_bool_zero, m_double_zero, m_int_zero));
  EXPECT_NO_THROW(select(m_bool_zero, m_int_zero, m_double_zero));
  EXPECT_THROW(select(m_bool_zero, m_double_zero, m_int_zero_rows),
               std::invalid_argument);
}

TEST(KernelGenerator, select_test) {
  std::string kernel_filename = "select.cl";
  using stan::math::select;
  MatrixXd m1(2, 3);
  m1 << 1, 2.5, 3, 4, 5, 6.3;
  MatrixXd m2(2, 3);
  m2 << 10, 100, 1000, 30.5, 12.1, 0.3;
  Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> m_cond(2, 3);
  m_cond << true, false, false, true, true, false;

  matrix_cl<double> m1_cl(m1);
  matrix_cl<double> m2_cl(m2);
  matrix_cl<bool> m_cond_cl(m_cond);

  auto tmp = select(m_cond_cl, m1_cl, m2_cl);

  matrix_cl<double> res_cl;
  std::string kernel_src = tmp.get_kernel_source_for_evaluating_into(res_cl);
  stan::test::store_reference_kernel_if_needed(kernel_filename, kernel_src);
  std::string expected_kernel_src
      = stan::test::load_reference_kernel(kernel_filename);
  EXPECT_EQ(expected_kernel_src, kernel_src);

  res_cl = tmp;
  MatrixXd res = stan::math::from_matrix_cl(res_cl);

  MatrixXd correct = m_cond.select(m1, m2);
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

TEST(KernelGenerator, multiple_operations) {
  using stan::math::select;
  MatrixXd m1(2, 3);
  m1 << 1, 2.5, 3, 4, 5, 6.3;
  MatrixXi m2(2, 3);
  m2 << 10, 100, 1000, 30, 12, 0;
  MatrixXd m3(2, 3);
  m3 << 1.4, 12.5, 6.3, 34.4, -5, -6.3;
  Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> m_cond(2, 3);
  m_cond << true, false, false, true, true, false;
  Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> m_cond2(2, 3);
  m_cond2 << false, false, true, true, false, true;

  matrix_cl<double> m1_cl(m1);
  matrix_cl<int> m2_cl(m2);
  matrix_cl<double> m3_cl(m3);
  matrix_cl<bool> m_cond_cl(m_cond);
  matrix_cl<bool> m_cond2_cl(m_cond2);
  auto tmp = select(m_cond_cl, m1_cl, select(m_cond2_cl, m2_cl, m3_cl));
  matrix_cl<double> res_cl = tmp;

  MatrixXd res = stan::math::from_matrix_cl(res_cl);

  MatrixXd correct = m_cond.select(m1, m_cond2.select(m2.cast<double>(), m3));
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

TEST(KernelGenerator, multiple_operations_size_zero) {
  using stan::math::select;

  matrix_cl<double> m1_cl(0, 0);
  matrix_cl<int> m2_cl(0, 0);
  matrix_cl<double> m3_cl(0, 0);
  matrix_cl<bool> m_cond_cl(0, 0);
  matrix_cl<bool> m_cond2_cl(0, 0);
  auto tmp = select(m_cond_cl, m1_cl, select(m_cond2_cl, m2_cl, m3_cl));
  matrix_cl<double> res_cl = tmp;

  EXPECT_EQ(0, res_cl.rows());
  EXPECT_EQ(0, res_cl.cols());
}

TEST(KernelGenerator, multiple_operations_accepts_lvalue) {
  using stan::math::select;
  MatrixXd m1(2, 3);
  m1 << 1, 2.5, 3, 4, 5, 6.3;
  MatrixXi m2(2, 3);
  m2 << 10, 100, 1000, 30, 12, 0;
  MatrixXd m3(2, 3);
  m3 << 1.4, 12.5, 6.3, 34.4, -5, -6.3;
  Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> m_cond(2, 3);
  m_cond << true, false, false, true, true, false;
  Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> m_cond2(2, 3);
  m_cond2 << false, false, true, true, false, true;

  matrix_cl<double> m1_cl(m1);
  matrix_cl<int> m2_cl(m2);
  matrix_cl<double> m3_cl(m3);
  matrix_cl<bool> m_cond_cl(m_cond);
  matrix_cl<bool> m_cond2_cl(m_cond2);
  auto tmp2 = select(m_cond2_cl, m2_cl, m3_cl);
  auto tmp = select(m_cond_cl, m1_cl, tmp2);
  matrix_cl<double> res_cl = tmp;

  MatrixXd res = stan::math::from_matrix_cl(res_cl);

  MatrixXd correct = m_cond.select(m1, m_cond2.select(m2.cast<double>(), m3));
  EXPECT_MATRIX_NEAR(res, correct, 1e-9);
}

#endif

max_stars_repo_name: HaoZeke/math

max_issues_repo_name: HaoZeke/math

max_forks_repo_name: SteveBronder/math


text:
/*
 *
 * Copyright (C) 2021 Intel Corporation
 *
 * SPDX-License-Identifier: MIT
 *
 */

#include <boost/process.hpp>
#include <boost/filesystem.hpp>

#include "gtest/gtest.h"

#include "utils/utils.hpp"
#include "test_harness/test_harness.hpp"
#include "logging/logging.hpp"

namespace bp = boost::process;
namespace fs = boost::filesystem;

namespace lzt = level_zero_tests;

#include <level_zero/ze_api.h>

namespace {

static void run_child_process(std::string driver_id, std::string affinity_mask,
                              uint32_t num_devices_mask) {
  auto env = boost::this_process::environment();
  bp::environment child_env = env;
  child_env["ZE_AFFINITY_MASK"] = affinity_mask;

  fs::path helper_path(boost::filesystem::current_path() / "device");
  std::vector<boost::filesystem::path> paths;
  paths.push_back(helper_path);
  bp::ipstream child_output;
  fs::path helper = bp::search_path("test_affinity_helper", paths);
  bp::child get_devices_process(helper, driver_id, child_env,
                                bp::std_out > child_output);
  get_devices_process.wait();

  int num_devices_child = -1;
  std::string result_string;
  std::getline(child_output, result_string);

  LOG_INFO << "[Affinity Mask: " << affinity_mask << "]";
  LOG_INFO << "Result from Child: " << result_string;

  auto result_code =
      std::stoul(result_string.substr(0, result_string.find(":")));
  if (result_code) {
    std::getline(child_output, result_string);
    ADD_FAILURE() << "Child process exited with error getting driver devices: "
                  << result_string;
  } else {
    num_devices_child =
        std::stoul(result_string.substr(result_string.find(":") + 1));
    EXPECT_EQ(num_devices_child, num_devices_mask);
  }
}

TEST(
    TestAffinity,
    GivenAffinityMaskSetWhenGettingDevicesThenCorrectNumberOfDevicesReturnedInAllCases) {

  std::string affinity_mask = "";

  for (auto driver : lzt::get_all_driver_handles()) {
    auto devices = lzt::get_devices(driver);
    uint32_t num_total_devices = 0;
    if (devices.empty()) {
      continue;
    }
    for (auto device : devices) {
      auto num_sub_devices = lzt::get_sub_device_count(device);
      num_total_devices += num_sub_devices ? num_sub_devices : 1;
    }

    // in each mask, either a device is present or it is not,
    // so for N devices there are 2^N possible masks
    auto num_masks = 1 << num_total_devices;
    for (uint32_t mask = 0; mask < num_masks; mask++) {
      uint32_t num_devices_mask = 0;
      auto temp = mask;
      while (temp) {
        num_devices_mask += temp & 0x1;
        temp >>= 1;
      }
      // an unset mask means all devices should be returned
      if (num_devices_mask == 0) {
        num_devices_mask = num_total_devices;
      }

      // build this affinity mask string
      std::stringstream os;
      auto temp_mask = mask;
      for (int root_device = 0; root_device < devices.size(); root_device++) {
        uint32_t num_sub_devices_in_mask = 0;
        std::vector<int> sub_devices;
        auto num_sub_devices = lzt::get_sub_device_count(devices[root_device]);

        for (int i = 0; i < num_sub_devices; i++) {
          if (temp_mask & 0x01) { // include this subdevice?
            num_sub_devices_in_mask++;
            // save this subdevice
            sub_devices.push_back(i);
          }
          temp_mask >>= 1;
        }

        if (num_sub_devices == 0) {
          if (os.rdbuf()->in_avail()) {
            os << ",";
          }
          os << ((temp_mask & 0x1) ? std::to_string(root_device) : "");
          temp_mask >>= 1;
        } else if (!num_sub_devices_in_mask) { // no subdevices specified, don't
                                               // include this device
          os << "";
        } else if (num_sub_devices_in_mask ==
                   num_sub_devices) { // all subdevices specified
          if (os.rdbuf()->in_avail()) {
            os << ",";
          }
          os << root_device;
        } else { // specific devices should be listed
          if (os.rdbuf()->in_avail()) {
            os << ",";
          }
          for (int j = 0; j < sub_devices.size() - 1; j++) {
            os << root_device << "." << sub_devices[j];
            os << ",";
          }
          os << root_device << "." << sub_devices[sub_devices.size() - 1];
        }
      }
      affinity_mask = os.str();

      // launch child process with constructed mask
      auto driver_properties = lzt::get_driver_properties(driver);
      // most significant 32-bits of UUID are timestamp, which can change, so
      // zero-out least significant 32-bits are driver version
      memset(&driver_properties.uuid.id[4], 0, 4);
      run_child_process(lzt::to_string(driver_properties.uuid), affinity_mask,
                        num_devices_mask);
    }
  }
}

TEST(TestAffinity,
     GivenAffinityMaskSetWhenGettingDevicesThenCorrectNumberOfDevicesReturned) {
  auto driver = lzt::get_default_driver();
  auto devices = lzt::get_devices(driver);

  if (devices.size() < 2) {
    LOG_WARNING << "Test not executed due to not enough devices";
    return;
  }

  uint32_t num_total_devices = 0;
  for (int i = 0; i < devices.size(); i++) {
    auto num_sub_devices = lzt::get_sub_device_count(devices[i]);
    num_total_devices += num_sub_devices ? num_sub_devices : 1;
  }

  auto mask1 = "";
  auto mask2 = "0";
  auto mask3 = "1";
  auto mask4 = "0,1";

  auto driver_properties = lzt::get_driver_properties(driver);
  memset(&driver_properties.uuid.id[4], 0, 4);
  run_child_process(lzt::to_string(driver_properties.uuid), mask1,
                    num_total_devices);
  run_child_process(lzt::to_string(driver_properties.uuid), mask2,
                    lzt::get_ze_sub_device_count(devices[0]));
  run_child_process(lzt::to_string(driver_properties.uuid), mask3,
                    lzt::get_ze_sub_device_count(devices[1]));
  run_child_process(lzt::to_string(driver_properties.uuid), mask4,
                    lzt::get_ze_sub_device_count(devices[0]) +
                        lzt::get_ze_sub_device_count(devices[1]));
}

TEST(
    TestAffinity,
    GivenAffinityMaskSetWhenGettingSubDevicesThenCorrectNumberOfSubDevicesReturned) {
  auto driver = lzt::get_default_driver();
  auto devices = lzt::get_devices(driver);

  if (lzt::get_ze_sub_device_count(devices[0]) < 2) {
    LOG_WARNING << "Test not executed due to not enough devices/sub_devices";
    return;
  }

  auto mask1 = "0";
  auto mask2 = "0.0";
  auto mask3 = "0.1";
  auto mask4 = "0.1,0.0";

  auto driver_properties = lzt::get_driver_properties(driver);
  memset(&driver_properties.uuid.id[4], 0, 4);
  run_child_process(lzt::to_string(driver_properties.uuid), mask1,
                    lzt::get_ze_sub_device_count(devices[0]));
  run_child_process(lzt::to_string(driver_properties.uuid), mask2, 1);
  run_child_process(lzt::to_string(driver_properties.uuid), mask3, 1);
  run_child_process(lzt::to_string(driver_properties.uuid), mask4, 2);
}

} // namespace

max_stars_repo_name: TApplencourt/level-zero-tests

max_issues_repo_name: TApplencourt/level-zero-tests

max_forks_repo_name: TApplencourt/level-zero-tests


text:
#include "Gui/mainwindow.h"
#include <QApplication>
#include <QDir>
#include <QTemporaryDir>
#include <QDebug>
//#include <3rdparty/qtdotnetstyle.h>
#include "Core/Logging.h"
#include <boost/filesystem/path.hpp>
#include <boost/locale.hpp>
#include "Core/CommonDefs.h"
#include "Core/ServiceLocator.h"
#include "Core/AppParams.h"

#include "QtUploadErrorHandler.h"
#include "QtDefaultLogger.h"
#include "QtScriptDialogProvider.h"
#include "Gui/LogWindow.h"

#include <Core/Settings/QtGuiSettings.h>
#include <QMessageBox>
#include "Core/i18n/Translator.h"
#include "versioninfo.h"

#ifdef _WIN32
CAppModule _Module;
QString dataFolder = "Data/";
#else
QString dataFolder = "/usr/share/imageuploader/";
#endif
QtGuiSettings Settings;

class Translator : public ITranslator {
public:
	std::string getCurrentLanguage() override {
		return "English";
	}
	std::string getCurrentLocale() override {
		return "en_US";
	}
	std::string translate(const char* str) override {
		return str;
	}
#ifdef _WIN32
	const wchar_t* translateW(const wchar_t* str) override {
		return str;
	}
#endif
};
Translator translator; // dummy translator

int main(int argc, char *argv[])
{
    ServiceLocator::instance()->setSettings(&Settings);
#if defined(_WIN32) && !defined(NDEBUG)
    // These global strings in GLOG are initially reserved with a small
    // amount of storage space (16 bytes). Resizing the string larger than its
    // initial size, after the _CrtMemCheckpoint call, can be reported as
    // a memory leak.
    // So for 'debug builds', where memory leak checking is performed,
    // reserve a large enough space so the string will not be resized later.
    // For these variables, _MAX_PATH should be fine.
    FLAGS_log_dir.reserve(_MAX_PATH);  // comment out this line to trigger false memory leak
    FLAGS_log_link.reserve(_MAX_PATH);
    FLAGS_logtostderr = false;
    FLAGS_alsologtostderr = true;
    // Enable memory dump from within VS.
#else
        FLAGS_logtostderr = true;
#endif

    google::InitGoogleLogging(argv[0]);
    AppParams::AppVersionInfo appVersion;
    appVersion.FullVersion = IU_APP_VER;
    appVersion.FullVersionClean = IU_APP_VER_CLEAN;
    appVersion.Build = std::stoi(IU_BUILD_NUMBER);
    appVersion.BuildDate = IU_BUILD_DATE;
    appVersion.CommitHash = IU_COMMIT_HASH;
    appVersion.CommitHashShort = IU_COMMIT_HASH_SHORT;
    appVersion.BranchName = IU_BRANCH_NAME;
    AppParams::instance()->setVersionInfo(appVersion);

	QApplication a(argc, argv);
    LogWindow logWindow;
	logWindow.show();
	auto logger = std::make_shared<QtDefaultLogger>(&logWindow);
	auto errorHandler = std::make_shared<QtUploadErrorHandler>(logger.get());
	QtScriptDialogProvider dlgProvider;
	ServiceLocator::instance()->setTranslator(&translator);
	ServiceLocator::instance()->setUploadErrorHandler(errorHandler);
	ServiceLocator::instance()->setLogger(logger);
	ServiceLocator::instance()->setDialogProvider(&dlgProvider);
    QString appDirectory = QCoreApplication::applicationDirPath();
    QString settingsFolder;
    setlocale(LC_ALL, "");

    if(QFileInfo::exists(appDirectory + "/Data/servers.xml")){
        dataFolder = appDirectory+"/Data/";
        settingsFolder = dataFolder;
    }
#ifndef _WIN32
   else {
dataFolder = "/usr/share/zenden2k-imageuploader/";
   }

#ifndef __APPLE__
settingsFolder = getenv("HOME")+QString("/.config/zenden2k-imageuploader/");
QDir settingsDir = QDir::root();
settingsDir.mkpath(settingsFolder);
#endif

#endif
    qDebug() << "Data directory:" << dataFolder;
    qDebug() << "Settings directory:" << settingsFolder;
    AppParams* params = AppParams::instance();
    params->setDataDirectory(Q2U(dataFolder));
    params->setSettingsDirectory(Q2U(settingsFolder));

    QTemporaryDir dir;
    if (dir.isValid()) {
        params->setTempDirectory(Q2U(dir.path()));
    } else {
        LOG(ERROR) << "Unable to create temp directory!";
    }

	Settings.LoadSettings(AppParams::instance()->settingsDirectory());
	auto engineList = std::make_unique<CUploadEngineList>();
	if (!engineList->loadFromFile(AppParams::instance()->dataDirectory() + "servers.xml", Settings.ServersSettings)) {
		QMessageBox::warning(nullptr, "Failure", "Unable to load servers.xml");
	}
    ServiceLocator::instance()->setEngineList(engineList.get());
    //google::AddLogSink(&logSink);
    //serviceLocator->setUploadErrorHandler(&uploadErrorHandler);
    //serviceLocator->setLogger(&defaultLogger);

	Settings.setEngineList(engineList.get());

    //QApplication::setStyle(new QtDotNetStyle);
    MainWindow w(engineList.get(), &logWindow);
    w.show();

    int res =  a.exec();

    //google::RemoveLogSink(&logSink);
	Settings.SaveSettings();
    google::ShutdownGoogleLogging();
    return res;
}

max_stars_repo_name: igor-sadchenko/image-uploader

max_issues_repo_name: igor-sadchenko/image-uploader

max_forks_repo_name: igor-sadchenko/image-uploader


text:
#include "main.h"

#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
#include <string>
// there are other ways of getting a path relative to the executable, but this
// one is part of the STL soon (if you can talk about soon in c++ development)
#include <boost/filesystem.hpp>
using boost::filesystem::absolute;

// when testing, the main of gtest and this main function will collide,
// this prevents the collision, but it's an ugly hack like all ifdef branches
#ifdef UNIT_TESTS
#define MAIN not_main
#else
#define MAIN main
#endif

int MAIN(int argc, char** argv) {
  // this way you can have a path relative to the executable
  // the absolute also gets rid of symlinks, so it should work pretty stable
  auto resource_path = absolute(argv[0]).parent_path() / "resources";
  std::fstream resource1((resource_path / "resource1").string());
  std::string line;
  while(resource1) {
    std::getline(resource1, line);
    cout << line << endl;
  }
  return EXIT_SUCCESS;
}

// just some function to have something that can be test
#include <exception>

void GetFrobnicationInterval() {
  throw std::string("InvalidOperation: frobnication interval can't be retrieved");
}

max_stars_repo_name: CassieEllen/jcbchat

max_issues_repo_name: CassieEllen/jcbchat

max_forks_repo_name: CassieEllen/jcbchat


text:
//
// Copyright (c) 2019-2020 Kris Jusiak (kris at jusiak dot net)
//
// 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)
//
#include <boost/ut.hpp>
#include <string_view>

namespace ut = boost::ut;

namespace cfg {
class reporter {
 public:
  auto on(ut::events::test_begin) -> void {}
  auto on(ut::events::test_run) -> void {}
  auto on(ut::events::test_skip) -> void {}
  auto on(ut::events::test_end) -> void {}
  template <class TMsg>
  auto on(ut::events::log<TMsg>) -> void {}
  template <class TExpr>
  auto on(ut::events::assertion_pass<TExpr>) -> void {}
  template <class TExpr>
  auto on(ut::events::assertion_fail<TExpr>) -> void {}
  auto on(ut::events::fatal_assertion) -> void {}
  auto on(ut::events::exception) -> void {}
  auto on(ut::events::summary) -> void {}
};
}  // namespace cfg

template <>
auto ut::cfg<ut::override> = ut::runner<cfg::reporter>{};

int main() {
  using namespace ut;
  using namespace std::literals::string_view_literals;

  "example"_test = [] {
    expect(42 == 42_i);
    expect("ut"sv != "tu"sv);
  };
}

max_stars_repo_name: ambushed/ut

max_issues_repo_name: ambushed/ut

max_forks_repo_name: ambushed/ut


text:
/*
The MIT License (MIT)

Copyright (c) 2013-2014 BitTorrent Inc.
Copyright (c) 2016 Arvid Norberg

author: Arvid Norberg & Steven Siloti

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

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

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

#pragma once

#include <unordered_set>
#include <cstdint>
#include <array>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/asio/ip/address_v6.hpp>

#include "city.h"

// The size of ipv6_prefix_type determines the size of the prefix to compare
// when determining if an IPv6 address should be discarded as a duplicate
using ipv6_prefix_type = std::array<std::uint8_t, 6>;

using boost::asio::ip::address_v4;
using boost::asio::ip::address_v6;

extern std::uint64_t hash_seed;

template <typename T, typename K>
void erase_one(T& container, K const& key)
{
	typename T::iterator i = container.find(key);
	assert(i != container.end());
	container.erase(i);
}

inline ipv6_prefix_type extract_key(address_v6 const& addr)
{
	ipv6_prefix_type ip6;
	std::memcpy(ip6.data(), addr.to_bytes().data(), ip6.size());
	return ip6;
}

inline address_v4::bytes_type extract_key(address_v4 const& addr)
{
	return addr.to_bytes();
}

namespace std {

template <>
struct hash<address_v4::bytes_type>
{
	size_t operator()(address_v4::bytes_type ip) const
	{
		return CityHash64WithSeed(reinterpret_cast<char const*>(&ip[0]), ip.size(), hash_seed);
	}
};

template <>
struct hash<ipv6_prefix_type>
{
	size_t operator()(ipv6_prefix_type const ip) const
	{
		return CityHash64WithSeed(reinterpret_cast<char const*>(&ip[0]), ip.size(), hash_seed);
	}
};

} // namespace std

template <typename Address>
struct ip_set
{
	// returns true if the address was not already in the set
	bool insert(Address const& addr)
	{ return m_ips.insert(extract_key(addr)).second; }

	size_t count(Address const& addr) const
	{ return m_ips.count(extract_key(addr)); }

	void erase(Address const& addr)
	{ erase_one(m_ips, extract_key(addr)); }

	bool operator==(ip_set const& rh) const
	{ return m_ips == rh.m_ips; }

	size_t size() const { return m_ips.size(); }
	void clear() { m_ips.clear(); }

private:
	std::unordered_set<decltype(extract_key(std::declval<Address>()))> m_ips;
};

ext: hpp


text:
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
using namespace std;

#include <boost/iterator/permutation_iterator.hpp>
using namespace boost;

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

void case1()
{
    char s[] = "abcdefg";
    int idx[] = {6, 0, 2, 2, 4};

    std::copy(
        make_permutation_iterator(s, idx),
        make_permutation_iterator(s, idx + 5),
        ostream_iterator<char>(cout, " ")
        );

}

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

int main()
{
    std::cout << "hello permutation_iterator" << std::endl;

    case1();
}


text:
/**
 * @file
 * @brief Reads meshes containing second order elements and performs refinement
 * @author Anian Ruoss
 * @date   24.02.2019 18:24:17
 * @copyright MIT License
 */

#include <lf/base/base.h>
#include <lf/io/io.h>
#include <lf/mesh/hybrid2d/hybrid2d.h>
#include <lf/mesh/mesh.h>
#include <lf/refinement/mesh_hierarchy.h>
#include <boost/filesystem.hpp>
#include <iostream>

using lf::io::TikzOutputCtrl;

int main() {
  boost::filesystem::path file_path = __FILE__;

  for (const std::string& mesh_name :
       {"square_quads.msh", "square_trias.msh"}) {
    auto mesh_path = file_path.parent_path() / "meshes" / mesh_name;

    // read mesh from file
    auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);
    const lf::io::GmshReader reader(std::move(mesh_factory),
                                    mesh_path.string());

    // create mesh hierarchy from mesh for refinement
    lf::refinement::MeshHierarchy multi_mesh(
        std::const_pointer_cast<lf::mesh::Mesh>(reader.mesh()),
        std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2));

    int refinement_steps = 2;

    for (int step = 0; step < refinement_steps; ++step) {
      // refine mesh and store to TikZ
      multi_mesh.RefineRegular();
      auto mesh = multi_mesh.getMesh(multi_mesh.NumLevels() - 1);
      lf::io::writeTikZ(
          *mesh,
          mesh_name.substr(0, mesh_name.find_last_of('.')) + "_" +
              std::to_string(step) + ".tex",
          TikzOutputCtrl::RenderCells | TikzOutputCtrl::CellNumbering |
              TikzOutputCtrl::VerticeNumbering | TikzOutputCtrl::NodeNumbering |
              TikzOutputCtrl::EdgeNumbering);
    }
  }

  return 0;
}

ext: cc

max_stars_repo_name: Pascal-So/lehrfempp

max_issues_repo_name: Pascal-So/lehrfempp

max_forks_repo_name: Pascal-So/lehrfempp


text:
#ifndef CANARD_NET_OFP_V10_BYTEORDER_CONVERSION_HPP
#define CANARD_NET_OFP_V10_BYTEORDER_CONVERSION_HPP

#include <boost/endian/conversion.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <canard/net/ofp/v10/detail/fusion_adaptor.hpp>
#include <canard/net/ofp/v10/openflow.hpp>

namespace canard {
namespace net {
namespace ofp {
namespace v10 {
namespace protocol {

  struct generic_endian_reverse_inplace
  {
    template <class Field>
    void operator()(Field& field) const noexcept
    {
      using boost::endian::endian_reverse_inplace;
      endian_reverse_inplace(field);
    }

    template <class T, std::size_t N>
    void operator()(T (&field)[N]) const noexcept
    {
      using boost::endian::endian_reverse_inplace;
      for (T& e : field) { endian_reverse_inplace(e); }
    }

    template <std::size_t N>
    void operator()(char (&)[N]) const noexcept {}

    template <std::size_t N>
    void operator()(std::uint8_t (&)[N]) const noexcept {}
  };

  inline void endian_reverse_inplace(ofp_header& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_header data) noexcept
    -> ofp_header
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_hello& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_hello data) noexcept
    -> ofp_hello
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_switch_config& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_switch_config data) noexcept
    -> ofp_switch_config
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_phy_port& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_phy_port data) noexcept
    -> ofp_phy_port
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_switch_features& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_switch_features data) noexcept
    -> ofp_switch_features
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_port_status& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_port_status data) noexcept
    -> ofp_port_status
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_port_mod& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_port_mod data) noexcept
    -> ofp_port_mod
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_packet_in& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_packet_in data) noexcept
    -> ofp_packet_in
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_output& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_output data) noexcept
    -> ofp_action_output
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_vlan_vid& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_vlan_vid data) noexcept
    -> ofp_action_vlan_vid
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_vlan_pcp& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_vlan_pcp data) noexcept
    -> ofp_action_vlan_pcp
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_dl_addr& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_dl_addr data) noexcept
    -> ofp_action_dl_addr
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_nw_addr& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_nw_addr data) noexcept
    -> ofp_action_nw_addr
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_tp_port& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_tp_port data) noexcept
    -> ofp_action_tp_port
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_nw_tos& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_nw_tos data) noexcept
    -> ofp_action_nw_tos
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_vendor_header& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_vendor_header data) noexcept
    -> ofp_action_vendor_header
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_header& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_header data) noexcept
    -> ofp_action_header
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_packet_out& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_packet_out data) noexcept
    -> ofp_packet_out
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_match& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_match data) noexcept
    -> ofp_match
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_flow_mod& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_flow_mod data) noexcept
    -> ofp_flow_mod
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_flow_removed& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_flow_removed data) noexcept
    -> ofp_flow_removed
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_error_msg& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_error_msg data) noexcept
    -> ofp_error_msg
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_stats_request& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_stats_request data) noexcept
    -> ofp_stats_request
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_stats_reply& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_stats_reply data) noexcept
    -> ofp_stats_reply
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_desc_stats& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_desc_stats data) noexcept
    -> ofp_desc_stats
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_flow_stats_request& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_flow_stats_request data) noexcept
    -> ofp_flow_stats_request
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_flow_stats& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_flow_stats data) noexcept
    -> ofp_flow_stats
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_aggregate_stats_request& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_aggregate_stats_request data) noexcept
    -> ofp_aggregate_stats_request
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_aggregate_stats_reply& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_aggregate_stats_reply data) noexcept
    -> ofp_aggregate_stats_reply
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_table_stats& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_table_stats data) noexcept
    -> ofp_table_stats
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_port_stats_request& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_port_stats_request data) noexcept
    -> ofp_port_stats_request
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_port_stats& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_port_stats data) noexcept
    -> ofp_port_stats
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_vendor_header& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_vendor_header data) noexcept
    -> ofp_vendor_header
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_queue_prop_header& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_queue_prop_header data) noexcept
    -> ofp_queue_prop_header
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_queue_prop_min_rate& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_queue_prop_min_rate data) noexcept
    -> ofp_queue_prop_min_rate
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_packet_queue& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_packet_queue data) noexcept
    -> ofp_packet_queue
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_queue_get_config_request& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_queue_get_config_request data) noexcept
    -> ofp_queue_get_config_request
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_queue_get_config_reply& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_queue_get_config_reply data) noexcept
    -> ofp_queue_get_config_reply
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_action_enqueue& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_action_enqueue data) noexcept
    -> ofp_action_enqueue
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_queue_stats_request& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_queue_stats_request data) noexcept
    -> ofp_queue_stats_request
  {
    endian_reverse_inplace(data);
    return data;
  }

  inline void endian_reverse_inplace(ofp_queue_stats& data) noexcept
  {
    boost::fusion::for_each(data, generic_endian_reverse_inplace{});
  }

  inline auto endian_reverse(ofp_queue_stats data) noexcept
    -> ofp_queue_stats
  {
    endian_reverse_inplace(data);
    return data;
  }

} // namespace protocol
} // namespace v10
} // namespace ofp
} // namespace net
} // namespace canard

#endif // CANARD_NET_OFP_V10_BYTEORDER_CONVERSION_HPP


text:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/member.hpp>
#include <string>
#include <iostream>

using namespace boost::multi_index;

struct animal
{
  std::string name;
  int legs;
};

typedef multi_index_container<
  animal,
  indexed_by<
    sequenced<>,
    ordered_non_unique<
      member<
        animal, int, &animal::legs
      >
    >,
    random_access<>
  >
> animal_multi;

int main()
{
  animal_multi animals;

  animals.push_back({"cat", 4});
  animals.push_back({"shark", 0});
  animals.push_back({"spider", 8});

  auto &legs_index = animals.get<1>();
  auto it = legs_index.lower_bound(4);
  auto end = legs_index.upper_bound(8);
  for (; it != end; ++it)
    std::cout << it->name << '\n';

  const auto &rand_index = animals.get<2>();
  std::cout << rand_index[0].name << '\n';
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
#include <FalconEngine/Core/Path.h>
#include <FalconEngine/Core/Exception.h>

#include <boost/filesystem.hpp>

using namespace boost;
using namespace std;

namespace FalconEngine
{

string
GetCurrentPath()
{
    return filesystem::current_path().string() + FALCON_ENGINE_DIRECTORY_SEPARATOR;
}

string
GetFileDirectory(const string& path)
{
    return filesystem::path(path).parent_path().string() + FALCON_ENGINE_DIRECTORY_SEPARATOR;
}

bool
GetFileExist(const string& relativePath)
{
    return filesystem::exists(GetCurrentPath() + relativePath);
}

string
GetFileName(const string& path)
{
    // http://stackoverflow.com/questions/4430780/how-can-i-extract-the-file-name-and-extension-from-a-path-in-c
    return filesystem::path(path).filename().string();
}

// ReSharper disable once CppNotAllPathsReturnValue
ifstream::pos_type
GetFileSize(const string& relativePath)
{
    // http://stackoverflow.com/questions/5840148/how-can-i-get-a-files-size-in-c
    if (GetFileExist(relativePath))
    {
        ifstream fileStream(relativePath, ifstream::ate | ifstream::binary);
        return fileStream.tellg();
    }

    FALCON_ENGINE_THROW_RUNTIME_EXCEPTION("File not found.");
}

std::string
GetFileStem(const std::string& path)
{
    return filesystem::path(path).stem().string();
}

string
GetFileExtension(const std::string& path)
{
    // http://stackoverflow.com/questions/959837/how-can-i-know-the-type-of-a-file-using-boost-filesystem
    return filesystem::path(path).extension().string();
}

string
ChangeFileExtension(const string& path, const string& extension)
{
    return filesystem::path(path).replace_extension(extension).string();
}

std::string
RemoveFileExtension(const std::string& path)
{
    return filesystem::path(path).replace_extension("").string();
}

// Return true if successful.
// Return false if there is already a directory named as given or other IO errors happen.
bool
CreateDirectory(const string& relativePath)
{
    auto path = GetCurrentPath() + relativePath;
    return filesystem::create_directory(path);
}

}

max_stars_repo_name: Lywx/FalconEngine

max_issues_repo_name: Lywx/FalconEngine

max_forks_repo_name: Lywx/FalconEngine


text:
//
//  Created by Robert Binna
//

#include <utility>

#include <boost/test/unit_test.hpp>

#include <idx/contenthelpers/PairKeyExtractor.hpp>

#include <idx/benchmark/BenchmarkEvent.hpp>
#include <idx/benchmark/BenchmarkEventListBackingBufferSizeEstimator.hpp>
#include <idx/benchmark/BenchmarkEventList.hpp>
#include <idx/benchmark/BenchmarkEventTypeId.hpp>
#include <idx/benchmark/BenchmarkLineReader.hpp>

namespace idx { namespace benchmark {

BOOST_AUTO_TEST_SUITE(BenchmarkEventListBackingBufferSizeEstimatorTest)

template <BenchmarkEventTypeId eventTypeId> using EventType = BenchmarkEvent<eventTypeId, std::pair<const char*, uint64_t>, idx::contenthelpers::PairKeyExtractor>;

BOOST_AUTO_TEST_CASE(createAndIterateBenchmarkEventList) {
	BenchmarkLineReader<std::pair<const char*, uint64_t>, idx::contenthelpers::PairKeyExtractor> readLine;

	std::array<std::string, 4> lines {
		"INSERT \"fourty four\" 42",
		"UPDATE \"fourty three\" 43",
		"SCAN \"fourty two\" 20",
		"READ \"fourty three\""
	};

	for(size_t linesToTest = 1; linesToTest <= lines.size(); ++linesToTest) {
		BenchmarkEventListBackingBuferSizeEstimator sizeEstimator {  };

		//std::cout << "test for " << linesToTest << " lines" << std::endl;
		for (size_t i = 0; i < linesToTest; ++i) {
			sizeEstimator.addEvent(readLine, lines[i], i + 1);
		}
		BenchmarkEventList events{sizeEstimator.getTotalBufferSize()};

		for (size_t i = 0; i < linesToTest; ++i) {
			events.addEvent(readLine, lines[i], i + 1);
		}
		size_t i = 0;
		BenchmarkBaseEvent const *previousEvent;
		BenchmarkEventTypeId eventTypeIds[]{InsertEventTypeId, UpdateEventTypeId, ScanEventTypeId, LookupEventTypeId};
		for (BenchmarkBaseEvent const &event : events) {
			BOOST_REQUIRE_EQUAL(event.mEventTypeId, eventTypeIds[i]);
			if (i > 0u) {
				BOOST_REQUIRE_EQUAL((void *) previousEvent->mNextEvent, (void *) &event);
			}
			previousEvent = &event;
			++i;
		}
		BOOST_REQUIRE_EQUAL(i, linesToTest);
		BOOST_REQUIRE_EQUAL(events.getRemainingBackingBytes(), 0u);

		BOOST_REQUIRE_EQUAL(events.size(),linesToTest);
	}

}

BOOST_AUTO_TEST_CASE(createAndIterateBenchmarkEventListFixed) {
	BenchmarkLineReader<std::pair<const char*, uint64_t>, idx::contenthelpers::PairKeyExtractor> readLine;
	BenchmarkEventListBackingBuferSizeEstimator sizeEstimator {  };

	sizeEstimator.addEvent(readLine, "INSERT \"fourty four\" 42", 1u);
	sizeEstimator.addEvent(readLine, "UPDATE \"fourty three\" 43", 2u);
	sizeEstimator.addEvent(readLine, "SCAN \"fourty two\" 20", 3u);
	sizeEstimator.addEvent(readLine, "READ \"fourty three\"", 4u);

	BenchmarkEventList events { sizeEstimator.getTotalBufferSize() };

	events.addEvent(readLine, "INSERT \"fourty four\" 42", 1u);
	events.addEvent(readLine, "UPDATE \"fourty three\" 43", 2u);
	events.addEvent(readLine, "SCAN \"fourty two\" 20", 3u);
	events.addEvent(readLine, "READ \"fourty three\"", 4u);

	int i=0;
	BenchmarkBaseEvent const * previousEvent;
	BenchmarkEventTypeId eventTypeIds[] { InsertEventTypeId, UpdateEventTypeId, ScanEventTypeId, LookupEventTypeId };
	for(BenchmarkBaseEvent const & event : events) {
		BOOST_REQUIRE_EQUAL(event.mEventTypeId, eventTypeIds[i]);
		if(i > 0) {
			BOOST_REQUIRE_EQUAL((void*) previousEvent->mNextEvent, (void*) &event);
		}
		previousEvent = &event;
		++i;
	}
	BOOST_REQUIRE_EQUAL(i, 4);
	BOOST_REQUIRE_EQUAL(events.getRemainingBackingBytes(), 0u);
}

BOOST_AUTO_TEST_SUITE_END()

}}

max_stars_repo_name: yishayahu/hot

max_issues_repo_name: SheldonZhong/hot

max_forks_repo_name: SheldonZhong/hot


text:
//          Copyright Oliver Kowalke 2009.
//          Copyright Edvard Severin Pettersen 2017.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE.md or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include <proxc/config.hpp>

#include <boost/intrusive/list.hpp>
#include <boost/intrusive/set.hpp>

PROXC_NAMESPACE_BEGIN

namespace detail {
namespace queue {

namespace intrusive = boost::intrusive;

template<typename T, typename Hook, Hook T::* Ptr>
using MemberHook = intrusive::member_hook<
    T, Hook, Ptr
>;

template<typename T, typename Hook, Hook T::* Ptr>
using ListQueue = intrusive::list<
    T,
    MemberHook< T, Hook, Ptr >,
    intrusive::constant_time_size< false > >;

template<typename T, typename Hook, Hook T::* Ptr, typename Fn>
using SetQueue = intrusive::multiset<
    T,
    MemberHook< T, Hook, Ptr >,
    intrusive::constant_time_size< false >,
    intrusive::compare< Fn > >;

} // namespace queue
} // namespace detail

PROXC_NAMESPACE_END

max_stars_repo_name: edvardsp/libproxc-

max_issues_repo_name: edvardsp/libproxc-

max_forks_repo_name: edvardsp/libproxc-


text:
/*
 * Copyright 2012 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

#ifndef MULTIPATH_SIM_HH
#define MULTIPATH_SIM_HH

#include <string>

#include <boost/bind.hpp>
#include <boost/thread.hpp>

#include <ros/ros.h>
#include <ros/advertise_options.h>
#include <sensor_msgs/LaserScan.h>

#include <sdf/Param.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/transport/TransportTypes.hh>
#include <gazebo/msgs/MessageTypes.hh>
#include <gazebo/common/Time.hh>
#include <gazebo/common/Plugin.hh>
#include <gazebo/common/Events.hh>
#include <gazebo/sensors/SensorTypes.hh>
#include <gazebo/plugins/RayPlugin.hh>
#include <gazebo_plugins/gazebo_ros_utils.h>
#include <gazebo_plugins/PubQueue.h>

#include <visualization_msgs/Marker.h>

// custom message
#include <multipath_sim/MultipathOffset.h>

namespace gazebo
{
  static constexpr double kDefaultUpdateRate = 5.0;               // hz
  static constexpr double kDefaultGpsXYRandomWalk = 2.0;          // (m/s) / sqrt(hz)
  static constexpr double kDefaultGpsZRandomWalk = 4.0;           // (m/s) / sqrt(hz)
  static constexpr double kDefaultGpsXYNoiseDensity = 2.0e-4;     // (m) / sqrt(hz)
  static constexpr double kDefaultGpsZNoiseDensity = 4.0e-4;      // (m) / sqrt(hz)
  class MultipathSimPlugin : public RayPlugin
  {
    /// \brief Constructor
    public: MultipathSimPlugin();

    /// \brief Destructor
    public: ~MultipathSimPlugin();

    /// \brief Load the plugin
    /// \param take in SDF root element
    public: void Load(sensors::SensorPtr _parent, sdf::ElementPtr _sdf);

    /// \brief Keep track of number of connctions
    private: int laser_connect_count_;
    private: void LaserConnect();
    private: void LaserDisconnect();

    // Pointer to the model
    GazeboRosPtr gazebo_ros_;
    private: std::string world_name_;
    private: physics::WorldPtr world_;
    private: physics::EntityPtr parent_entity_;
    /// \brief The parent sensor
    private: sensors::RaySensorPtr parent_ray_sensor_;

    /// \brief pointer to ros node
    private: ros::NodeHandle* rosnode_;
    private: ros::Publisher pub_;
    private: PubQueue<sensor_msgs::LaserScan>::Ptr pub_queue_;
    private: ros::Publisher offset_pub_;
    private: PubQueue<multipath_sim::MultipathOffset>::Ptr offset_pub_queue_;
    private: ros::Publisher sat_ray_pub_;
    private: PubQueue<visualization_msgs::Marker>::Ptr sat_ray_pub_queue_;

    /// \brief topic name
    private: std::string topic_name_;
    private: std::string offset_topic_name_;
    private: std::string sat_ray_topic_name_;

    /// \brief frame transform name, should match link name
    private: std::string frame_name_;

    /// \brief scale factor of error
    private: double error_scale_;

    /// \brief define properties of satellites
    /// TODO: maybe get elevation and azimuth from satellite's lat lon and vehicle's position on earth
    private: int num_sat_;
    private: std::vector<double> sat_dir_elevation_;
    private: std::vector<double> sat_dir_azimuth_;

    private: bool disable_noise_;

    /// \brief tf prefix
    private: std::string tf_prefix_;

    /// \brief for setting ROS name space
    private: std::string robot_namespace_;

    // deferred load in case ros is blocking
    private: sdf::ElementPtr sdf;
    private: void LoadThread();
    private: boost::thread deferred_load_thread_;

    private: gazebo::transport::NodePtr gazebo_node_;
    private: gazebo::transport::SubscriberPtr laser_scan_sub_;
    private: void OnScan(ConstLaserScanStampedPtr &_msg);

    /// \brief prevents blocking
    private: PubMultiQueue pmq;

    common::Time last_gps_time_;
    common::Time last_time_;
    common::Time current_time_;
    common::Time start_time_;
    std::mutex data_mutex_;
    /// return the mirror ray index of the current ray
    private: void setRayAngles(std::vector<double> &ray_ranges);
    ignition::math::Vector3<double> gps_bias_;
    ignition::math::Vector3<double>noise_gps_pos_;
    ignition::math::Vector3<double>random_walk_gps_;

    // Gaussian random walk params
    std::default_random_engine rand_;
    std::normal_distribution<float> randn_;
    static constexpr const double gps_corellation_time_ = 100.0;    // s
    double gps_xy_random_walk_;
    double gps_z_random_walk_;
    double gps_xy_noise_density_;
    double gps_z_noise_density_;
  };
}
#endif

ext: hh


text:
/*
 * Author: Mario Lüder
 * Date: Nov. 2018
 */

#ifndef MOTIONUKF_HPP
#define MOTIONUKF_HPP

#include "Ukf.hpp"
#include "tools.h"

#include <Eigen/Dense>
#include <sstream>

class ProcessModel
{
public:
   struct MotionParams
   {
      double p_x;
      double p_y;
      double v;
      double yaw;
      double yaw_dot;
      double std_a;
      double std_yaw_dot_dot;
   };

   static inline void normalize(const long colIdx, Eigen::MatrixXd &XSigmaPointsDiff)
   {
      double & yaw = XSigmaPointsDiff.col(colIdx)(3);

      // normalize phi to -/+ pi
      Tools::normalizeAngle(yaw);
   }

   static void predictSigmaPoints(const Eigen::MatrixXd & XSigmaPoints, const double d_t_s, Eigen::MatrixXd & XSigmaPointsPred);
   static inline void processModel(const MotionParams & x, const double d_t_s, MotionParams & x_pred);

   //set state dimension
   static constexpr long m_n_x = 5;

   //set augumented state dimension
   static constexpr long m_n_x_aug = 7;

   // constant 2 * PI
   static constexpr double TWO_PI = 2 * M_PI;

   static constexpr long m_nSigmaPoints = 1 + 2 * m_n_x_aug;

   // Process noise standard deviation longitudinal acceleration in m/s^2
   // static constexpr double m_std_a = 0.2;
   static constexpr double m_std_a = 1.5;

   // Process noise standard deviation yaw acceleration in rad/s^2
   // static constexpr double m_std_yawdd = 0.2;
   static constexpr double m_std_yawdd = 1;
};

class MotionUkf : public Ukf<ProcessModel>
{
public:
   MotionUkf()
      : Ukf<ProcessModel>()
   {}

   virtual ~MotionUkf();

   struct Measurement
   {
      Measurement(int32_t dim) : value(dim) {}
      Eigen::VectorXd value;
   };

   struct RadarMeasurement : public Measurement
   {
      RadarMeasurement() : Measurement(3) {}
      RadarMeasurement(std::istringstream & iss)  : Measurement(3)
      {
         double rho;
         double phi;
         double rho_dot;
         iss >> rho;
         iss >> phi;
         iss >> rho_dot;

         value << rho, phi, rho_dot;
      }

      RadarMeasurement & operator=(std::istringstream & iss)
      {
         double rho;
         double phi;
         double rho_dot;
         iss >> rho;
         iss >> phi;
         iss >> rho_dot;

         value << rho, phi, rho_dot;
         return  *this;
      }

      double & rho() {return value(0);}
      double & phi() {return value(1);}
      double & rho_dot() {return value(2);}

      struct Definition
      {
         double rho;
         double phi;
         double rho_dot;
      };

      static Definition * cast(void * data)
      {
         return reinterpret_cast<Definition*>(data);
      }
   };

   struct RadarMeasurementModel
   {
      using MEASUREMENT_T = RadarMeasurement;

      RadarMeasurementModel();

      static inline void normalize(const long colIdx, Eigen::MatrixXd &ZSigmaPointsDiff)
      {
         //double & phi = reinterpret_cast<RadarMeasurement*>(ZSigmaPointsDiff.col(colIdx).data())->phi;
         double & phi = RadarMeasurement::cast(ZSigmaPointsDiff.col(colIdx).data())->phi;

         // normalize phi to -/+ pi
         Tools::normalizeAngle(phi);
      }

      static inline void normalize(Eigen::MatrixXd &matrix)
      {
         const int cols = matrix.cols();

         for (int colIdx = 0; colIdx < cols; ++colIdx)
         {
            normalize(colIdx, matrix);
         }
      }

      static inline void normalize(Eigen::VectorXd &vector)
      {
         double & phi = RadarMeasurement::cast(vector.data())->phi;

         // normalize phi to -/+ pi
         Tools::normalizeAngle(phi);
      }

      void predictCovar(const Ukf<ProcessModel> & ukf, const Eigen::MatrixXd & XSigmaPoints, const Eigen::VectorXd & x_pred, Eigen::MatrixXd & P_pred) const;
      void predictMeasurement(const Eigen::MatrixXd & XSigmaPointPred, Eigen::MatrixXd & ZSigmaPointsRadarPred) const;

      static constexpr long nRadarValues = 3;

      //radar measurement noise standard deviation radius in m
      const double m_std_radr = 0.3;

      //radar measurement noise standard deviation angle in rad
      const double m_std_radphi = 0.03;

      //radar measurement noise standard deviation radius change in m/s
      const double m_std_radrd = 0.3;

      MEASUREMENT_T measurement;

      // NIS
      double m_nis = 0.0;

   private:
      Eigen::MatrixXd m_R;
   };

   struct LaserMeasurement : public Measurement
   {
      LaserMeasurement() : Measurement(2) {}
      LaserMeasurement(std::istringstream & iss) : Measurement(2)
      {
         double px;
         double py;
         iss >> px;
         iss >> py;
         value << px , py;
      }

      LaserMeasurement & operator=(std::istringstream & iss)
      {
         double px;
         double py;
         iss >> px;
         iss >> py;
         value << px, py;
         return *this;
      }

      double & px() {return value(0);}
      double & py() {return value(1);}

      struct Definition
      {
         double px;
         double py;
      };

      static Definition * cast(void * data)
      {
         return reinterpret_cast<Definition*>(data);
      }
   };

   struct LaserMeasurementModel
   {
      using MEASUREMENT_T = LaserMeasurement;

      LaserMeasurementModel();

      static inline void normalize(const long colIdx, Eigen::MatrixXd &ZSigmaPointsDiff)
      {
         (void)colIdx;
         (void)ZSigmaPointsDiff;
         // nothing to normalize
      }

      static inline void normalize(Eigen::MatrixXd &matrix)
      {
         (void)matrix;
      }

      static inline void normalize(Eigen::VectorXd &vector)
      {
         (void)vector;
      }

      void predictCovar(const Ukf<ProcessModel> & ukf, const Eigen::MatrixXd & XSigmaPoints, const Eigen::VectorXd & x_pred, Eigen::MatrixXd & P_pred) const;
      void predictMeasurement(const Eigen::MatrixXd & XSigmaPointPred, Eigen::MatrixXd & ZSigmaPointsLaserPred) const;

      // Process noise standard deviation longitudinal acceleration in m/s^2
      double m_std_a = 30;

      //laser measurement noise standard deviation (position) in m
      const double m_std_laser_pos = 0.15;

      static constexpr long nLaserValues = 2;

      MEASUREMENT_T measurement;

      // NIS
      double m_nis = 0.0;
   private:

      // Laser Measurement Covariance Matrix
      Eigen::MatrixXd m_L;
   };

   template<typename MEASUREMENTMODEL_T>
   void processMeasurement(MEASUREMENTMODEL_T & measurementModel, int64_t timestamp_us)
   {
      Ukf<ProcessModel>::processMeasurement<typename MEASUREMENTMODEL_T::MEASUREMENT_T, MEASUREMENTMODEL_T>(measurementModel.measurement, measurementModel, timestamp_us);
   }

   void init(const LaserMeasurementModel & laserMeasurementModel, int64_t timestamp_us)
   {
      Ukf<ProcessModel>::setNewTime(timestamp_us);
      m_x.setZero(ProcessModel::m_n_x);

      // set initial x pos
      m_x(0) = laserMeasurementModel.measurement.value(0);

      // set initial y pos
      m_x(1) = laserMeasurementModel.measurement.value(1);

      // initialize process noise
      m_std.setZero(2);
      m_std(0) = ProcessModel::m_std_a;
      m_std(1) = ProcessModel::m_std_yawdd;
   }

   RadarMeasurementModel radarMeasurementModel;
   LaserMeasurementModel laserMeasurementModel;
};

#endif // MOTIONUKF_HPP


text:
#pragma once

// first includes
#include <boost/config.hpp>
#include <boost/system/api_config.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/optional.hpp>

namespace bunsan {
namespace process {
namespace file {

class handle {
 public:
#if defined(BOOST_POSIX_API)
  using implementation = int;
#elif defined(BOOST_WINDOWS_API)
  using implementation = void *;
#endif

  handle() = default;
  ~handle();

  explicit handle(implementation fd);
  handle(implementation fd, bool close);

  handle(const handle &) = delete;
  handle(handle &&);

  handle &operator=(const handle &) = delete;
  handle &operator=(handle &&);

  explicit operator bool() const { return static_cast<bool>(m_fd); }
  implementation operator*() const { return *m_fd; }

  void reset();
  void reset(implementation fd);
  void close();
  void close_no_except() noexcept;

  void swap(handle &o) noexcept {
    using std::swap;

    swap(m_fd, o.m_fd);
    swap(m_close, o.m_close);
  }

  handle dup() const;

#if defined(BOOST_POSIX_API)
  handle dup2(implementation new_fd) const;
#endif

  bool inheritable() const;
  void set_inheritable(bool inheritable=true);

  static handle open_null();  // /dev/null, NUL, ...
  static handle open_read(const boost::filesystem::path &path);
  static handle open_write(const boost::filesystem::path &path);
  static handle open_read_write(const boost::filesystem::path &path);
  static handle open_append(const boost::filesystem::path &path);

  static handle std_input();
  static handle std_output();
  static handle std_error();

 private:
  boost::optional<implementation> m_fd;
  bool m_close = true;
};

inline void swap(handle &a, handle &b) noexcept { a.swap(b); }

}  // namespace file
}  // namespace process
}  // namespace bunsan


text:
/**
 *-----------------------------------------------------------------------------
 * Title         : SMuRF Data Base Transmitter Channel
 * ----------------------------------------------------------------------------
 * File          : BaseTransmitterChannel.cpp
 * Created       : 2019-09-27
 *-----------------------------------------------------------------------------
 * Description :
 *   SMuRF Data Base Transmitter Class, channel interface
 *-----------------------------------------------------------------------------
 * This file is part of the smurf software platform. It is subject to
 * the license terms in the LICENSE.txt file found in the top-level directory
 * of this distribution and at:
    * https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
 * No part of the smurf software platform, including this file, may be
 * copied, modified, propagated, or distributed except according to the terms
 * contained in the LICENSE.txt file.
 *-----------------------------------------------------------------------------
**/

#include <boost/python.hpp>
#include "smurf/core/transmitters/BaseTransmitterChannel.h"
#include "smurf/core/transmitters/BaseTransmitter.h"

namespace bp  = boost::python;
namespace sct = smurf::core::transmitters;

sct::BaseTransmitterChannel::BaseTransmitterChannel(sct::BaseTransmitterPtr bt, uint32_t channel)
:
    ris::Slave(),
    channel_(channel),
    bt_(bt)
{
}

sct::BaseTransmitterChannelPtr sct::BaseTransmitterChannel::create(sct::BaseTransmitterPtr bt, uint32_t channel)
{
    return std::make_shared<BaseTransmitterChannel>(bt,channel);
}

void sct::BaseTransmitterChannel::setup_python()
{
    bp::class_< sct::BaseTransmitterChannel,
                sct::BaseTransmitterChannelPtr,
                bp::bases<ris::Slave>,
                boost::noncopyable >
                ("BaseTransmitterChannel",bp::no_init);
    bp::implicitly_convertible<sct::BaseTransmitterChannelPtr, ris::SlavePtr>();
}

void sct::BaseTransmitterChannel::acceptFrame(ris::FramePtr frame)
{
    if ( channel_ == 0 )
        bt_->acceptDataFrame(frame);
    else if ( channel_ == 1 )
        bt_->acceptMetaFrame(frame);
}