text:
#ifndef __MODALITY_HPP__
#define __MODALITY_HPP__

#include <iostream>
#include <boost/version.hpp>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
//#include <mecab.h>
#ifdef USE_CABOCHA
#  include <cabocha.h>
#endif
#include "../tinyxml2/tinyxml2.h"

namespace linear {
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
#include "../liblinear-1.8/linear.h"
};

#include "sentence.hpp"
#include "cdbmap.hpp"
#include "../config.h"
#include "util.hpp"
#include "funcsem.hpp"

#ifndef PACKAGE_VERSION
#  define PACKAGE_VERSION "beta"
#endif
#define LABEL_NUM 6

#ifndef MODELDIR_IPA
#  define MODELDIR_IPA "model_ipa"
#endif
#ifndef MODELDIR_JUMAN
#  define MODELDIR_JUMAN "model_juman"
#endif

#ifndef DICDIR
#  define DICDIR "dic"
#endif

#define POSSET_IPA "動詞,*|形容詞,*|名詞,サ変接続|名詞,形容動詞語幹"
//#define POS_IPA "動詞,*|形容詞,*|名詞,サ変接続|名詞,形容動詞語幹|名詞,*:助動詞,*|名詞,*:助詞,*:助動詞,*"
#define POSSET_JUMAN "動詞,*|形容詞,*|名詞,サ変名詞"

//const boost::filesystem::path TMP_DIR("/tmp");

namespace modality {
	typedef boost::unordered_map< std::string, boost::unordered_map< std::string, double > > t_feat_cat;
	typedef boost::unordered_map< std::string, double > t_feat;

	enum {
		IN_RAW = 0,
		IN_DEP_CAB = 1,
		IN_DEP_KNP = 2,
		IN_PAS_SYN = 3,
		IN_PAS_KNP = 4,
		IN_XML_CAB = 5,
		IN_XML_KNP = 6
	};

	enum {
		POS_IPA = 0,
		POS_JUMAN = 1
	};

	enum {
		SOURCE = 0,  // 態度表明者
		TENSE = 1,  // 時制
		ASSUMPTIONAL = 2,  // 仮想
		TYPE = 3,  // 態度
		AUTHENTICITY = 4,  // 真偽判断
		SENTIMENT = 5,  // 評価極性
	};

	enum {
		DETECT_BY_POS = 0,
		DETECT_BY_PAS = 1,
		DETECT_BY_ML = 2,
		DETECT_BY_GOLD = 3,
	};

	typedef struct {
		int sp;
		int ep;
		std::string orthToken;
		std::string morphID;
		nlp::t_eme eme;
	} t_token;

	typedef struct {
		std::vector<int> tok_ids;
		std::string semrel;
	} t_match_func;

	class feature_generator2 {
		public:
			boost::unordered_map< std::string, std::vector<std::string> > keyterms;

			nlp::token *tok_core;
			nlp::chunk *chk_core;
			nlp::sentence *sent;
			t_feat_cat feat_cat;

			bool tagged_tense;
			bool tagged_fadic;
		public:
			feature_generator2() {
				tagged_tense = false;
				tagged_fadic = false;
			}
		public:
			bool compile_feat_str( const std::vector<std::string> &, std::string & );
			bool compile_feat( const std::vector<std::string> &, t_feat & );
			void gen_feature_function();
			void gen_feature_mod(const std::string &);
			void gen_feature_basic(const int);
			void gen_feature_dst_chunks();
			void gen_feature_ttj(cdbpp::cdbpp *);
			void gen_feature_fadic(cdbpp::cdbpp *);
			void gen_feature_neg();
			void gen_feature_fsem();
			/*
			void gen_feature_last_pred();
			void gen_feature_dst_chunks(const unsigned int);
			*/

		public:
			void set(nlp::sentence *_sent, nlp::chunk *chk, nlp::token *tok) {
				sent = _sent;
				tok_core = tok;
				chk_core = chk;
				feat_cat.clear();
				tagged_tense = false;
			}

		public:
			void load_keyterms(const boost::filesystem::path &kt_path) {
				keyterms.clear();

				std::ifstream ifs;
				ifs.open(kt_path.string().c_str());
				std::string line, key;
				while (ifs && getline(ifs, line)) {
					boost::algorithm::trim_right(line);
					if (line.compare(0, 1, "#") == 0 || line.size() == 0) {
						continue;
					}
					else if (line.compare(0, 1, ":") == 0) {
						line.replace(0,1,"");
						key = line;
					}
					else {
						keyterms[key].push_back(line);
					}
				}

				boost::unordered_map< std::string, std::vector<std::string> >::iterator it_kt;
				boost::unordered_map< std::string, std::vector<std::string> >::iterator ite_kt=keyterms.end();
				for (it_kt=keyterms.begin() ; it_kt!=ite_kt ; ++it_kt) {
					std::sort(it_kt->second.begin(), it_kt->second.end());
#ifdef _MODEBUG
					std::string buf = boost::algorithm::join(it_kt->second, ",");
					std::cerr << it_kt->first << ": " << it_kt->second.size() << " " << buf << std::endl;
#endif
				}
			}
	};

	class parser {
		public:
			boost::filesystem::path *model_path;
			boost::filesystem::path *feat_path;
			boost::filesystem::path model_dir_path;

			cdbpp::cdbpp dbr_ttj;
			cdbpp::cdbpp dbr_fadic;

//			MeCab::Tagger *mecab;
#ifdef USE_CABOCHA
			CaboCha::Parser *cabocha;
#endif

#if defined(USE_CRFSUITE) || defined(USE_CRFPP)
			funcsem::tagger *f_tagger;
#endif

			std::vector< nlp::sentence > learning_data;
			unsigned int target_detection;

			CdbMap<std::string, int> l2i;
			boost::filesystem::path l2i_path;
			boost::filesystem::path l2id_path;

			CdbMap<int, std::string> i2l;
			boost::filesystem::path i2l_path;
			boost::filesystem::path i2ld_path;

			CdbMap<std::string, int> f2i;
			boost::filesystem::path f2i_path;
			boost::filesystem::path f2id_path;

			linear::model *models[LABEL_NUM];
			bool model_loaded;
			std::vector<unsigned int> analyze_tags;

			std::string use_feats_str[LABEL_NUM];
			std::vector<std::string> use_feats[LABEL_NUM];

			int pos_tag;
			std::vector< std::vector< std::vector<std::string> > > target_pos;
			int max_num_tok_target;

			feature_generator2 fgen;

			parser(std::string model_dir = MODELDIR_IPA, std::string dic_dir = DICDIR) {
				analyze_tags.push_back(TENSE);
				analyze_tags.push_back(TYPE);
				analyze_tags.push_back(ASSUMPTIONAL);
				analyze_tags.push_back(AUTHENTICITY);
				analyze_tags.push_back(SENTIMENT);

				std::string use_feats_common_str = "func,tok,chunk,func_sem";
				use_feats_str[TENSE] = use_feats_common_str + ",mod_type";
				use_feats_str[TYPE] = use_feats_common_str + ",fadic_worth";
				use_feats_str[ASSUMPTIONAL] = use_feats_common_str + ",mod_type";
				use_feats_str[AUTHENTICITY] = use_feats_common_str + ",fadic_authenticity,mod_type,neg";
				use_feats_str[SENTIMENT] = use_feats_common_str + ",fadic_sentiment,mod_type";

				BOOST_FOREACH (unsigned int i, analyze_tags) {
					boost::algorithm::split(use_feats[i], use_feats_str[i], boost::algorithm::is_any_of(","));
				}

				model_path = new boost::filesystem::path[LABEL_NUM];
				feat_path = new boost::filesystem::path[LABEL_NUM];
				model_dir_path = model_dir;
				set_model_dir(model_dir_path);

				//				mecab = MeCab::createTagger("-p");
				//
				std::ifstream ifs_db;
				boost::filesystem::path dic_dir_path(dic_dir);
				boost::filesystem::path ttj_path("ttjcore2seq.cdb");
				ttj_path = dic_dir_path / ttj_path;
				ifs_db.open(ttj_path.string().c_str(), std::ios_base::binary);
				if (ifs_db.fail()) {
					std::cerr << "ERROR: Failed to open a database file \"" << ttj_path.string() << "\"" << std::endl;
					exit(-1);
				}
				dbr_ttj.open(ifs_db);
				ifs_db.close();

				boost::filesystem::path fadic_path("FAdic.cdb");
				fadic_path = dic_dir_path / fadic_path;
				ifs_db.open(fadic_path.string().c_str(), std::ios_base::binary);
				if (ifs_db.fail()) {
					std::cerr << "ERROR: Failed to open a database file \"" << fadic_path.string() << "\"" << std::endl;
					exit(-1);
				}
				dbr_fadic.open(ifs_db);
				ifs_db.close();

#ifdef USE_CABOCHA
				cabocha = CaboCha::createParser("-f1");
#endif

#if defined(USE_CRFSUITE) || defined(USE_CRFPP)
				f_tagger = new funcsem::tagger();
				f_tagger->set_model_dir(model_dir_path);
#endif

				target_detection = DETECT_BY_POS;
				pos_tag = POS_IPA;
				set_pos_tag(pos_tag, "");

				open_f2i_cdb();
				open_l2i_cdb();

				model_loaded = false;

				boost::filesystem::path kt_path("keyterms.txt");
				kt_path = dic_dir_path / kt_path;
				fgen.load_keyterms(kt_path);
			}

			~parser() {
#ifdef USE_CABOCHA
				delete cabocha;
#endif

#if defined(USE_CRFSUITE) || defined(USE_CRFPP)
				delete f_tagger;
#endif
				delete [] model_path;
				delete [] feat_path;
				if (model_loaded) {
					BOOST_FOREACH (unsigned int i, analyze_tags) {
						linear::free_and_destroy_model(&models[i]);
					}
				}
			}

		public:
			std::string id2tag(unsigned int);
			void set_model_dir(const std::string &);
			void set_model_dir(const boost::filesystem::path &);
			bool detect_target(nlp::token &, nlp::sentence &);

			bool parse_pos_str(const std::string &t_pos, std::vector< std::vector< std::vector<std::string> > > *t_pos_vec, int *_max_num_tok_target) {
				*_max_num_tok_target = 0;
				if (t_pos.empty())
					return false;
				t_pos_vec->clear();

				std::vector<std::string> psets;
				boost::algorithm::split(psets, t_pos, boost::algorithm::is_any_of("|"));
				BOOST_FOREACH (std::string pset, psets) {
					std::vector<std::string> _poss;
					std::vector< std::vector<std::string> > poss;
					boost::algorithm::split(_poss, pset, boost::algorithm::is_any_of(":"));
					BOOST_FOREACH (std::string pos, _poss) {
						std::vector<std::string> pp;
						boost::algorithm::split(pp, pos, boost::algorithm::is_any_of(","));
						poss.push_back(pp);
					}
					t_pos_vec->push_back(poss);
					if (*_max_num_tok_target < poss.size())
						*_max_num_tok_target = poss.size();
				}

				return true;
			}

			void set_pos_tag(int _pos_tag, const std::string &_pos_set) {
				pos_tag = _pos_tag;
				std::string t_pos;
				switch (pos_tag) {
					case POS_IPA:
						t_pos = POSSET_IPA;
						break;
					case POS_JUMAN:
						t_pos = POSSET_JUMAN;
						break;
					default:
						std::cerr << "ERROR: invalid pos tag" << std::endl;
						break;
				}
				if (!_pos_set.empty())
					t_pos = _pos_set;
				parse_pos_str(t_pos, &target_pos, &max_num_tok_target);
			}

			bool load_models(boost::filesystem::path *);
			bool load_models();
			bool analyze(const std::string &, const int, nlp::sentence &);
			bool analyze(nlp::sentence &);
			bool analyzeToString(nlp::sentence &, std::string &);
			bool analyzeToString(const std::string &, const int, std::string &);
			void pack_feat_linear(t_feat &, linear::feature_node *);
//			bool parse(std::string);
			void load_xmls(std::vector< std::string >, int);
			void load_deppasmods(std::vector< std::string >, int);
			void learn(boost::filesystem::path *, boost::filesystem::path *);
			void learn();

			nlp::sentence make_tagged_ipasents( std::vector< t_token >, int );
			bool make_tagged_ipasents( std::vector< t_token >, int, nlp::sentence & );

			std::vector< std::vector< t_token > > parse_OC(std::string);
			std::vector< std::vector< t_token > > parse_OW_PB_PN(std::string);
			std::vector< std::vector< t_token > > parse_OC_sents (tinyxml2::XMLElement *);
			std::vector<t_token> parse_bccwj_sent(tinyxml2::XMLElement *, int *);
			void parse_modtag_for_sent(tinyxml2::XMLElement *, std::vector< t_token > *);

			void open_f2i_cdb();
			void open_l2i_cdb();
			void open_i2l_cdb();
			void save_f2i();
			void save_l2i();
			void save_i2l();
	};

};

#endif

max_stars_repo_name: jmizuno/zunda

max_issues_repo_name: jmizuno/zunda

max_forks_repo_name: jmizuno/zunda


text:
  //==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2014 MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_SSE2_FAST_RSQRT_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_SSE_SSE2_FAST_RSQRT_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_SSE2_SUPPORT

#include <boost/simd/arithmetic/functions/fast_rsqrt.hpp>
#include <boost/simd/include/functions/simd/multiplies.hpp>
#include <boost/simd/include/functions/simd/minus.hpp>
#include <boost/simd/include/functions/simd/sqr.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_
                                    , boost::simd::tag::sse2_
                                    , (A0)
                                    , ((simd_ < single_<A0>
                                              , boost::simd::tag::sse_
                                              >
                                      ))
                                    )
  {
    typedef A0 result_type;

    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const
    {
      result_type nr  = _mm_rsqrt_ps( a0 );
                  nr *= 0.5f * (3.f - a0 * sqr(nr));

      return nr;
    }
  };
} } }

#endif

#endif

ext: hpp


text:
// Copyright (c) 2019-2020 The ION Core developers
// Copyright (c) 2021 The Bytz Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "tokens/tokendb.h"
#include "tokens/tokengroupmanager.h"
#include "ui_interface.h"
#include "validation.h"

#include <boost/thread.hpp>

CTokenDB::CTokenDB(size_t nCacheSize, bool fMemory, bool fWipe) : CDBWrapper(GetDataDir() / "tokens", nCacheSize, fMemory, fWipe) {}

bool CTokenDB::WriteTokenGroupsBatch(const std::vector<CTokenGroupCreation>& tokenGroups) {
    CDBBatch batch(*this);
    for (std::vector<CTokenGroupCreation>::const_iterator it = tokenGroups.begin(); it != tokenGroups.end(); it++){
        batch.Write(std::make_pair('c', it->tokenGroupInfo.associatedGroup), *it);
    }
    return WriteBatch(batch);
}

bool CTokenDB::WriteTokenGroup(const CTokenGroupID& tokenGroupID, const CTokenGroupCreation& tokenGroupCreation) {
    return Write(std::make_pair('c', tokenGroupID), tokenGroupCreation);
}

bool CTokenDB::ReadTokenGroup(const CTokenGroupID& tokenGroupID, CTokenGroupCreation& tokenGroupCreation) {
    return Read(std::make_pair('c', tokenGroupID), tokenGroupCreation);
}

bool CTokenDB::EraseTokenGroupBatch(const std::vector<CTokenGroupID>& newTokenGroupIDs) {
    CDBBatch batch(*this);
    for (std::vector<CTokenGroupID>::const_iterator it = newTokenGroupIDs.begin(); it != newTokenGroupIDs.end(); it++){
        batch.Erase(std::make_pair('c', *it));
    }
    return WriteBatch(batch);

}

bool CTokenDB::EraseTokenGroup(const CTokenGroupID& tokenGroupID) {
    return Erase(std::make_pair('c', tokenGroupID));
}

bool CTokenDB::DropTokenGroups(std::string& strError) {
    std::vector<CTokenGroupCreation> vTokenGroups;
    std::vector<CTokenGroupID> vTokenGroupIDs;
    FindTokenGroups(vTokenGroups, strError);

    for (auto tokenGroup : vTokenGroups) {
        vTokenGroupIDs.emplace_back(tokenGroup.tokenGroupInfo.associatedGroup);
        EraseTokenGroupBatch(vTokenGroupIDs);
    }

    return true;
}

bool CTokenDB::FindTokenGroups(std::vector<CTokenGroupCreation>& vTokenGroups, std::string& strError) {
    boost::scoped_ptr<CDBIterator> pcursor(NewIterator());
    pcursor->SeekToFirst();

    while (pcursor->Valid()) {
        boost::this_thread::interruption_point();
        std::pair<char, CTokenGroupID> key;
        if (pcursor->GetKey(key) && key.first == 'c') {
            CTokenGroupCreation tokenGroupCreation;
            if (pcursor->GetValue(tokenGroupCreation)) {
                vTokenGroups.push_back(tokenGroupCreation);
            } else {
                strError = "Failed to read token data from database";
                return error(strError.c_str());
            }
        }
        pcursor->Next();
    }
    return true;
}

bool CTokenDB::LoadTokensFromDB(std::string& strError) {
    tokenGroupManager.get()->ResetTokenGroups();

    std::vector<CTokenGroupCreation> vTokenGroups;
    FindTokenGroups(vTokenGroups, strError);

    tokenGroupManager.get()->AddTokenGroups(vTokenGroups);
    return true;
}

bool VerifyTokenDB(std::string &strError) {
    std::vector<CTokenGroupCreation> vTokenGroups;
    if (!pTokenDB->FindTokenGroups(vTokenGroups, strError)) {
        return error(strError.c_str());
    }
    if (fHavePruned) {
        LogPrintf("The block database has been pruned: lowering token database validation level\n");
    }
    for (auto tgCreation : vTokenGroups) {
        uint256 hash_block;
        CTransactionRef tx;
        uint256 txHash = tgCreation.creationTransaction->GetHash();

        LOCK(cs_main);
        auto pindex = mapBlockIndex.find(tgCreation.creationBlockHash);
        if (pindex == mapBlockIndex.end()) {
            strError = "Cannot find token creation transaction's block";
            return error(strError.c_str());
        }
        if (!chainActive.Contains(pindex->second)) {
            strError = "Token creation not found in the current chain";
            return error(strError.c_str());
        }
        if (fHavePruned && !(pindex->second->nStatus & BLOCK_HAVE_DATA) && pindex->second->nTx > 0) {
            // Block is in the index, but it's data has been pruned
            continue;
        }
        CBlock block;
        if (!ReadBlockFromDisk(block, pindex->second, Params().GetConsensus())) {
            strError = "Cannot locate token creation transaction's block";
            return error(strError.c_str());
        }
        for (auto& tx : block.vtx) {
            if (tx->GetHash() != txHash) {
                continue;
            }
            // Found creation transaction
            CTokenGroupCreation tgCreation2;
            if (!CreateTokenGroup(tx, block.GetHash(), tgCreation2)) {
                strError = "Cannot recreate token configuration transaction";
                return error(strError.c_str());
            }
            if (!(tgCreation == tgCreation2)) {
                strError = "Cannot verify token configuration transaction";
                return error(strError.c_str());
            }
        }
    }
    return true;
}

bool ReindexTokenDB(std::string &strError) {
    if (!pTokenDB->DropTokenGroups(strError)) {
        strError = "Failed to reset token database";
        return false;
    }
    tokenGroupManager.get()->ResetTokenGroups();

    uiInterface.ShowProgress(_("Reindexing token database..."), 0, false);

    CBlockIndex* pindex = chainActive[Params().GetConsensus().ATPStartHeight];
    std::vector<CTokenGroupCreation> vTokenGroups;
    while (pindex) {
        uiInterface.ShowProgress(_("Reindexing token database..."), std::max(1, std::min(99, (int)((double)(pindex->nHeight - Params().GetConsensus().ATPStartHeight) / (double)(chainActive.Height() - Params().GetConsensus().ATPStartHeight) * 100))), false);

        if (pindex->nHeight % 10000 == 0)
            LogPrintf("Reindexing token database: block %d...\n", pindex->nHeight);

        CBlock block;
        if (!ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
            strError = "Reindexing token database failed";
            return false;
        }

        for (const CTransactionRef& ptx : block.vtx) {
            if (!ptx->IsCoinBase() && !ptx->HasZerocoinSpendInputs() && IsAnyOutputGroupedCreation(*ptx)) {
                CTokenGroupCreation tokenGroupCreation;
                if (CreateTokenGroup(ptx, block.GetHash(), tokenGroupCreation)) {
                    vTokenGroups.push_back(tokenGroupCreation);
                }
            }
        }

        if (!vTokenGroups.empty() && !pTokenDB->WriteTokenGroupsBatch(vTokenGroups)) {
            strError = "Error writing token database to disk";
            return false;
        }
        tokenGroupManager.get()->AddTokenGroups(vTokenGroups);
        vTokenGroups.clear();

        pindex = chainActive.Next(pindex);
    }

    uiInterface.ShowProgress("", 100, false);

    return true;
}

ext: cpp

max_stars_repo_name: celbalrai/bytz

max_issues_repo_name: celbalrai/bytz

max_forks_repo_name: celbalrai/bytz


text: #include <boost/spirit/include/classic_assign_key_actor.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * for_each_pair.hpp
 *
 *  Created on: Aug 28, 2009
 *      Author: stewie
 */

#ifndef FOR_EACH_PAIR_HPP_
#define FOR_EACH_PAIR_HPP_

#include <boost/next_prior.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>

namespace bn {

namespace util {

/**
 * Applies binary function @a f on all the 2-combinations without
 * repetition of elements in the given ranges.
 *
 * This function calls @a f \f${n \choose 2} = \frac{n^2 - n}{2}\f$ times,
 * where @e n is the length of the range. The behaviour of this template
 * function is equivalent to:
 * @code
 * for (; first != last; ++first) {
 * 	ForwardIterator temp = first;
 * 	for (ForwardIterator it = ++temp; it != last; ++it)
 * 		f(*first, *it);
 * 	}
 * return f;
 * @endcode
 * @param first forward iterator to the initial position of the range
 * @param last forward iterator to the final position of the range
 * @param f binary function object to apply
 * @return the function object
 *
 * @see std::for_each() for a similar iteration algorithm.
 */
template<class ForwardIterator, class Function> Function for_each_pair(
		ForwardIterator first, ForwardIterator last, Function f) {
	for (; first != last; ++first)
		for (ForwardIterator it = boost::next(first); it != last; ++it)
			f(*first, *it);
	return f;
}

template<class ForwardRange, class Function> Function for_each_pair(
		ForwardRange& r, Function f) {
	return for_each_pair(boost::begin(r), boost::end(r), f);
}

template<class ForwardRange, class Function> Function for_each_pair(
		const ForwardRange& r, Function f) {
	return for_each_pair(boost::begin(r), boost::end(r), f);
}

}

}

#endif /* FOR_EACH_PAIR_HPP_ */

max_stars_repo_name: Markfrancisrogers/BooleanNetwork

max_issues_repo_name: Markfrancisrogers/BooleanNetwork

max_forks_repo_name: Markfrancisrogers/BooleanNetwork


text:
#include "graph.hpp"
#include <algorithm>
#include <boost/assert.hpp>

sssp::graph::graph() {}

size_t sssp::graph::add_node() {
    size_t index = m_nodes.size();
    m_nodes.emplace_back();
    return index;
}

void sssp::graph::add_edge(size_t source, size_t destination, double cost) {
    BOOST_ASSERT(
        std::find_if(m_nodes[source].outgoing.begin(), m_nodes[source].outgoing.end(), [&](const edge_info& e) {
            return e.destination == destination;
        }) == m_nodes[source].outgoing.end());
    BOOST_ASSERT(std::find_if(m_nodes[destination].incoming.begin(),
                              m_nodes[destination].incoming.end(),
                              [&](const edge_info& e) { return e.source == source; }) ==
                 m_nodes[destination].incoming.end());
    BOOST_ASSERT(source != destination);
    BOOST_ASSERT(cost >= 0.0);
    m_nodes[source].outgoing.push_back(edge_info(source, destination, cost));
    m_nodes[destination].incoming.push_back(edge_info(source, destination, cost));
    m_edge_count += 1;
}

size_t sssp::graph::node_count() const {
    return m_nodes.size();
}

const std::vector<sssp::edge_info>& sssp::graph::outgoing_edges(size_t source) const {
    return m_nodes[source].outgoing;
}

const std::vector<sssp::edge_info>& sssp::graph::incoming_edges(size_t destination) const {
    return m_nodes[destination].incoming;
}

max_stars_repo_name: kaini/sssp-simulation

max_issues_repo_name: kaini/sssp-simulation

max_forks_repo_name: kaini/sssp-simulation


text:
/**
 * Copyright (c) 2020 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <boost/algorithm/string.hpp>

#include "po-alias.hpp"

namespace ba = boost::algorithm;

namespace utility { namespace po {

namespace {

std::pair<std::string, std::string>
renameOptions(const std::string &token, const OptionAliases &aliases)
{
    auto rtoken(boost::make_iterator_range(token));

    // consume "--" prefix
    if (!ba::starts_with(rtoken, "--")) { return { "", "" }; }
    rtoken.advance_begin(2);

    // find equal sign (returns iterator range)
    const auto eq(ba::find_first(rtoken, "="));

    // extract option (between "--prefix" and "="/end() and map it to output
    const auto faliases(aliases.find(std::string(rtoken.begin(), eq.begin())));
    if (faliases == aliases.end()) { return { "", "" }; }

    // return remapped option and (optionally) value after "="
    return std::make_pair(faliases->second
                          , std::string(eq.end(), rtoken.end()));
}

} // namespace

boost::program_options::ext_parser optionAlias(OptionAliases &&aliases)
{
    return [aliases{std::move(aliases)}](const std::string &token)
    {
        return renameOptions(token, aliases);
    };
}

} } // namespace utility::po

max_stars_repo_name: ExploreWilder/libutility

max_issues_repo_name: ExploreWilder/libutility

max_forks_repo_name: ExploreWilder/libutility


text:
/*
	Copyright (C) 2003-2013 by David White <davewx7@gmail.com>

    This program 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 2 of the License, or
    (at your option) any later version.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/bind.hpp>

#include "checkbox.hpp"
#include "graphical_font_label.hpp"
#include "grid_widget.hpp"
#include "image_widget.hpp"
#include "raster.hpp"
#include "widget_factory.hpp"

namespace gui {
namespace {

widget_ptr create_checkbox_widget(widget_ptr label,
	bool checked,
	BUTTON_RESOLUTION resolution,
	int hpadding=12) {
	grid_ptr g(new grid(2));
	g->set_hpad(hpadding);
	g->add_col(widget_ptr(new gui_section_widget(checked ? "checkbox_ticked" : "checkbox_unticked", -1, -1, resolution == BUTTON_SIZE_NORMAL_RESOLUTION ? 1 : 2)));

	g->add_col(label);

	return g;
}

widget_ptr create_checkbox_widget(const std::string& text, bool checked, BUTTON_RESOLUTION resolution) {
	return create_checkbox_widget(widget_ptr(new graphical_font_label(text, "door_label", 2)), checked, resolution);
}
}

checkbox::checkbox(const std::string& label, bool checked, boost::function<void(bool)> onclick, BUTTON_RESOLUTION button_resolution)
  : button(create_checkbox_widget(label, checked, button_resolution), boost::bind(&checkbox::on_click, this), BUTTON_STYLE_NORMAL,button_resolution), label_(label), onclick_(onclick), checked_(checked), hpadding_(12)
{
	set_environment();
}

checkbox::checkbox(widget_ptr label, bool checked, boost::function<void(bool)> onclick, BUTTON_RESOLUTION button_resolution)
  : button(create_checkbox_widget(label, checked, button_resolution), boost::bind(&checkbox::on_click, this), BUTTON_STYLE_NORMAL,button_resolution), label_widget_(label), onclick_(onclick), checked_(checked), hpadding_(12)
{
	set_environment();
}

checkbox::checkbox(const variant& v, game_logic::formula_callable* e)
	: checked_(false), button(v,e)
{
	hpadding_ = v["hpad"].as_int(12);
	if(v.has_key("padding")) {
		ASSERT_LOG(v["padding"].num_elements() == 2, "Incorrect number of padding elements specifed." << v["padding"].num_elements());
		hpadding_ = v["padding"][0].as_int();
	}
	checked_ = v["checked"].as_bool(false);
	variant label_var = v["label"];
	label_ = (label_var.is_map() || label_var.is_callable()) ? "" : label_var.as_string_default("Checkbox");
	label_widget_ = (label_var.is_map() || label_var.is_callable())
		? widget_factory::create(label_var, e)
		: widget_ptr(new graphical_font_label(label_, "door_label", 2));
	ASSERT_LOG(get_environment() != 0, "You must specify a callable environment");
	click_handler_ = get_environment()->create_formula(v["on_click"]);
	onclick_ = boost::bind(&checkbox::click, this, _1);
	set_click_handler(boost::bind(&checkbox::on_click, this));

	set_label(create_checkbox_widget(label_widget_,
		checked_,
		button_resolution(),
		hpadding_));

	if(v.has_key("width") || v.has_key("height")) {
		set_dim(v["width"].as_int(width()), v["height"].as_int(height()));
	}
}

void checkbox::on_click()
{
	checked_ = !checked_;
	const int w = width();
	const int h = height();
	if(label_widget_) {
		set_label(create_checkbox_widget(label_widget_, checked_, button_resolution(), hpadding_));
	} else {
		set_label(create_checkbox_widget(label_, checked_, button_resolution()));
	}
	set_dim(w, h);
	onclick_(checked_);
}

void checkbox::click(bool checked)
{
	using namespace game_logic;
	if(get_environment()) {
		map_formula_callable_ptr callable = map_formula_callable_ptr(new map_formula_callable(get_environment()));
		callable->add("checked", variant::from_bool(checked));
		variant value = click_handler_->execute(*callable);
		get_environment()->execute_command(value);
	} else {
		std::cerr << "checkbox::click() called without environment!" << std::endl;
	}
}

variant checkbox::get_value(const std::string& key) const
{
	if(key == "checked") {
		return variant::from_bool(checked_);
	} else if(key == "label") {
		return variant(label_widget_.get());
	}
	return button::get_value(key);
}

}

max_stars_repo_name: sweetkristas/anura

max_issues_repo_name: sweetkristas/anura

max_forks_repo_name: sweetkristas/anura


text:
/*
 *  Software License Agreement (BSD License)
 *
 *  Robot Operating System code by the University of Osnabrück
 *  Copyright (c) 2015, University of Osnabrück
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   1. Redistributions of source code must retain the above
 *      copyright notice, this list of conditions and the following
 *      disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above
 *      copyright notice, this list of conditions and the following
 *      disclaimer in the documentation and/or other materials provided
 *      with the distribution.
 *
 *   3. Neither the name of the copyright holder nor the names of its
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 *  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 *  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 *  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 *
 *  ClusterLabelDisplay.hpp
 *
 *
 *  authors:
 *
 *    Kristin Schmidt <krschmidt@uni-osnabrueck.de>
 *    Jan Philipp Vogtherr <jvogtherr@uni-osnabrueck.de>
 */

#ifndef CLUSTER_LABEL_DISPLAY_HPP
#define CLUSTER_LABEL_DISPLAY_HPP

#include <Types.hpp>

#include <vector>
#include <map>
#include <memory>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>

#include <string>
#include <math.h>
#include <algorithm>

#include <QMessageBox>
#include <QApplication>
#include <QIcon>

#include <ros/ros.h>
#include <ros/console.h>
#include <rviz/viewport_mouse_event.h>
#include <rviz/visualization_manager.h>
#include <rviz/visualization_frame.h>
#include <rviz/geometry.h>

#include <rviz/display_context.h>
#include <rviz/frame_manager.h>
#include <rviz/display.h>

#include <rviz/tool.h>
#include <rviz/tool_manager.h>
#include <rviz/display_group.h>

#include <std_msgs/Int32.h>
#include <geometry_msgs/Point32.h>
#include <geometry_msgs/PoseStamped.h>
#include <mesh_msgs/TriangleMeshStamped.h>
#include <mesh_msgs/MeshGeometryStamped.h>
#include <mesh_msgs/MeshGeometry.h>
#include <mesh_msgs/GetGeometry.h>
#include <mesh_msgs/GetUUID.h>
#include <mesh_msgs/GetLabeledClusters.h>

#ifndef Q_MOC_RUN
#include <rviz/mesh_loader.h>

#include <OGRE/OgreManualObject.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include <OGRE/OgreEntity.h>
#include <OGRE/OgreStringConverter.h>
#include <OGRE/OgreMaterialManager.h>
#include <OGRE/OgreRay.h>
#include <OGRE/OgreSceneQuery.h>
#include <OGRE/OgreColourValue.h>

#endif

namespace rviz
{

// Forward declaration
class BoolProperty;
class ColorProperty;
class FloatProperty;
class IntProperty;
class EnumProperty;
class StringProperty;

} // End namespace rviz

namespace rviz_map_plugin
{

using std::shared_ptr;
using std::unique_ptr;
using std::string;
using std::vector;
using std::map;

// Forward declaration
class ClusterLabelVisual;
class ClusterLabelTool;

/**
 * @class ClusterLabelDisplay
 * @brief Display class for the map plugin
 */
class ClusterLabelDisplay: public rviz::Display
{

Q_OBJECT

public:

    /**
     * @brief Constructor
     */
    ClusterLabelDisplay();

    /**
     * @brief Destructor
     */
    ~ClusterLabelDisplay();

    /**
     * @brief The tool will call this function and emit the signal below to the master display to
     *        create the label
     * @param label The label name
     * @param faces The list of face IDs
     */
    void addLabel(string label, vector<uint32_t> faces);

    /**
     * @brief RViz callback on enable
     */
    void onEnable();

    /**
     * @brief RViz callback on disable
     */
    void onDisable();

Q_SIGNALS:

    /**
     * @brief This signal is used for delegating new label data to the master display.
     * @param cluster The cluster
     */
    void signalAddLabel(Cluster cluster);

public Q_SLOTS: // not sure wether any of those actually need to be q slots ...

    /**
     * @brief Refreshes the tool's current visual
     */
    void notifyLabelTool();

    /**
     * @brief Getter for the current geometry
     * @return The geometry
     */
    shared_ptr<Geometry> getGeometry();

    /**
     * @brief Setter for the geometry and cluster data
     * @param geometry The geometry
     * @param clusters The clusters
     */
    void setData(shared_ptr<Geometry> geometry, vector<Cluster> clusters);

private Q_SLOTS:

    /**
     * @brief Update the map, based on newly loaded data since the last update
     */
    void updateMap();

    /**
     * @brief Updates the colors, based on newly loaded data since the last update
     */
    void updateColors();

    /**
     * @brief Updates the sphere size for the brush tool
     */
    void updateSphereSize();

    /**
     * @brief Updates the phantom visual, based on newly loaded data since the last update
     */
    void updatePhantomVisual();

    /**
     * @brief Slot for changing the visual to the selected visual from the dropdown menu
     */
    void changeVisual();

private:

    /**
     * @brief RViz callback on initialize
     */
    void onInitialize();

    /**
     * @brief Programmatically create an instance of the label tool from this package
     */
    void initializeLabelTool();

    /**
     * @brief Create visuals for each cluster in the list
     */
    void createVisualsFromClusterList();

    /**
     * @brief Creates a phantom visual
     */
    void createPhantomVisual();

    /**
     * @brief Dynamically fills the dropdown menus of those properties
     */
    void fillPropertyOptions();

    /// Geometry
    shared_ptr<Geometry> m_geometry;

    /// Visuals
    vector<shared_ptr<ClusterLabelVisual>> m_visuals;

    /// ID of the current active visual
    uint32_t m_activeVisualId = 0;

    /// Additional visual to help with labeling without a TexturedMesh
    unique_ptr<ClusterLabelVisual> m_phantomVisual;

    /// Cluster data
    vector<Cluster> m_clusterList;

    /// Label tool
    ClusterLabelTool* m_tool;

    /// Property for the current active visual
    rviz::EnumProperty* m_activeVisualProperty;

    /// Property to set transparency
    rviz::FloatProperty* m_alphaProperty;

    /// Property for selecting colors (menu)
    rviz::Property* m_colorsProperty;

    /// Properties for selecting colors (menu-items)
    std::vector<rviz::ColorProperty*> m_colorProperties;

    /// Property to set the brushsize of the sphere brush of the label tool from this package
    rviz::FloatProperty* m_sphereSizeProperty;

    /// Property to hide or show a phantom visual
    rviz::BoolProperty* m_phantomVisualProperty;

    /// Index for the visuals
    int m_labelToolVisualIndex = 0;

    /// A variable that will be set to true, once the initial data has arrived
    bool has_data = false;

};

} // end namespace rviz_map_plugin

#endif


text:
/*
 * Copyright (C) 2008-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef LIBPORT_FWD_HH
# define LIBPORT_FWD_HH

#include <boost/version.hpp>

namespace libport
{
  // asio.hh;
  class ConcreteSocket;
  class Socket;

  // lockable.hh.
  class Lockable;

  // input-arguments.
  namespace opts
  {
    struct DataVisitor;
    struct Data;
    struct DataList;
  }

  // map.hh.
  template <class T, class N>
  class map;

  // package-info.hh.
  class PackageInfo;

  // path.hh.
  class path;

  // ref-pt.hh.
  template <class T> class RefPt;

  // select-const.hh.
  template <typename T> struct constify_traits;
  template <typename T> struct id_traits;

  // semaphore.hh.
  class Semaphore;

  // shared-ref.hh.
  template <typename T> class shared_ref;

  // symbol.hh.
  class Symbol;

  // xltdl.hh
  class xlt_advise;
  class xlt_handle;
}

namespace boost
{
  namespace asio
  {
#if BOOST_VERSION >= 106800
    class io_context;
    typedef io_context io_service;
#else
    class io_service;
#endif
  }
}

#endif // !LIBPORT_FWD_HH

ext: hh

max_stars_repo_name: jcbaillie/libport

max_issues_repo_name: jcbaillie/libport

max_forks_repo_name: jcbaillie/libport


text:
/**
 * This file is part of the boostcache package.
 *
 * (c) Azat Khuzhin <a3at.mail@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include "commands.h"
#include "util/compiler.h"
#include "util/version.h"

#include <boost/format.hpp>

namespace PlaceHolders = std::placeholders;

#define ADD_COMMAND(callback, objectPtr, argsNum) \
    CallbackInfo(std::bind(callback, objectPtr, PlaceHolders::_1), argsNum);

Commands::Callback Commands::find(const std::string &commandName,
                                  int numberOfArguments) const
{
    HashTable::const_iterator command = m_commands.find(commandName);

    if (command == m_commands.end()) {
        return std::bind(&Commands::notImplementedYetCallback,
                         PlaceHolders::_1);
    }

    const int expectedArguments = command->second.numberOfArguments;
    if ((expectedArguments >= 0) && (expectedArguments != numberOfArguments)) {
        return std::bind(malformedArgumentsCallback,
                         PlaceHolders::_1, numberOfArguments, expectedArguments);
    }

    return command->second.callback;
}

Commands::Commands()
{
    addGenericCommands();
    addDbCommands();
}

void Commands::addGenericCommands()
{
    m_commands["COMMANDS"] = ADD_COMMAND(&Commands::commandsList, this, 0);
    m_commands["PING"]     = ADD_COMMAND(&Commands::pingPong, this, 0);
    /**
     * -1 because this command has an optional argument
     * @TODO: handle optional arguments more pretty
     * @TODO: somehow told which optional arguments command have
     */
    m_commands["VERSION"]  = ADD_COMMAND(&Commands::version, this, -1);
}

void Commands::addDbCommands()
{
    /* hashtable */
    m_commands["HGET"] =   ADD_COMMAND(&Db::HashTable::get, &m_dbHashTable, 1);
    m_commands["HSET"] =   ADD_COMMAND(&Db::HashTable::set, &m_dbHashTable, 2);
    m_commands["HDEL"] =   ADD_COMMAND(&Db::HashTable::del, &m_dbHashTable, 1);
    m_commands["HFOR"] =   ADD_COMMAND(&Db::HashTable::foreach, &m_dbHashTable, 1);
    /* avltree */
    m_commands["ATGET"] =  ADD_COMMAND(&Db::AvlTree::get, &m_dbAvlTree, 1);
    m_commands["ATSET"] =  ADD_COMMAND(&Db::AvlTree::set, &m_dbAvlTree, 2);
    m_commands["ATDEL"] =  ADD_COMMAND(&Db::AvlTree::del, &m_dbAvlTree, 1);
    m_commands["ATFOR"] =  ADD_COMMAND(&Db::AvlTree::foreach, &m_dbAvlTree, 1);
}

std::string Commands::notImplementedYetCallback(const CommandHandler::Arguments &arguments)
{
    boost::format format = boost::format("%s is not implemented") % arguments[0];
    return CommandHandler::toErrorReplyString(boost::str(format));
}

std::string Commands::malformedArgumentsCallback(const CommandHandler::Arguments &arguments,
                                                 int inputArguments, int expectedArguments)
{
    boost::format format = boost::format("%s malformed number of arguments (%i vs %i)")
                                         % arguments[0]
                                         % inputArguments
                                         % expectedArguments;
    return CommandHandler::toErrorReplyString(boost::str(format));
}

std::string Commands::commandsList(const CommandHandler::Arguments &UNUSED(arguments))
{
    std::string asString;
    for (const HashTablePair &pair : m_commands) {
        asString += pair.first;
        asString += "\n";
    }
    return CommandHandler::toReplyString(asString);
}

std::string Commands::pingPong(const CommandHandler::Arguments &UNUSED(arguments))
{
    return CommandHandler::toInlineReplyString("PONG");
}

std::string Commands::version(const CommandHandler::Arguments &arguments)
{
    /**
     * TODO: add helper for checking arguments
     */
    bool verbose = (arguments.size() == 2 && arguments[1] == "VERBOSE");

    return CommandHandler::toInlineReplyString(Util::versionString(verbose));
}

max_stars_repo_name: azat/boostcache

max_issues_repo_name: boostcache/boostcache

max_forks_repo_name: boostcache/boostcache


text:
//=======================================================================
// Copyright (c)
//
// 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)
//=======================================================================
/**
 * @file linear_programming_long_test.cpp
 * @brief
 * @author Piotr Godlewski
 * @version 1.0
 * @date 2014-04-03
 */

#include "test_utils/logger.hpp"
#include "test_utils/read_lp.hpp"
#include "test_utils/get_test_dir.hpp"
#include "test_utils/system.hpp"

#include "paal/lp/glp.hpp"
#include "paal/utils/parse_file.hpp"

#include <boost/mpl/list.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/numeric.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>

#include <fstream>
#include <unordered_map>

using lp_types = boost::mpl::list<paal::lp::glp>;

template <typename LP, typename RowBounds, typename ColBounds,
          typename CostCoefs, typename Coefficients>
void run_test(RowBounds &row_bounds, ColBounds &col_bounds,
              CostCoefs &cost_coefs, Coefficients &coefs, double best_cost,
              int rows_num, int cols_num, int non_zeros,
              paal::lp::simplex_type type) {

    LP lp("LP long test", paal::lp::MINIMIZE);
    std::unordered_map<std::string, paal::lp::col_id> col_ids;

    std::string col_name;
    for (auto c : col_bounds) {
        col_name = c.first;
        col_ids[col_name] =
            lp.add_column(0., c.second.first, c.second.second, col_name);
    }

    int non_zero_cost_coefs = 0;
    for (auto c : cost_coefs) {
        lp.set_col_cost(col_ids[c.first], c.second);
        if (!paal::utils::compare<double>().e(c.second, 0.)) {
            ++non_zero_cost_coefs;
        }
    }

    std::string row_name;
    std::pair<double, double> row_bound;
    for (auto row : row_bounds) {
        std::tie(row_name, row_bound) = row;

        paal::lp::linear_expression expr;

        for (auto elem :
             boost::make_iterator_range(coefs.equal_range(row_name))) {
            expr += elem.second.second * col_ids[elem.second.first];
        }

        lp.add_row(row_bound.first <= std::move(expr) <= row_bound.second);
    }

    BOOST_CHECK_EQUAL(rows_num, lp.rows_number() + 1);
    BOOST_CHECK_EQUAL(cols_num, lp.columns_number());
    auto lp_non_zeros =
        boost::accumulate(lp.get_rows(), 0, [&](int sum, paal::lp::row_id row) {
        return sum + lp.get_row_degree(row);
    });
    BOOST_CHECK_EQUAL(non_zeros, lp_non_zeros + non_zero_cost_coefs);

    auto status = lp.solve_simplex(type);
    BOOST_CHECK_EQUAL(status, paal::lp::OPTIMAL);
    static const double EPSILON = 6e-5;
    BOOST_CHECK_CLOSE(best_cost, lp.get_obj_value(), EPSILON);
}

BOOST_AUTO_TEST_SUITE(linear_programming_long)

BOOST_AUTO_TEST_CASE_TEMPLATE(linear_programming_long, LP, lp_types) {
    std::string test_dir = paal::system::get_test_data_dir("LP");
    using paal::system::build_path;
    paal::parse(build_path(test_dir, "cases.txt"),
                [&](const std::string & fname, std::istream & is_test_cases) {
        double best_cost;
        int rows_num, cols_num, non_zeros;
        is_test_cases >> best_cost >> rows_num >> cols_num >> non_zeros;

        LOGLN(fname);
        std::ifstream ifs(build_path(test_dir, "/cases/" + fname + ".mps"));
        assert(ifs.good());

        std::unordered_map<std::string, std::pair<double, double>> row_bounds;
        std::unordered_map<std::string, std::pair<double, double>> col_bounds;
        std::unordered_map<std::string, double> cost_coefs;
        std::unordered_multimap<std::string, std::pair<std::string, double>>
            coefs;

        paal::read_lp(ifs, row_bounds, col_bounds, cost_coefs, coefs);
        LOGLN("primal");
        run_test<LP>(row_bounds, col_bounds, cost_coefs, coefs, best_cost,
                     rows_num, cols_num, non_zeros, paal::lp::PRIMAL);
        LOGLN("dual");
        run_test<LP>(row_bounds, col_bounds, cost_coefs, coefs, best_cost,
                     rows_num, cols_num, non_zeros, paal::lp::DUAL);
    });
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVROUND2EVEN_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_DIVROUND2EVEN_HPP_INCLUDED

#include <boost/simd/arithmetic/functions/divround2even.hpp>
#include <boost/simd/include/functions/scalar/round2even.hpp>
#include <boost/simd/include/functions/scalar/abs.hpp>
#include <boost/simd/include/functions/scalar/is_even.hpp>
#include <boost/simd/include/functions/scalar/is_odd.hpp>
#include <boost/simd/include/functions/scalar/copysign.hpp>
#include <boost/simd/include/functions/scalar/tofloat.hpp>
#include <boost/simd/include/constants/valmin.hpp>
#include <boost/simd/include/constants/valmax.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_
                                    , (A0)
                                    , (scalar_< int64_<A0> >)
                                      (scalar_< int64_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      typedef typename boost::dispatch::meta::as_integer<A0, unsigned>::type uitype;
      if (!a0) return  Zero<result_type>();
      if(a1)
      {
        uitype aa0 = abs(a0);
        uitype aa1 = abs(a1);
        uitype q = aa0/aa1;
        uitype rx2 = 2*(aa0-q*aa1);
        if (rx2 >= aa1)
        {
          if ((rx2 == aa1) && is_even(q)) --q;
          ++q;
        }
        return copysign(result_type(q), a0^a1);
      }
      else
        return ((a0>0) ? Valmax<result_type>() : Valmin<result_type>());
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_
                                    , (A0)
                                    , (scalar_< signed_<A0> >)
                                      (scalar_< signed_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      if(a1)
        return static_cast<result_type >(round2even(static_cast<double>(a0)/static_cast<double>(a1)));
      else
      {
        return (a0) ? ((a0>0) ? Valmax<result_type>() : Valmin<result_type>()) : Zero<result_type>();
      }
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_
                                    , (A0)
                                    , (scalar_< unsigned_<A0> >)
                                      (scalar_< unsigned_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      if(a1)
      {
        result_type q = a0/a1;
        result_type rx2 = 2*(a0-q*a1);
        if (rx2 >= a1)
        {
          if ((rx2 == a1) && is_even(q)) --q;
          ++q;
        }
        return q;
      }
      else
        return (a0) ? Valmax<result_type>() : Zero<result_type>();
    }
  };

#ifdef BOOST_MSVC
  #pragma warning(push)
  #pragma warning(disable: 4723) // potential divide by 0
#endif

  BOOST_DISPATCH_IMPLEMENT          ( divround2even_, tag::cpu_
                                    , (A0)
                                    , (scalar_< floating_<A0> > )
                                      (scalar_< floating_<A0> > )
                                    )
  {
    typedef A0 result_type;

    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return round2even(a0/a1);
    }
  };
} } }

#ifdef BOOST_MSVC
  #pragma warning(pop)
#endif

#endif


text:
#ifndef __LM_ENV_STEPWISE_H__
#define __LM_ENV_STEPWISE_H__

#include <string>
#include <vector>

#include <armadillo>

#include <glm/glm.hpp>
#include <besiq/method/env_method.hpp>
#include <besiq/stats/log_scale.hpp>

/**
 * This class is responsible for initializing and repeatedly
 * executing the lm regression on a single variant and an
 * environmental factor. The variant is treated as a factor
 * variable.
 */
class lm_env_stepwise
: public method_env_type
{
public:
    /**
     * Constructor.
     *
     * @param data Additional data required by all methods.
     * @param E Environment matrix that only contains the
     *          non-redundant levels, i.e. the intercept has
     *          been removed.
     */
    lm_env_stepwise(method_data_ptr data, const arma::mat &E);

    /**
     * @see method_env_type::init.
     */
    virtual void init(std::ostream &output);

    /**
     * @see method_env_type::run.
     */
    virtual void run(const snp_row &row, std::ostream &output);

private:
    /**
     * Design matrix corresponding to the 4 hypotheses.
     *
     * null: No snp or environment
     * snp: Only snp effect
     * env: Only env effect
     * add: Additive snp and env
     * alt: Full snp and env model
     */
    arma::mat m_null_matrix;
    arma::mat m_snp_matrix;
    arma::mat m_env_matrix;
    arma::mat m_add_matrix;
    arma::mat m_alt_matrix;

    /**
     * Contains all design matrices.
     */
    std::vector<arma::mat *> m_model;

    /**
     * Only contains non-redundant levels, i.e. the
     * "reference level" or "intercept" is removed
     *
     * Environment matrix, need to save this to compute
     * the variant interaction features.
     */
    arma::mat m_E;

    /**
     * Initializes all design matrices with the genotypes.
     *
     * @param row Variant.
     * @param missing The missing samples.
     * @param valid Determines whether there were enough samples in each cell.
     */
    void init_matrix_with_snp(const snp_row &row, arma::uvec &missing, bool *valid);
};

#endif /* End of __LM_ENV_STEPWISE_H__ */

max_stars_repo_name: hoehleatsu/besiq

max_issues_repo_name: hoehleatsu/besiq

max_forks_repo_name: hoehleatsu/besiq


text:
// Copyright Cromwell D. Enage 2019.
// 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)

#ifndef BOOST_PARAMETER_AUX_ALWAYS_TRUE_PREDICATE_HPP
#define BOOST_PARAMETER_AUX_ALWAYS_TRUE_PREDICATE_HPP

#include <boost/parameter/config.hpp>
#include <boost/mpl/bool.hpp>

#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mp11/integral.hpp>
#endif
#else
#include <boost/mpl/always.hpp>
#endif

namespace boost { namespace parameter { namespace aux {

#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
    struct always_true_predicate
    {
        template <typename ...>
        struct apply
        {
            typedef ::boost::mpl::true_ type;
        };

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        template <typename ...>
        using fn = ::boost::mp11::mp_true;
#endif
    };
#else
    typedef ::boost::mpl::always< ::boost::mpl::true_> always_true_predicate;
#endif  // BOOST_NO_CXX11_VARIADIC_TEMPLATES
}}} // namespace boost::parameter::aux

#endif  // include guard


text:
/***************************************************************************
   Copyright 2015 Ufora Inc.

   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.
****************************************************************************/
#include "RateLimitedChannelGroup.hpp"

#include <boost/python.hpp>
#include <boost/random.hpp>

#include "../native/Registrar.hpp"
#include "../core/PolymorphicSharedPtrFuncFromMemberFunc.hpp"

class RateLimitedStringChannelGroupWrapper :
		public native::module::Exporter<RateLimitedStringChannelGroupWrapper> {
public:
		std::string		getModuleName(void)
			{
			return "StringChannel";
			}

		static boost::python::object createRateLimitedStringChannelGroup(
						PolymorphicSharedPtr<CallbackScheduler> scheduler,
						double throughput
						)
			{
			return boost::python::object(
				PolymorphicSharedPtr<RateLimitedChannelGroup<std::string, std::string> >(
					new RateLimitedChannelGroup<std::string, std::string>(
						scheduler,
						boost::function1<double, std::string>([](std::string s) { return (double)s.size(); }),
						boost::function1<double, std::string>([](std::string s) { return (double)s.size(); }),
						throughput
						)
					)
				);
			}

		void exportPythonWrapper()
			{
			using namespace boost::python;

			typedef RateLimitedChannelGroup<std::string, std::string> group_type;

			typedef typename group_type::pointer_type ptr_type;

			class_<ptr_type>("RateLimitedStringChannelGroup", no_init)
				.macro_psp_py_def("wrap", group_type::wrap)
				;

			def("createRateLimitedStringChannelGroup", createRateLimitedStringChannelGroup);
			}
};

//explicitly instantiating the registration element causes the linker to need
//this file
template<>
char native::module::Exporter<RateLimitedStringChannelGroupWrapper>::mEnforceRegistration =
		native::module::ExportRegistrar<
			RateLimitedStringChannelGroupWrapper>::registerWrapper();

max_stars_repo_name: ufora/ufora


text:
#include <boost/asio/signal_set.hpp>
#include <boost/asio/io_service.hpp>
#include "utils/idle_service.h"
#include "utils/log.h"
#include "utils/util.h"
#include "client/transcode_service.h"
#include "client/record_service.h"

int main(int argc, char **argv) {
    const std::string url = "your Rtsp stream URL Here";
    Log *log = Log::getInstance();
    TranscodeService *transcodeService = new TranscodeService();
    RecordService *recordService = new RecordService();
    IdleService *idleService = new IdleService();
    std::shared_ptr<StreamQueue> streamQueue = std::make_shared<StreamQueue>();
    boost::asio::io_service io_service;
    boost::asio::signal_set signals(io_service, SIGINT, SIGALRM);

    Util::enable_core_dump();

    log->init();

    transcodeService->setStreamQueue(streamQueue);
    transcodeService->init(url);
    auto param = transcodeService->getCodecParameter();

    recordService->setStreamQueue(streamQueue);
    recordService->init(param);

    idleService->init();

    log->info("start nap");
    signals.async_wait(
        [&io_service](const boost::system::error_code& /*error*/, int signal_number){
            switch (signal_number) {
                case SIGINT: {
                    io_service.stop();
                    break;
                };

                case SIGALRM: {
                    io_service.stop();
                    break;
                };

                default: {
                    break;
                }
            }
        });

    log->info("nap alarm setup done");
    io_service.run();
    log->info("io_service done");
    idleService->destroy();
    log->info("nap done");

    recordService->destory();
    delete(recordService);

    transcodeService->destory();
    delete(transcodeService);

    log->destroy();

    return 0;
}

max_stars_repo_name: TomerJLevy/RTSPServer

max_issues_repo_name: codacy-badger/RTSPServer

max_forks_repo_name: codacy-badger/RTSPServer


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// 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)
//
// Official repository: https://github.com/boostorg/json
//

#ifndef BOOST_JSON_VISIT_HPP
#define BOOST_JSON_VISIT_HPP

#include <boost/json/detail/config.hpp>
#include <boost/json/value.hpp>
#include <type_traits>
#include <utility>

BOOST_JSON_NS_BEGIN

/** Invoke a function object with the contents of a @ref value

    @return The value returned by Visitor.

    @param v The visitation function to invoke

    @param jv The value to visit.
*/
/** @{ */
template<class Visitor>
auto
visit(
    Visitor&& v,
    value& jv) -> decltype(
        std::declval<Visitor>()(nullptr));

template<class Visitor>
auto
visit(
    Visitor &&v,
    value const &jv) -> decltype(
        std::declval<Visitor>()(nullptr));
/** @} */

BOOST_JSON_NS_END

#include <boost/json/impl/visit.hpp>

#endif


text:
#include "i_ui.h"
#include <boost/algorithm/string.hpp>
#include <string.h>

Widget::WidgetIterator& Widget::WidgetIterator::operator++()
{
    // go to the bottom of the hierarchy
    if( mThis->mFirstChild )
    {
        mThis = mThis->mFirstChild;
        ++mLevel;
    }
    // visit the bottom-most level
    else if( mThis->mNext )
    {
        mThis = mThis->mNext;
    }
    // go up
    else
    {
        Widget const* Next = mThis;
        // find the first parent with siblings
        while( Next && !Next->mNext && mLevel )
        {
            Next = Next->mParent;
            --mLevel;
        }
        // if found, visit siblings
        mThis = NULL == Next ? NULL : Next->mNext;
    }
    return *this;
}

void Widget::AddChild( Widget* Child )
{
    assert( !Child->mPrev && !Child->mParent && !Child->mNext );

    Widget* WhatWillBeNext = mFirstChild;
    while( WhatWillBeNext && WhatWillBeNext->mZOrder < Child->mZOrder )
    {
        WhatWillBeNext = WhatWillBeNext->mNext;
    }

    if( WhatWillBeNext )
    {
        Child->mPrev = WhatWillBeNext->mPrev;
        if( WhatWillBeNext->mPrev )
        {
            WhatWillBeNext->mPrev->mNext = Child;
        }
        Child->mNext = WhatWillBeNext;
        WhatWillBeNext->mPrev = Child;
        if( WhatWillBeNext == mFirstChild )
        {
            mFirstChild = Child;
        }
    }
    else
    {
        if( !mFirstChild )
        {
            mFirstChild = Child;
        }
        mLastChild = Child;
    }
    Child->mParent = this;
    Child->UpdateDimensions();
    Child->UpdateChildrenDimensions();
}

Widget::Widget( int32_t Id )
    : mZOrder( 0 )
    , mParent( NULL )
    , mNext( NULL )
    , mPrev( NULL )
    , mFirstChild( NULL )
    , mLastChild( NULL )
    , mRelativeDimensions( 0, 0, 1, 1 )
    , mTypeId( Id )
    , mDimSet( false )
    , mProperties( this )
{
    operator()( PT_Highlight ) = 0;
}

Widget const* Widget::Parent() const
{
    return mParent;
}

Widget::~Widget()
{
    Widget* What = mFirstChild;
    while( What )
    {
        Widget* Next = What->mNext;
        delete What;
        What = Next;
    }
    if( mNext )
    {
        mNext->mPrev = mPrev;
    }
    if( mPrev )
    {
        mPrev->mNext = mNext;
    }
    if( mParent )
    {
        if( mParent->mFirstChild == this )
        {
            mParent->mFirstChild = mNext;
        }
        if( mParent->mLastChild == this )
        {
            mParent->mLastChild = mPrev;
        }
    }
}

glm::vec4 const& Widget::GetDimensions() const
{
    return mDimensions;
}

Widget::const_iterator Widget::begin() const
{
    return WidgetIterator( this );
}

Widget::const_iterator Widget::end() const
{
    return WidgetIterator();
}

void Widget::UpdateDimensions()
{
    UpdateSelfDimensions();
    UpdateChildrenDimensions();
}

void Widget::UpdateSelfDimensions()
{
    if( !mParent || !mParent->mDimSet )
    {
        return;
    }
    mDimSet = true;
    glm::vec4 const& ParentDim = mParent->GetDimensions();
    double const X = ParentDim.x;
    double const Y = ParentDim.y;
    double const Width = ParentDim.z;
    double const Height = ParentDim.w;
    mDimensions = glm::vec4(  X + mRelativeDimensions.x * Width,
                              Y + mRelativeDimensions.y * Height,
                              mRelativeDimensions.z * Width,
                              mRelativeDimensions.w * Height );
}

void Widget::UpdateChildrenDimensions()
{
    if( !mParent || !mParent->mDimSet )
    {
        return;
    }
    for( Widget* i = mFirstChild; i; i = i->mNext )
    {
        i->UpdateDimensions();
    }
}

Widget* Widget::GetHit( const glm::vec2& Pos )
{
    if( !IsInside( Pos ) || mProperties( PT_SubtreeHidden ).Value.ToInt != 0 )
    {
        return NULL;
    }
    for( Widget* i = mLastChild; i; i = i->mPrev )
    {
        Widget* Wdg = i->GetHit( Pos );
        if( Wdg )
        {
            return Wdg;
        }
    }
    return mProperties( PT_Enabled ).operator int32_t() ? this : NULL;
}

bool Widget::IsInside( const glm::vec2& Pos ) const
{
    return mDimSet &&
           Pos.x >= mDimensions.x &&
           Pos.x <= mDimensions.x + mDimensions.z &&
           Pos.y >= mDimensions.y &&
           Pos.y <= mDimensions.y + mDimensions.w;
}

void Widget::SetRelativeDimensions( glm::vec4 const& Dim )
{
    mRelativeDimensions = Dim;
    UpdateDimensions();
}

bool Widget::AreDimensionsSet() const
{
    return mDimSet;
}

Widget* Widget::GetNext() const
{
    return mNext;
}

Widget::Prop const& Widget::operator()( PropertyType Property ) const
{
    return mProperties( Property );
}

Widget::Prop& Widget::operator()( PropertyType Property )
{
    return mProperties.Mutable( Property );
}

void Widget::ParseColor( PropertyType Property, Json::Value& Color, int32_t Default )
{
    int32_t i;
    if ( Color.isNull() )
    {
        operator()( Property ) = Default;
    }
    else if( Json::GetColor( Color, i ) )
    {
        operator()( Property ) = i;
    }
    else
    {
        ParseIntProp( Property, Color, Default);
    }
}

void Widget::Init( Json::Value& Descriptor )
{
    double d;
    mRelativeDimensions.x = Json::GetDouble( Descriptor["x"], d ) ? d : 0;
    mRelativeDimensions.y = Json::GetDouble( Descriptor["y"], d ) ? d : 0;
    mRelativeDimensions.z = Json::GetDouble( Descriptor["w"], d ) ? d : 0;
    mRelativeDimensions.w = Json::GetDouble( Descriptor["h"], d ) ? d : 0;
    static const int32_t DefaultColor = 0x00000077;
    ParseColor( PT_Color, Descriptor["color"], DefaultColor );
    ParseColor( PT_HighlightColor, Descriptor["highlight_color"], DefaultColor );
    ParseIntProp( PT_Enabled, Descriptor["enabled"], 0 );
    ParseIntProp( PT_Visible, Descriptor["visible"], 0 );
    Json::Value& Children = Descriptor["children"];
    if( !Children.isArray() || !Children.size() )
    {
        return;
    }
    WidgetFactory& Fact( WidgetFactory::Get() );
    for( Json::Value::iterator i = Children.begin(), e = Children.end(); i != e; ++i )
    {
        std::string Str;
        if( !Json::GetStr( ( *i )["type"], Str ) )
        {
            continue;
        }
        std::auto_ptr<Widget> wdg = Fact( Str, *i );
        AddChild( wdg.release() );
    }
}

int32_t Widget::GetId() const
{
    return mTypeId;
}

void Widget::ParseIntProp( PropertyType Pt, Json::Value& Val, int32_t Default )
{
    ParseIntProp( operator()( Pt ), Val, Default );
}

void Widget::ParseIntProp( Prop& Pt, Json::Value& Val, int32_t Default )
{
    if( Val.isString() )
    {
        Pt = Val.asString();
        assert( Pt.IsResolvable() );
    }
    else
    {
        int32_t i;
        Pt = Json::GetInt( Val, i ) ? i : Default;
    }
}

void Widget::ParseDoubleProp( PropertyType Pt, Json::Value& Val, double Default )
{
    ParseDoubleProp( operator()( Pt ), Val, Default );
}

void Widget::ParseDoubleProp( Prop& Pt, Json::Value& Val, double Default )
{
    if( Val.isString() )
    {
        Pt = Val.asString();
        assert( Pt.IsResolvable() );
    }
    else
    {
        double d;
        Pt = Json::GetDouble( Val, d ) ? d : Default;
    }
}

void Widget::ParseStrProp( PropertyType Pt, Json::Value& Val, std::string const& Default )
{
    ParseStrProp( operator()( Pt ), Val, Default );
}

void Widget::ParseStrProp( Prop& Pt, Json::Value& Val, std::string const& Default )
{
    Pt = Val.isString() ? Val.asString() : Default;
}

Widget::Prop::Prop( Widget* owner )
    : Type( T_Null )
    , mOwner( owner )
{
    Value.ToInt = 0;
}

Widget* Widget::Prop::GetOwner() const
{
    return mOwner;
}

Widget::Prop::Prop( Prop const& Other )
    : Value( Other.Value )
    , Type( Other.Type )
    , mOwner( Other.mOwner )
{
    if( Type == T_Str )
    {
        Init( std::string( Other.Value.ToStr ) );
    }
}

Widget::Prop::~Prop()
{
    Cleanup();
}

Widget::Prop::operator int32_t() const
{
    if( IsResolvable() )
    {
        if( IsAutoId() )
        {
            return ( int32_t )AutoId( Value.ToStr + 2 );
        }
        if( IsVectorModelValue() )
        {
            std::vector<int32_t> const& v = ResolveModel().operator std::vector<int32_t>();
            int32_t idx = ResolveIndex();
            return v.size() > idx ? v.at( idx ) : 0;
        }
        if( IsModelIndex() )
        {
            return ResolveIndex();
        }
        return( int32_t )ResolveModel();
    }
    assert( Type == T_Int || Type == T_Double );
    return ( Type == T_Int ) ? Value.ToInt : ( Type == T_Double ? int32_t( Value.ToDouble ) : 0 );
}

Widget::Prop::operator double() const
{
    if( IsResolvable() )
    {
        return( double )ResolveModel();
    }
    assert( Type == T_Int || Type == T_Double );
    return ( Type == T_Double ) ? Value.ToDouble : ( Type == T_Int ? double( Value.ToInt ) : 0.0 );
}

Widget::Prop& Widget::Prop::operator=( std::string const& Str )
{
    Cleanup();
    Type = T_Str;
    Init( Str );
    return *this;
}

Widget::Prop& Widget::Prop::operator=( char const* Str )
{
    Cleanup();
    Type = T_Str;
    Init( std::string( Str ) );
    return *this;
}

Widget::Prop& Widget::Prop::operator=( int32_t I )
{
    Cleanup();
    Type = T_Int;
    Value.ToInt = I;
    return *this;
}

Widget::Prop& Widget::Prop::operator=( double D )
{
    Cleanup();
    Type = T_Double;
    Value.ToDouble = D;
    return *this;
}

void Widget::Prop::Init( std::string const& StrVal )
{
    Type = T_Str;
    const size_t Size = StrVal.size();
    char* Buf = new char[Size + 1];
    memset( Buf, 0, Size + 1 );
    memcpy( Buf, StrVal.c_str(), Size );
    Value.ToStr = Buf;
}

void Widget::Prop::Cleanup()
{
    if( Type == T_Str )
    {
        delete[] Value.ToStr;
    }
    Type = T_Null;
}

Widget::Prop::operator std::string() const
{
    if( IsResolvable() )
    {
        if( IsVectorModelValue() )
        {
            std::vector<std::string> const& v = ResolveModel().operator std::vector<std::string>();
            int32_t idx = ResolveIndex();
            return v.size() > idx ? v.at( idx ) : std::string();
        }
        return( std::string )ResolveModel();
    }
    assert( Type == T_Str );
    return ( Type == T_Str ) ? Value.ToStr : NULL;
}

bool Widget::Prop::IsResolvable() const
{
    return Type == T_Str && Value.ToStr && ( *Value.ToStr == '%' || *Value.ToStr == '#' );
}

bool Widget::Prop::IsAutoId() const
{
    return IsResolvable() && Value.ToStr[1] == '%';
}

bool Widget::Prop::IsModelValue() const
{
    return Type == T_Str && Value.ToStr && ( ( *Value.ToStr == '%' && Value.ToStr[1] != '%' ) || *Value.ToStr == '#' );
}

bool Widget::Prop::IsModelIndex() const
{
    return Type == T_Str && Value.ToStr && *Value.ToStr == '#';
}

bool Widget::Prop::IsVectorModelValue() const
{
    return IsModelValue() && strrchr( Value.ToStr + 1, '#' ) != NULL ;
}

ModelValue const& Widget::Prop::ResolveModel() const
{
    assert( IsResolvable() );
    std::string name = std::string( ( *Value.ToStr == '#' ) ?  "ui." : "" ) + std::string( Value.ToStr + 1 );
    typedef std::vector<std::string> Fields_t;
    Fields_t fields;
    boost::split( fields, name, boost::is_any_of( "#%" ) );
    return RootModel::Get()[ fields[0] ];
}

int32_t Widget::Prop::ResolveIndex() const
{
    assert( IsVectorModelValue() || IsModelIndex() );
    typedef std::vector<std::string> Fields_t;
    Fields_t fields;
    boost::split( fields, Value.ToStr, boost::is_any_of( "#" ) );
    std::string last = fields.back();
    int32_t startindex = RootModel::Get()[ "ui." + last ].operator int32_t();
    for( Widget const* w = mOwner; NULL != w; w = w->Parent() )
    {
        Prop const& p = w->operator()( PT_StartId );
        if( p.GetType() != T_Str )
        {
            continue;
        }
        if( p.Value.ToStr + 1 !=  last )
        {
            continue;
        }
        // found a widget with the same startid
        // check for index prop
        Prop const& p2 = w->operator()( PT_Index );
        if( p2.GetType() != T_Int )
        {
            continue;
        }
        return startindex + p2.operator int32_t();
    }
    return startindex;
}

Widget::PropertyRepo_t::PropertyRepo_t( Widget* owner )
    : mOwner( owner )
    , mDefaultProperty( owner )
    , RepoBase( mDefaultProperty )
{
}

Widget::Prop& Widget::PropertyRepo_t::Mutable( PropertyType Property )
{
    int32_t Id( Property );
    ElementMap_t::iterator i = mElements.find( Id );
    if( mElements.end() == i )
    {
        Prop* p = new Prop( mOwner );
        mElements.insert( Id, p );
        return *p;
    }
    return *i->second;
}


text:
/* (c) Copyright 2012 Felipe Magno de Almeida
 *
 * 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 <morbid/giop/common_terminals.hpp>
#include <morbid/giop/compile.hpp>

#include <boost/proto/core.hpp>

#include "test_compile.hpp"

struct float_terminal {};
struct double_terminal {};
struct long_double_terminal {};

namespace test_compile {

template <typename Modifiers, typename Enable>
struct make_primitive<boost::spirit::tag::float_, Modifiers, Enable>
{
  typedef ::float_terminal result_type;

  template <typename T_>
  result_type operator()(T_& val, boost::spirit::unused_type) const;
};

template <typename Modifiers, typename Enable>
struct make_primitive<boost::spirit::tag::double_, Modifiers, Enable>
{
  typedef ::double_terminal result_type;

  template <typename T_>
  result_type operator()(T_& val, boost::spirit::unused_type) const;
};

template <typename Modifiers, typename Enable>
struct make_primitive<morbid::giop::tag::long_double, Modifiers, Enable>
{
  typedef ::long_double_terminal result_type;

  template <typename T_>
  result_type operator()(T_& val, boost::spirit::unused_type) const;
};

}

template <typename Elements>
void test( test_compile::sequence<Elements> const& s)
{
  BOOST_MPL_ASSERT_RELATION(boost::mpl::size<Elements>::value, ==, 3);
  BOOST_MPL_ASSERT((boost::is_same<typename boost::mpl::at_c<Elements, 0>::type, float_terminal>));
  BOOST_MPL_ASSERT((boost::is_same<typename boost::mpl::at_c<Elements, 1>::type, double_terminal>));
  BOOST_MPL_ASSERT((boost::is_same<typename boost::mpl::at_c<Elements, 2>::type, long_double_terminal>));
}

template <typename Expr>
void compile(Expr const& expr)
{
  typedef typename morbid::giop::result_of::compile< test_compile::domain, Expr>::type result_type;
  result_type r = morbid::giop::compile< test_compile::domain>(expr);
  test(r);
}

int main()
{
  namespace giop = morbid::giop;
  compile(giop::float_ & giop::double_ & giop::long_double);
}

max_stars_repo_name: felipealmeida/mORBid

max_issues_repo_name: felipealmeida/mORBid

max_forks_repo_name: felipealmeida/mORBid


text:
#include <iostream>
#include <functional>
#include <cmath>
#include <boost/mpi.hpp>

namespace mpi = boost::mpi;

int main (int argc, char* argv[])
{
    mpi::environment env(argc, argv);
    mpi::communicator world;
    int myrank= world.rank();

    float vec[2];
    vec[0]= 2*myrank; vec[1]= vec[0]+1;

    // Local accumulation
    float local= std::abs(vec[0]) + std::abs(vec[1]);

    // Global accumulation
    float global= mpi::all_reduce(world, local, std::plus<float>());
    std::cout << "Hello, I am process " << world.rank() << " and I know too that |v|_1 is " << global << ".\n";

    return 0 ;
}

max_stars_repo_name: tzaffi/cpp

max_issues_repo_name: tzaffi/cpp

max_forks_repo_name: tzaffi/cpp