text:
///////////////////////////////////////////////////////////////////////////////
// alternate_matcher.hpp
//
//  Copyright 2004 Eric Niebler. 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_XPRESSIVE_DETAIL_CORE_MATCHER_ALTERNATE_MATCHER_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_CORE_MATCHER_ALTERNATE_MATCHER_HPP_EAN_10_04_2005

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <vector>

#include <boost/version.hpp>
#if BOOST_VERSION <= 103200
// WORKAROUND for Fusion bug in Boost 1.32
namespace boost { namespace fusion
{
    namespace detail { struct iterator_root; }
    using detail::iterator_root;
}}
#endif

#include <boost/shared_ptr.hpp>
#include <boost/spirit/fusion/sequence/range.hpp>
#include <boost/spirit/fusion/algorithm/for_each.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/core/quant_style.hpp>
#include <boost/xpressive/detail/core/state.hpp>
#include <boost/xpressive/detail/static/width_of.hpp>
#include <boost/xpressive/detail/static/is_pure.hpp>
#include <boost/xpressive/detail/dynamic/matchable.hpp>
#include <boost/xpressive/detail/utility/hash_peek_bitset.hpp>
#include <boost/xpressive/detail/utility/algorithm.hpp>
#include <boost/xpressive/detail/utility/any.hpp>

namespace boost { namespace xpressive { namespace detail
{

    ///////////////////////////////////////////////////////////////////////////////
    // alt_match_pred
    //
    template<typename BidiIter, typename Next>
    struct alt_match_pred
    {
        state_type<BidiIter> &state_;

        alt_match_pred(state_type<BidiIter> &state)
          : state_(state)
        {
        }

        template<typename Xpr>
        bool operator ()(Xpr const &xpr) const
        {
            return get_pointer(xpr)->BOOST_NESTED_TEMPLATE push_match<Next>(this->state_);
        }

    private:
        alt_match_pred &operator =(alt_match_pred const &);
    };

    ///////////////////////////////////////////////////////////////////////////////
    // alt_match
    //
    template<typename BidiIter>
    inline bool alt_match
    (
        std::vector<shared_ptr<matchable<BidiIter> const> > const &alternates
      , state_type<BidiIter> &state
      , matchable<BidiIter> const &
    )
    {
        typedef alt_match_pred<BidiIter, matchable<BidiIter> > alt_match_pred;
        return detail::any(alternates.begin(), alternates.end(), alt_match_pred(state));
    }

    template<typename BidiIter, typename Next, typename Alternates>
    inline bool alt_match
    (
        fusion::sequence_base<Alternates> const &alternates
      , state_type<BidiIter> &state
      , Next const &
    )
    {
        typedef alt_match_pred<BidiIter, Next> alt_match_pred;
        return fusion::any(alternates.cast(), alt_match_pred(state));
    }

    ///////////////////////////////////////////////////////////////////////////////
    // make_range
    template<typename Begin, typename End>
    inline fusion::range<Begin, End> make_range(Begin const &begin, End const &end)
    {
        return fusion::range<Begin, End>(begin, end);
    }

    ///////////////////////////////////////////////////////////////////////////////
    // alt_get_width_pred
    //
    template<typename BidiIter>
    struct alt_get_width_pred
    {
        state_type<BidiIter> *state_;
        std::size_t *width_;

        alt_get_width_pred(state_type<BidiIter> *state, std::size_t *width)
          : state_(state)
          , width_(width)
        {
        }

        template<typename Xpr>
        void operator ()(Xpr const &xpr) const
        {
            if(*this->width_ != unknown_width())
            {
                std::size_t that_width = get_pointer(xpr)->get_width(this->state_);
                if(*this->width_ != that_width)
                {
                    *this->width_ = unknown_width();
                }
            }
        }
    };

    ///////////////////////////////////////////////////////////////////////////////
    // alt_get_width
    //
    template<typename BidiIter>
    inline std::size_t alt_get_width
    (
        std::vector<shared_ptr<matchable<BidiIter> const> > const &alternates
      , state_type<BidiIter> *state
    )
    {
        typedef alt_get_width_pred<BidiIter> alt_get_width_pred;
        std::size_t width = alternates.front()->get_width(state);
        std::for_each(alternates.begin() + 1, alternates.end(), alt_get_width_pred(state, &width));
        return width;
    }

    template<typename BidiIter, typename Alternates>
    inline std::size_t alt_get_width
    (
        fusion::sequence_base<Alternates> const &alternates
      , state_type<BidiIter> *state
    )
    {
        typedef alt_get_width_pred<BidiIter> alt_get_width_pred;
        std::size_t width = (*fusion::begin(alternates.cast())).get_width(state);
        fusion::for_each
        (
            make_range(fusion::next(fusion::begin(alternates.cast())), fusion::end(alternates.cast()))
          , alt_get_width_pred(state, &width)
        );
        return width;
    }

    ///////////////////////////////////////////////////////////////////////////////
    // alternate_matcher
    //
    template<typename Alternates, typename Traits>
    struct alternate_matcher
      : quant_style_auto<width_of<Alternates>, is_pure<Alternates> >
    {
        typedef Alternates alternates_type;
        typedef typename Traits::char_type char_type;

        Alternates alternates_;
        mutable hash_peek_bitset<char_type> bset_;

        explicit alternate_matcher(Alternates const &alternates = Alternates())
          : alternates_(alternates)
          , bset_()
        {
        }

        template<typename BidiIter, typename Next>
        bool match(state_type<BidiIter> &state, Next const &next) const
        {
            if(!state.eos() && !this->can_match_(*state.cur_, traits_cast<Traits>(state)))
            {
                return false;
            }

            return detail::alt_match(this->alternates_, state, next);
        }

        template<typename BidiIter>
        std::size_t get_width(state_type<BidiIter> *state) const
        {
            return detail::alt_get_width(this->alternates_, state);
        }

    private:
        alternate_matcher &operator =(alternate_matcher const &);

        bool can_match_(char_type ch, Traits const &traits) const
        {
            return this->bset_.test(ch, traits);
        }
    };

}}}

#endif

ext: hpp

max_stars_repo_name: dstrigl/mcotf

max_issues_repo_name: dstrigl/mcotf

max_forks_repo_name: dstrigl/mcotf


text:
#ifdef _WIN32
#include "tuntapinstaller.h"
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <boost/algorithm/string.hpp>
#pragma comment(lib, "IPHLPAPI.lib")
#include "../utils/system_exec.h"

const std::string TunTapDescription = "TAP-Windows Adapter V9";

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

std::string getTuntapAdapterName()
{
	std::vector<std::string> strs;
	auto res = ExecAndGetRes("getmac /fo csv /v");
	boost::split(strs, res, boost::is_any_of("\n"));

	if (strs.size() > 1)
	{
		for (auto str : strs)
		{
			std::vector<std::string> adapter_list;
			boost::split(adapter_list, str, boost::is_any_of(","));
			for (int i = 0; i < adapter_list.size(); i++)
			{
				if (boost::contains(adapter_list[i], TunTapDescription))
				{
					//boost::trim_if(adapter_list[i - 1], boost::is_any_of("\""));
					return adapter_list[i - 1];
				}
			}
		}
	}

	return "";
}

void TuntapInstaller::changeAdapterName()
{
	PIP_ADAPTER_INFO pAdapterInfo;
	PIP_ADAPTER_INFO pAdapter = NULL;
	DWORD dwRetVal = 0;
	UINT i;

	/* variables used to print DHCP time info */
	struct tm newtime;
	char buffer[32];
	errno_t error;

	ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
	pAdapterInfo = (IP_ADAPTER_INFO*)MALLOC(sizeof(IP_ADAPTER_INFO));
	if (pAdapterInfo == NULL) {
		printf("Error allocating memory needed to call GetAdaptersinfo\n");
		return;
	}
	// Make an initial call to GetAdaptersInfo to get
	// the necessary size into the ulOutBufLen variable
	if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
		FREE(pAdapterInfo);
		pAdapterInfo = (IP_ADAPTER_INFO*)MALLOC(ulOutBufLen);
		if (pAdapterInfo == NULL) {
			printf("Error allocating memory needed to call GetAdaptersinfo\n");
			return;
		}
	}
	bool tundevicefound = false;

	if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
		pAdapter = pAdapterInfo;
		while (pAdapter) {

			if (std::string(pAdapter->Description) == TunTapDescription)
			{
				tundevicefound = true;
				break;
			}
			pAdapter = pAdapter->Next;
		}
	}
	else {
		printf("GetAdaptersInfo failed with error: %d\n", dwRetVal);

	}

	if (tundevicefound)
	{
		std::string changeNameCmd = "netsh interface set interface name = " + getTuntapAdapterName() + " newname = \"UTUN64\" ";
		system(changeNameCmd.c_str());
	}

	if (pAdapterInfo)
		FREE(pAdapterInfo);

}

#endif

ext: cpp

max_stars_repo_name: dllexport/libtunosocks

max_issues_repo_name: dllexport/libtunosocks

max_forks_repo_name: dllexport/libtunosocks


text:
#ifndef SF1R_MINING_SUFFIX_MATCHMANAGER_H_
#define SF1R_MINING_SUFFIX_MATCHMANAGER_H_

#include "SuffixMatchMiningTask.hpp"
#include <common/type_defs.h>
#include <am/succinct/fm-index/fm_index.hpp>
#include <query-manager/ActionItem.h>
#include <mining-manager/group-manager/GroupParam.h>
#include <common/ResultType.h>

#include <boost/shared_ptr.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <list>

namespace sf1r
{
using izenelib::util::UString;
class DocumentManager;
class FilterManager;
class FMIndexManager;
namespace b5m {
class ProductMatcher;
}
class CategoryClassifyTable;
class FuzzyNormalizer;

namespace faceted
{
    class GroupManager;
    class AttrManager;
}
class NumericPropertyTableBuilder;

class SuffixMatchManager
{
public:
    SuffixMatchManager(
            const std::string& homePath,
            boost::shared_ptr<DocumentManager>& document_manager,
            faceted::GroupManager* groupmanager,
            faceted::AttrManager* attrmanager,
            NumericPropertyTableBuilder* numeric_tablebuilder,
            FuzzyNormalizer* fuzzyNormalizer);

    ~SuffixMatchManager();

    void addFMIndexProperties(const std::vector<std::string>& property_list, const VirtualConfig& virtualProperty, int type, bool finished = false);

    bool isStartFromLocalFM() const;

    size_t longestSuffixMatch(
            const std::string& pattern,
            std::vector<std::string> search_in_properties,
            size_t max_docs,
            std::vector<std::pair<double, uint32_t> >& res_list) const;

    size_t AllPossibleSuffixMatch(
            bool use_synonym,
            const std::list<std::pair<UString, double> >& major_tokens,
            const std::list<std::pair<UString, double> >& minor_tokens,
            const std::vector<std::string>& search_in_properties,
            size_t max_docs,
            const SearchingMode::SuffixMatchFilterMode& filter_mode,
            const std::vector<QueryFiltering::FilteringType>& filter_param,
            const faceted::GroupParam& group_param,
            std::vector<std::pair<double, uint32_t> >& res_list,
            double rank_boundary);

    SuffixMatchMiningTask* getMiningTask();

    bool buildMiningTask();

    boost::shared_ptr<FilterManager>& getFilterManager();

    void updateFmindex();

private:
    typedef izenelib::am::succinct::fm_index::FMIndex<uint16_t> FMIndexType;
    typedef FMIndexType::MatchRangeListT RangeListT;
    bool GetSynonymSet_(const UString& pattern, std::vector<UString>& synonym_set, int& setid);
    bool GetSynonymId_(const UString& pattern, int& setid);
    void ExpandSynonym_(const std::vector<std::pair<UString, double> >& tokens, std::vector<std::vector<std::pair<UString, double> > >& refine_tokens, size_t& major_size);
    bool getAllFilterRangeFromGroupLable_(
            const faceted::GroupParam& group_param,
            std::vector<size_t>& prop_id_list,
            std::vector<RangeListT>& filter_range_list) const;
    bool getAllFilterRangeFromAttrLable_(
            const faceted::GroupParam& group_param,
            std::vector<size_t>& prop_id_list,
            std::vector<RangeListT>& filter_range_list) const;
    bool getAllFilterRangeFromFilterParam_(
            const std::vector<QueryFiltering::FilteringType>& filter_param,
            std::vector<size_t>& prop_id_list,
            std::vector<RangeListT>& filter_range_list) const;

    std::string data_root_path_;

    boost::shared_ptr<DocumentManager> document_manager_;
    size_t last_doc_id_;

    boost::shared_ptr<FMIndexManager> fmi_manager_;
    boost::shared_ptr<FilterManager> filter_manager_;
    boost::shared_ptr<FilterManager> new_filter_manager;

    SuffixMatchMiningTask* suffixMatchTask_;

    typedef boost::shared_mutex MutexType;
    typedef boost::shared_lock<MutexType> ReadLock;
    typedef boost::unique_lock<MutexType> WriteLock;

    mutable MutexType mutex_;

    FuzzyNormalizer* fuzzyNormalizer_;
};

}

#endif


text:
/*
 * Copyright 2019 Applied Research Center for Computer Networks
 *
 * 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 "StatsBucket.hpp"

#include <runos/core/future.hpp>
#include <runos/core/logging.hpp>
#include <runos/core/catch_all.hpp>

#include "StatisticsStore.hpp"
#include "OFServer.hpp"

#include "lib/qt_executor.hpp"
#include "api/OFAgent.hpp"

#include <boost/thread/shared_mutex.hpp>
#include <range/v3/action/transform.hpp>
#include <range/v3/algorithm/fill.hpp>
#include <range/v3/to_container.hpp>
#include <range/v3/view/transform.hpp>

#include <unordered_map>
#include <iterator> // begin, end, move
#include <chrono>
#include <atomic>
#include <functional> // mem_fn

namespace runos {

REGISTER_APPLICATION(StatsBucketManager, {"of-server", ""})

class FlowStatsBucketImpl : public FlowStatsBucket
                          , public std::enable_shared_from_this<FlowStatsBucketImpl>
{
    Q_OBJECT

public:
    explicit FlowStatsBucketImpl(std::string name,
                                 StatsBucketManager::FlowSelector selector,
                                 QObject* parent)
        : id_(next_id++)
        , name_(std::move(name))
    {
        using namespace flow_selector;
        moveToThread(parent->thread());

        ofp::flow_stats_request req_proto;

        if (selector.get(table)) {
            req_proto.table_id = *selector.get(table);
        }

        if (selector.get(cookie) && not selector.get(cookie_mask)) {
            req_proto.cookie = *selector.get(cookie);
            req_proto.cookie_mask = 0xFFFFFFFFFFFFFFFFULL;
        }

        if (selector.get(cookie) && selector.get(cookie_mask)) {
            req_proto.cookie = *selector.get(cookie);
            req_proto.cookie_mask = *selector.get(cookie_mask);
        }

        if (selector.get(match)) {
            req_proto.match = std::move(*selector.get(match));
        }

        std::vector<uint32_t> out_ports;
        if (selector.get(out_port)) {
            out_ports = std::move(*selector.get(out_port));
        } else {
            out_ports.push_back(of13::OFPP_ANY);
        }

        std::vector<uint32_t> out_groups;
        if (selector.get(out_group)) {
            out_groups = std::move(*selector.get(out_group));
        } else {
            out_groups.push_back(of13::OFPG_ANY);
        }

        for (auto port : out_ports) {
            for (auto group : out_groups) {
                auto req = req_proto;
                req.out_port = port;
                req.out_group = group;
                requests_.push_back( std::move(req) );
            }
        }

        dpids_ = *selector.get(dpid);
        per_request_stats_.resize( dpids_.size() * requests_.size() );
    }

    void start(OFServer* ofserver, std::chrono::milliseconds period);

    // observers
    int id() const override { return id_; }
    std::string name() const override { return name_; }

    Statistics<FlowMeasurement> stats() const override
    {
        return aggregated_stats_.get();
    }

    void update();

protected:
    void timerEvent(QTimerEvent*) override;

private:
    using stats_store_type
        = StatisticsStore<FlowMeasurement>;

    static std::atomic<int> next_id;
    const int id_;
    const std::string name_;

    std::vector<uint64_t> dpids_;
    std::vector<OFAgentPtr> agents_;
    std::vector<ofp::flow_stats_request> requests_;

    std::chrono::steady_clock clock_;
    stats_store_type aggregated_stats_;
    std::vector< ofp::aggregate_stats > per_request_stats_;

    qt_executor executor {this};
    std::vector<OFAgentPtr> agents;
};

std::atomic<int> FlowStatsBucketImpl::next_id {0};

using FlowStatsBucketImplPtr = std::shared_ptr<FlowStatsBucketImpl>;
using FlowStatsBucketImplWeakPtr = std::weak_ptr<FlowStatsBucketImpl>;

void FlowStatsBucketImpl::start(OFServer* ofserver, std::chrono::milliseconds period)
{
    auto futures = dpids_
        | ranges::view::transform([&](auto id) { return ofserver->agent(id); })
        | ranges::to_<std::vector>();

    when_all_fix(futures.begin(), futures.end()).then(executor,
        [self = shared_from_this(), period](auto ret) {
            VLOG(10) << "Activating stats bucket " << self->id()
                << " (" << self->name() << ')';

            for (auto&& agent : ret.get()) {
                self->agents_.push_back(agent.get());
            }

            self->startTimer(period.count());
            self->update();
        });
}

void FlowStatsBucketImpl::timerEvent(QTimerEvent*)
try {
    update();
} catch (std::bad_weak_ptr const&) {
    // shared_ptr control block may be destroyed before
    // QObject deleted by deleteLater(), so ignore this
    // exception (caused by shared_from_this())
}

void FlowStatsBucketImpl::update()
{
    using future_vector =
        std::vector< future<ofp::aggregate_stats> >;

    future_vector futures;
    futures.reserve( per_request_stats_.size() );

    int j = 0;
    for (int i = agents_.size()-1; i >= 0; --i) {
        auto agent = agents_[i];
        for (auto& req : requests_) {
            try {
                auto f = agent->request_aggregate(req);
                futures.push_back(std::move(f));
            } catch (OFAgent::request_error const& ex) {
                futures.push_back(make_ready_future(per_request_stats_[j]));
                VLOG(10) << "Failed to request flow stats " << j << ":";
                //diagnostic_information::get().log();
            }
            ++j;
        }
    }

    when_all_fix(futures.begin(), futures.end()).then(executor,
        [self = shared_from_this()](future< future_vector > result) {
            VLOG(10) << "Entering flow stats continuation";

            FlowMeasurement<uint64_t> acc;
            ranges::fill(acc, 0);

            int j = 0;
            for (auto& fstats : result.get()) {
                ofp::aggregate_stats stats;
                try {
                    stats = fstats.get();
                } catch (OFAgent::openflow_error const& ex) {
                    stats = self->per_request_stats_[j];
                    VLOG(10) << "Failed to get flow stats " << j << ":";
                    diagnostic_information::get().log();
                }

                acc.packets() += stats.packets;
                acc.bytes() += stats.bytes;
                acc.flows() += stats.flows;
                ++j;
            }

            VLOG(10) << "Bucket " << self->id() << " (" << self->name() << ") updated";
            self->aggregated_stats_.append(self->clock_.now().time_since_epoch(), acc);
            emit self->updated();
        }
    );
}

///////////////////////////
//        Manager        //
///////////////////////////

struct StatsBucketManager::implementation
{
    OFServer* ofserver;
    mutable boost::shared_mutex mutex;
    std::unordered_map<int, FlowStatsBucketImplWeakPtr> bucket;
    std::unordered_map<std::string, FlowStatsBucketImplWeakPtr> bucket_by_name;
};

StatsBucketManager::StatsBucketManager()
    : impl(new implementation)
{ }

StatsBucketManager::~StatsBucketManager() noexcept = default;

void StatsBucketManager::init(Loader* loader, const Config&)
{
    impl->ofserver = OFServer::get(loader);
}

auto StatsBucketManager::bucket(int id) const
    -> FlowStatsBucketPtr
{
    boost::shared_lock< boost::shared_mutex > lock(impl->mutex);
    return impl->bucket.at(id).lock();
}

auto StatsBucketManager::bucket(std::string const& name) const
    -> FlowStatsBucketPtr
{
    boost::shared_lock< boost::shared_mutex > lock(impl->mutex);
    auto bucket_it = impl->bucket_by_name.find(name);
    if (bucket_it == impl->bucket_by_name.end())
        return nullptr;
    return bucket_it->second.lock();
}

auto StatsBucketManager::aggregateFlows(duration poll_interval,
                                        std::string name,
                                        FlowSelector selector)
    -> FlowStatsBucketPtr
{
    FlowStatsBucketImplPtr bucket {new FlowStatsBucketImpl(
        std::move(name),
        std::move(selector),
        this
    ), std::mem_fn(&QObject::deleteLater)};

    {
        boost::unique_lock< boost::shared_mutex > lock(impl->mutex);
        impl->bucket[bucket->id()] = bucket;
        if (not bucket->name().empty()) {
            impl->bucket_by_name[bucket->name()] = bucket;
        }
    }

    bucket->start(impl->ofserver, poll_interval);
    return bucket;
}

} // namespace runos

#include "StatsBucket.moc"

ext: cc

max_stars_repo_name: estepanov-lvk/runos

max_issues_repo_name: estepanov-lvk/runos

max_forks_repo_name: estepanov-lvk/runos


text:
///////////////////////////////////////////////////////////////////////////////
// numeric::algorithm::min_element.hpp                                       //
//                                                                           //
//  Copyright 2009 Erwann Rogard. 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_STATISTICS_DETAIL_NUMERIC_ALGORITHM_MIN_ELEMENT_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_NUMERIC_ALGORITHM_MIN_ELEMENT_HPP_ER_2009
#include <limits>
#include <boost/iterator/iterator_traits.hpp>
#include <boost/numeric/conversion/bounds.hpp>
#include <boost/limits.hpp>
#include <boost/concept_check.hpp>
#include <boost/concept/assert.hpp>
#include <iostream>

namespace boost{
namespace statistics{
namespace detail{
namespace numeric{
namespace algorithm{

// This is a rewrite of std::min_element with one additional argument, m, which
// is assigned the min value of *i over [first,last).
//
// Rationale: saves one dereferencing operation,
// which may be worthwhile if dereferencing is expensive.
template <typename It,typename V>
It min_element(It first, It last,V& min_value) {
    typedef typename iterator_value<It>::type value_type;

    // TODO see about enable_if/disable_if
    static bool has_inf = std::numeric_limits<V>::has_infinity;
    static V inf_if = std::numeric_limits<V>::infinity();
    static V highest = boost::numeric::bounds<V>::highest();
    static V inf_ = has_inf? inf_if : highest;

    BOOST_CONCEPT_ASSERT((
        boost::IncrementableIterator<It>
    ));

    min_value = inf_;
    value_type value;
    It result = first;
    while (first != last){
        value = (*first);
        if (value < min_value){
            min_value = value;
            result = first;
        }

        ++first;
    }
    return result;
}

}// algorithm
}// numeric
}// detail
}// statistics
}// boost

#endif


text:
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"
#include "Generic/theories/Lexicon.h"
#include "Generic/common/UnrecoverableException.h"
#include "Generic/common/InternalInconsistencyException.h"
#include "Generic/common/SessionLogger.h"
#include "Generic/state/XMLStrings.h"
#include "Generic/state/XMLTheoryElement.h"

#include <algorithm>
#include <boost/foreach.hpp>

Lexicon::Lexicon(size_t starting_size){
	_start_size = starting_size;

	//the entries stored by their key (symbol) value
	_entries_by_symbol_static = _new SymbolHashMap;
	_entries_by_symbol_dynamic = _new SymbolHashMap;
}

Lexicon::~Lexicon(){
	BOOST_FOREACH(LexicalEntry* entry, _entries_by_id)
		delete entry;
	delete _entries_by_symbol_static;
	delete _entries_by_symbol_dynamic;

};

Lexicon* Lexicon::_sessionLexicon = 0;
Lexicon *Lexicon::getSessionLexicon() {
	if (!_sessionLexicon) {
		_sessionLexicon = _factory()->build();
	}
	return _sessionLexicon;
}

void Lexicon::destroySessionLexicon() {
	delete _sessionLexicon;
	_sessionLexicon = 0;
}

boost::shared_ptr<Lexicon::Factory> &Lexicon::_factory() {
	static boost::shared_ptr<Lexicon::Factory> factory(new DefaultLexiconFactory());
	return factory;
}

//returns the number of entries with the given key and
//fills the result array with the corresponding entries
//MRK: fixed
int Lexicon::getEntriesByKey(Symbol key, LexicalEntry** result, int size){
	int nResults = 0;

	// add static matches
    nResults = addEntriesByKey(key, result, size, nResults, true);
	// add dynamic matches
    nResults = addEntriesByKey(key, result, size, nResults, false);
	return nResults;
}

// add results from either the static or dynamic table to the "results" array, up to a max of maxResults,
// and starting at the index "firstIndex". Return the *total* resulting size of the array.
// MRK: fixed
int Lexicon::addEntriesByKey(Symbol key,
							 LexicalEntry** results,
							 int maxResults,
							 int firstIndex,
							 bool useStaticTable)
{
	int count = firstIndex;

	SymbolHashMap *table = (useStaticTable ? _entries_by_symbol_static : _entries_by_symbol_dynamic);
	bool hasKey = (table->get(key) != NULL);

	if (hasKey){
		BOOST_FOREACH(LexicalEntry *entry, (*table)[key]) {
			if (entry == NULL) {
				throw UnrecoverableException("Lexicon::getEntriesByKey",
					std::string("NULL entry inside array for key: ") + key.to_debug_string());
			}
			if(count >= maxResults){
				//skip lexical entries
				//Todo: log in session logger
			}
			else results[count++] = entry;
		}
	}
	return count;
}

// MRK: fixed
int Lexicon::getNEntriesByKey(Symbol key){
	int nResults = 0;

	if(_entries_by_symbol_static->get(key) != NULL)
		nResults += static_cast<int>((*_entries_by_symbol_static)[key].size());

	if(_entries_by_symbol_dynamic->get(key) != NULL)
		nResults += static_cast<int>((*_entries_by_symbol_dynamic)[key].size());

	return nResults;
}

// MRK: fixed
LexicalEntry* Lexicon::getEntryByID(size_t id){

	if(id < MAX_ENTRIES){
		return _entries_by_id[id];
	}else{
		return NULL;
	}
}

size_t Lexicon::getNextID(){
	return _entries_by_id.size();
}

void Lexicon::addStaticEntryDBG(LexicalEntry* le) {
	SessionLogger::info("SERIF")<<"In addStaticEntryDBG() "<<std::endl;
	SessionLogger::info("SERIF")<<"Current Entries_by_symbol_static size: "<<static_cast<int>(_entries_by_symbol_static->size())<<std::endl;

	// make sure we're still populating the static part of the array
	if (le->getID() >= _start_size){
		SessionLogger::err("SERIF")<<"Throw Inconsistent Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", is not a static ID.";
		throw UnrecoverableException("Lexicon::addStaticEntry", message.str());
	}

	addEntryDBG(le, true);
}

void Lexicon::addDynamicEntryDBG(LexicalEntry* le) {
	SessionLogger::info("SERIF")<<"In addDynamicEntryDBG() "<<std::endl;
	SessionLogger::info("SERIF")<<"Current Entries_by_symbol_dynamic size: "<<static_cast<int>(_entries_by_symbol_dynamic->size())<<std::endl;

	// make sure we're populating the dynamic part of the array
	if (le->getID() < _start_size){
		SessionLogger::err("SERIF")<<"Throw Inconsistent Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", is not a dynamic ID.";
		throw UnrecoverableException("Lexicon::addDynamicEntry", message.str());
	}

    addEntryDBG(le, false);
}

// MRK: fixed
void Lexicon::addEntryDBG(LexicalEntry* le, bool isStaticEntry) throw (UnrecoverableException){
	SessionLogger::info("SERIF")<<"In addEntryDBG() "<<std::endl;
	if (le->getID() != _entries_by_id.size()){
		std::cerr<<"Throw Inconsistent Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", not allowed. Please choose use, " << _entries_by_id.size();
		throw UnrecoverableException("Lexicon::addEntry", message.str());
	}else if (le->getID() >= MAX_ENTRIES){
		SessionLogger::err("SERIF")<<"Throw Too high Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", exceeds maximum number of entries allowed, " << MAX_ENTRIES;
//this wasn't caught???
		SessionLogger::err("SERIF")<<"Exception: "<<message.str()<<std::endl;
		throw UnrecoverableException("Lexicon::addEntry", message.str());
	}else{
		SessionLogger::info("SERIF")<<"adding lexentry id: "<<static_cast<int>(le->getID())<<std::endl;
		_entries_by_id.push_back(le);
		SessionLogger::info("SERIF")<<"added to entries by id"<<std::endl;

		SymbolHashMap *table = (isStaticEntry ? _entries_by_symbol_static : _entries_by_symbol_dynamic);
		bool hasKey = (table->get(le->getKey()) != NULL);

		//if the key exists
		if(hasKey){
			SessionLogger::info("SERIF")<<"try adding to known key"<<std::endl;
			if((*table)[le->getKey()].size() >= MAX_ENTRIES_PER_SYMBOL){
				std::stringstream message;
				message << "LexicalEntry with symbol, " << le->getKey().to_debug_string() << ", cannot be added to array exceeding maximum number of entries per key, " << MAX_ENTRIES_PER_SYMBOL;
				SessionLogger::info("SERIF")<<"too many exceptions"<<std::endl;
				throw UnrecoverableException("Lexicon::addEntry", message.str());
			}else{
				(*table)[le->getKey()].push_back(le);
			}
			SessionLogger::info("SERIF")<<"added"<<std::endl;
		//else if the key doesn't exist yet
		}else{
			SessionLogger::info("SERIF")<<"try adding to unknown key"<<std::endl;
			SessionLogger::info("SERIF")<<"key: "<<le->getKey().to_debug_string()
				<<" HashCode: "<<static_cast<int>(le->getKey().hash_code())<<std::endl;
			SessionLogger::info("SERIF")<<"Current Entries_by_symbol size: "<<static_cast<int>(table->size())<<std::endl;

			//add the new lexical item
			(*table)[le->getKey()].push_back(le);
			SessionLogger::info("SERIF")<<"added"<<std::endl;

		}
	}

	return;
}

void Lexicon::addStaticEntry(LexicalEntry* le) throw (UnrecoverableException){
	// make sure we're still populating the static part of the array
	if (le->getID() >= _start_size){
		SessionLogger::err("SERIF")<<"Throw Inconsistent Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", is not a static ID.";
		throw UnrecoverableException("Lexicon::addStaticEntry", message.str());
	}

	addEntry(le, true);
}

void Lexicon::addDynamicEntry(LexicalEntry* le) throw (UnrecoverableException){
	// make sure we're populating the dynamic part of the array
	if (le->getID() < _start_size){
		SessionLogger::err("SERIF")<<"Throw Inconsistent Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", is not a dynamic ID.";
		throw UnrecoverableException("Lexicon::addDynamicEntry", message.str());
	}

	addEntry(le, false);
}

//TODO
void Lexicon::clearDynamicEntries() {
	//// delete and reinstantiate the dynamic symbol hash
	//delete _entries_by_symbol_dynamic;
	//_entries_by_symbol_dynamic = _new SymbolHashMap(MAX_DYNAMIC_ENTRIES);

	// deleting the whole hash is too slow. instead remove all the elements.
	_entries_by_symbol_dynamic->clear();

	// delete the dynamic part of the array
	_entries_by_id.erase(_entries_by_id.begin()+_start_size, _entries_by_id.end());
}

// MRK: fixed
void Lexicon::addEntry(LexicalEntry* le, bool isStaticEntry) throw (UnrecoverableException){

	// if it's not the correct next id, it's an error
	if (le->getID() != getNextID()){
		SessionLogger::err("SERIF")<<"Throw Inconsistent Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", not allowed. Please choose use, " << getNextID();
		throw UnrecoverableException("Lexicon::addEntry", message.str());
	}
	// if we don't have room for another entry, it's an error
	else if (le->getID() >= MAX_ENTRIES){
		SessionLogger::err("SERIF")<<"Throw Too high Exception "<<std::endl;
		std::stringstream message;
		message << "LexicalEntry ID, " << le->getID() << ", exceeds maximum number of entries allowed, " << MAX_ENTRIES;
		//this wasn't caught???
		SessionLogger::err("SERIF")<<"Exception: "<<message.str()<<std::endl;
		throw UnrecoverableException("Lexicon::addEntry", message.str());
	}
	// else we're ok
	else{
		// add to array
		// regardless of static or dynamic we add to the same array
		_entries_by_id.push_back(le);

		// add to table
		// specifically, add to the static or the dynamic table
		SymbolHashMap *table = (isStaticEntry ? _entries_by_symbol_static : _entries_by_symbol_dynamic);
		bool hasKey = (table->get(le->getKey()) != NULL);

		//if the key exists
		if(hasKey) {
			if((*table)[le->getKey()].size() >= MAX_ENTRIES_PER_SYMBOL){
				std::stringstream message;
				message << "LexicalEntry with symbol, " << le->getKey().to_debug_string() << ", cannot be added to array exceeding maximum number of entries per key, " << MAX_ENTRIES_PER_SYMBOL;
				SessionLogger::info("SERIF")<<"skipping entry: "<<message.str()<<std::endl;
				//throw UnrecoverableException("Lexicon::addEntry", message.str());
			}else{
				(*table)[le->getKey()].push_back(le);
			}
		//else if the key doesn't exist yet
		}else{
			//add the new lexical item
			(*table)[le->getKey()].push_back(le);

		}
	}

	return;
}

bool Lexicon::hasID(size_t id){
	return (id < _entries_by_id.size());
}

bool Lexicon::isDynamicEntry(size_t id) {
	return hasID(id) && (id >= _start_size);
}

bool Lexicon::isStaticEntry(size_t id) {
	return (id < _start_size);
}

//MRK: commented out because it wasn't used
/*
void Lexicon::removeAddedEntries()throw (UnrecoverableException){
	if(!_clear_lexicon){
		throw UnrecoverableException("Lexicon::removeAddedEntries",
			"Try to remove added entries without setting _clear_lexicion");
	}
	if(_n_entries < (MAX_ENTRIES - 1000)){
		return;
	}
	UTF8OutputStream uos;
	char buffer[500];
	std::cout<<"Writing Old Lexicon"<<std::endl;
	//sprintf(buffer,"\\\\traid02\\users\\mfreedman\\lexicon.%d.txt",_reset_counter);
	sprintf(buffer,"C:\\clitic_sep\\lexicon.%d.txt",_reset_counter);
	uos.open(buffer);
	dump(uos);
	uos.close();
	std::cout<<"Removing Lexical Entries"<<std::endl;
	SymbolHashMap::iterator startIt = _entries_by_symbol->begin();
	SymbolHashMap::iterator endIt = _entries_by_symbol->end();
	Symbol remove_list[MAX_SYMBOLS];
	int removecount =0;
	for(SymbolHashMap::iterator it = startIt; it!=endIt; ++it){
		SymbolHashEntry* ents = &((SymbolHashEntry)(*it).second);
		int nent = ents->n_entries;
		for(int i=0; i<nent;i++){
			if(ents->entries[i]->getID() >_start_size){
				ents->entries[i] = NULL;
				ents->n_entries--;
			}
		}
		if(ents->n_entries == 0){
			remove_list[removecount] = (Symbol)(*it).first;
			removecount++;
		}
	}
	for(int i=0; i<removecount; i++){
		_entries_by_symbol->remove(remove_list[i]);
	}
	size_t s= _start_size;
	size_t end = _n_entries;
	for(size_t i=s;  i<end; i++){
		LexicalEntry* le = _entries_by_id[i];
		delete _entries_by_id[i];
	}
	_n_entries = _start_size;
	std::cout<<"Writing New Lexicon"<<std::endl;
	//sprintf(buffer,"\\\\traid02\\users\\mfreedman\\new_lexicon.%d.txt",_reset_counter);
	sprintf(buffer,"C:\\clitic_sep\\new_lexicon.%d.txt",_reset_counter);
	uos.open(buffer);
	dump(uos);
	uos.close();
	_reset_counter++;
	std::cout<<"done with reset"<<std::endl;

}
*/

// MRK: fixed
bool Lexicon::hasKey(Symbol key){
	return
		(_entries_by_symbol_static->get(key) != NULL) ||
		(_entries_by_symbol_dynamic->get(key) != NULL);
}

size_t Lexicon::getNEntries(){
	return _entries_by_id.size();
}

LexicalEntry* Lexicon::findEntry(LexicalEntry* entry) {
	LexicalEntry *static_le = findEntryInTable(entry, _entries_by_symbol_static);
	if (static_le != NULL)
		return static_le;
	else
		return findEntryInTable(entry, _entries_by_symbol_static);
}

namespace {
	// Private class used by findEntryInTable to search for a lexical entry.
	struct LexicalEntryEquals {
		LexicalEntry* target;
		LexicalEntryEquals(LexicalEntry* target): target(target) {}
		bool operator()(LexicalEntry* entry) {
			return (*target) == (*entry);
		}
	};
}

LexicalEntry* Lexicon::findEntryInTable(LexicalEntry* entry, SymbolHashMap* table) {
	std::vector<LexicalEntry*> &row = (*table)[entry->getKey()];
	std::vector<LexicalEntry*>::iterator it = std::find_if(row.begin(), row.end(), LexicalEntryEquals(entry));
	if (it == row.end()) return 0;
	else return *it;
}

void Lexicon::dump(UTF8OutputStream &uos){
	uos << (int)	getNEntries() << "\n";

	//initialize the array to 0
	BOOST_FOREACH(LexicalEntry* entry, _entries_by_id) {
		entry->dump(uos);
	}
}

//MRK: ok
void Lexicon::dumpDynamicVocab(UTF8OutputStream &uos){
	size_t new_entries = getNEntries() - _start_size;
	if(new_entries > 0){
		uos<< static_cast<int>(new_entries)<<"\n";
		for(size_t entry = _start_size; entry < getNEntries(); entry++){
			_entries_by_id[entry]->dump(uos);
		}
	}
}

void Lexicon::updateObjectIDTable() const {
	throw InternalInconsistencyException("Lexicon::updateObjectIDTable()",
										"Using unimplemented method.");
}

void Lexicon::saveState(StateSaver *stateSaver) const {
	throw InternalInconsistencyException("Lexicon::saveState()",
										"Using unimplemented method.");

}

void Lexicon::resolvePointers(StateLoader * stateLoader) {
	throw InternalInconsistencyException("Lexicon::resolvePointers()",
										"Using unimplemented method.");

}

const wchar_t* Lexicon::XMLIdentifierPrefix() const {
	return L"lexicon";
}

void Lexicon::saveXML(SerifXML::XMLTheoryElement lexiconElem, const Theory *context) const {
	using namespace SerifXML;
	if (context != 0)
		throw InternalInconsistencyException("Lexicon::saveXML", "Expected context to be NULL");
	SessionLogger::warn("unimplemented_method") << "saveXML method not filled in yet!" << std::endl; // [XX] FILL THIS IN [XX]
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
#include "Session.h"

#include <boost/beast.hpp>
#include <boost/asio.hpp>

#include <iostream>
#include <memory>

//----------------------------------------------------------------------------------------------------------------------
Session::Session(boost::asio::ip::tcp::socket&& socket)
    :
    m_websocket(std::move(socket))
{
}

//----------------------------------------------------------------------------------------------------------------------
void Session::run()
{
    // Execution needs to take place within a strand to perform the async operations on the I/O objects in this Session.
    boost::asio::dispatch(m_websocket.get_executor(),
                          boost::beast::bind_front_handler(&Session::onRun, shared_from_this()));
}

//----------------------------------------------------------------------------------------------------------------------
void Session::onRun()
{
    // Set suggested timeout settings for the websocket
    m_websocket.set_option(boost::beast::websocket::stream_base::timeout::suggested(boost::beast::role_type::server));

    // Set a decorator to change the Server of the handshake
    m_websocket.set_option(boost::beast::websocket::stream_base::decorator(
        [](boost::beast::websocket::response_type& res)
        {
            res.set(boost::beast::http::field::server,
                std::string(BOOST_BEAST_VERSION_STRING) + " websocket-server-async");
        }));

    // Accept the websocket handshake
    m_websocket.async_accept(boost::beast::bind_front_handler(&Session::onAccept, shared_from_this()));
}

//----------------------------------------------------------------------------------------------------------------------
void Session::onAccept(boost::beast::error_code errorCode)
{
    if (errorCode)
    {
        // TODO - Fairly certain we cannot throw from the strand
        //        Would probably just log and continue on to accept other connections
        std::cerr << "Session::onAccept called with error code: " << errorCode << std::endl;
    }

    // Read a message
    doRead();
}

//----------------------------------------------------------------------------------------------------------------------
void Session::doRead()
{
    // Read a message into our buffer
    m_websocket.async_read(m_buffer,
                           boost::beast::bind_front_handler(&Session::onRead, shared_from_this()));
}

//----------------------------------------------------------------------------------------------------------------------
void Session::onRead(boost::beast::error_code errorCode, std::size_t bytesTransferred)
{
    boost::ignore_unused(bytesTransferred);

    // This indicates that the Session was closed
    if (errorCode == boost::beast::websocket::error::closed)
    {
        return;
    }

    if (errorCode)
    {
        // TODO - Fairly certain we cannot throw from the strand
        //        Would probably just log
        //        Might flag the session for closure if repeated errors. Test.
        std::cerr << "Session::onRead called with error code: " << errorCode << std::endl;
    }

    // Echo the message
    m_websocket.text(m_websocket.got_text());
    m_websocket.async_write(m_buffer.data(),
                            boost::beast::bind_front_handler(&Session::onWrite, shared_from_this()));
}

//----------------------------------------------------------------------------------------------------------------------
void Session::onWrite(boost::beast::error_code errorCode, std::size_t bytesTransferred)
{
    boost::ignore_unused(bytesTransferred);

    if (errorCode)
    {
        // TODO - Fairly certain we cannot throw from the strand
        //        Would probably just log
        //        Might flag the session for closure if repeated errors. Test.
        std::cerr << "Session::onWrite called with error code: " << errorCode << std::endl;
    }

    // Clear the buffer
    m_buffer.consume(m_buffer.size());

    // Do another read
    doRead();
}


text:
#pragma once

#include <steemit/protocol/transaction.hpp>

#include <steemit/chain/steem_object_types.hpp>

#include <boost/multi_index/hashed_index.hpp>

namespace steemit {
    namespace chain {

        using steemit::protocol::signed_transaction;

        /**
         * The purpose of this object is to enable the detection of duplicate transactions. When a transaction is included
         * in a block a transaction_object is added. At the end of block processing all transaction_objects that have
         * expired can be removed from the index.
         */
        class transaction_object
                : public object<transaction_object_type, transaction_object> {
            transaction_object() = delete;

        public:
            template<typename Constructor, typename Allocator>
            transaction_object(Constructor &&c, allocator <Allocator> a)
                    : packed_trx(a) {
                c(*this);
            }

            id_type id;

            bip::vector<char, allocator<char>> packed_trx;
            transaction_id_type trx_id;
            time_point_sec expiration;
        };

        struct by_expiration;
        struct by_trx_id;
        typedef multi_index_container <
        transaction_object,
        indexed_by<
                ordered_unique < tag <
                by_id>, member<transaction_object, transaction_object_id_type, &transaction_object::id>>,
        hashed_unique<tag<by_trx_id>, BOOST_MULTI_INDEX_MEMBER(transaction_object, transaction_id_type, trx_id), std::hash<transaction_id_type>>,
        ordered_non_unique <tag<by_expiration>, member<transaction_object, time_point_sec, &transaction_object::expiration>>
        >,
        allocator <transaction_object>
        >
        transaction_index;

    }
} // steemit::chain

FC_REFLECT(steemit::chain::transaction_object, (id)(packed_trx)(trx_id)(expiration))
CHAINBASE_SET_INDEX_TYPE(steemit::chain::transaction_object, steemit::chain::transaction_index)

max_stars_repo_name: sergeyrizan/botchain-bot

max_issues_repo_name: sergeyrizan/botchain-bot

max_forks_repo_name: sergeyrizan/botchain-bot


text:
/*=============================================================================
    Copyright (c) 2001-2009 Hartmut Kaiser

    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/config/warning_disable.hpp>
#include <boost/spirit/include/karma_operator.hpp>
#include <boost/spirit/include/karma_char.hpp>
#include <boost/spirit/include/karma_string.hpp>
#include <boost/spirit/include/karma_numeric.hpp>
#include <boost/spirit/include/karma_nonterminal.hpp>
#include <boost/spirit/include/karma_generate.hpp>

#include "test.hpp"

using namespace boost::spirit;
using namespace boost::spirit::karma;
using namespace boost::spirit::ascii;

struct num_list : grammar<char const*, rule<char const*> >
{
    num_list()
    {
        using boost::spirit::int_;
        start = int_(1) << ',' << int_(0);
    }

    rule<char const*, rule<char const*> > start;
};

// this test must fail compiling
int main()
{
    using boost::make_function_output_iterator;
    using spirit_test::make_string_appender;

    std::string generated;

    num_list def;
    bool r = generate_delimited(
                make_function_output_iterator(make_string_appender(generated)),
                make_generator(def), char_('%') << '\n');

    return 0;
}


text:
// Boost.Geometry

// This file was modified by Oracle on 2018, 2019.
// Modifications copyright (c) 2018, 2019, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to 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_GEOMETRY_SRS_PROJECTIONS_GRIDS_HPP
#define BOOST_GEOMETRY_SRS_PROJECTIONS_GRIDS_HPP

#include <boost/geometry/srs/projections/impl/pj_gridinfo.hpp>

#include <fstream>

namespace boost { namespace geometry
{

namespace projections { namespace detail
{

struct grids_tag {};
struct shared_grids_tag {};

}} // namespace projections::detail

namespace srs
{

class grids
{
public:
    std::size_t size() const
    {
        return gridinfo.size();
    }

    bool empty() const
    {
        return gridinfo.empty();
    }

    typedef projections::detail::grids_tag tag;

    projections::detail::pj_gridinfo gridinfo;
};

struct ifstream_policy
{
    typedef std::ifstream stream_type;

    static inline void open(stream_type & is, std::string const& gridname)
    {
        is.open(gridname.c_str(), std::ios::binary);
    }
};

template
<
    typename StreamPolicy = srs::ifstream_policy,
    typename Grids = grids
>
struct grids_storage
{
    typedef StreamPolicy stream_policy_type;
    typedef Grids grids_type;

    grids_storage()
    {}

    explicit grids_storage(stream_policy_type const& policy)
        : stream_policy(policy)
    {}

    stream_policy_type stream_policy;
    grids_type hgrids;
};

template <typename GridsStorage = grids_storage<> >
class projection_grids
{
public:
    projection_grids(GridsStorage & storage)
        : m_storage_ptr(boost::addressof(storage))
    {}

    typedef GridsStorage grids_storage_type;

    GridsStorage & grids_storage() const
    {
        return *m_storage_ptr;
    }

private:
    GridsStorage * const m_storage_ptr;

public:
    std::vector<std::size_t> hindexes;
};

template <typename GridsStorage = grids_storage<> >
struct transformation_grids
{
    explicit transformation_grids(GridsStorage & storage)
        : src_grids(storage)
        , dst_grids(storage)
    {}

    projection_grids<GridsStorage> src_grids;
    projection_grids<GridsStorage> dst_grids;
};

namespace detail
{

struct empty_grids_storage {};
struct empty_projection_grids {};

} // namespace detail

template <>
struct transformation_grids<detail::empty_grids_storage>
{
    detail::empty_projection_grids src_grids;
    detail::empty_projection_grids dst_grids;
};

}}} // namespace boost::geometry::srs

#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_GRIDS_HPP

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/*
 *  tutte.hpp
 *
 *
 *  Created by Andrea Bedini on 24/Nov/2011.
 *  Copyright (c) 2011-2014, Andrea Bedini <andrea.bedini@gmail.com>.
 *
 *  Distributed under the terms of the Modified BSD License.
 *  The full license is in the file COPYING, distributed as part of
 *  this software.
 *
 */

#ifndef TUTTE_HPP
#define TUTTE_HPP

#include "connectivity/connectivity.hpp"
#include <boost/unordered/unordered_map.hpp>

template<class Weight>
class tutte
{
  const Weight Q;
  const Weight v;

public:
  using weight_type = Weight ;
  using table_type = boost::unordered_map<connectivity, weight_type>;

  template<class T, class U>
  tutte(T const& Q_, U const& v_) : Q(Q_), v(v_) {}

  table_type empty_state(unsigned int size) const
  {
    table_type tmp_table;
    tmp_table[connectivity(size)] = Weight(1);
    return tmp_table;
  }

  table_type
  join_operator(unsigned int i, unsigned int j, table_type const& t) const
  {
    table_type tmp_table;
    for (auto const & e : t) {
      tmp_table[e.first] += e.second;
      tmp_table[connectivity(e.first).connect(i, j).canonicalize()]
        += e.second * v;
    }
    return tmp_table;
  }

  table_type
  delete_operator(unsigned int i, table_type const& t) const
  {
    table_type tmp_table;
    for (auto const& e : t) {
      tmp_table[connectivity(e.first).delete_node(i).canonicalize()]
        += (e.first.singleton(i) ? (e.second * Q) : e.second);
    }
    return tmp_table;
  }

  template<class Mapping>
  table_type
  table_fusion(Mapping A_to_B,
    table_type const& A_table,
    table_type const& B_table) const
  {
    table_type tmp_table;
    for (auto const & eA : A_table) {
      for (auto const & eB : B_table) {
        connectivity c = eB.first;
        eA.first.decompose([&](unsigned int i, unsigned int j) {
          c.connect(A_to_B[i], A_to_B[j]);
        });
        tmp_table[c.canonicalize()] += eA.second * eB.second;
      }
    }
    return tmp_table;
  }
};
#endif

max_stars_repo_name: andreabedini/tutte

max_issues_repo_name: andreabedini/tutte

max_forks_repo_name: andreabedini/tutte


text:
/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
 *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
 *    Author(s):       Vincent Rouvreau
 *
 *    Copyright (C) 2015 Inria
 *
 *    Modification(s):
 *      - YYYY/MM Author: Description of the modification
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "alpha_complex"
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>

#include <CGAL/Delaunay_triangulation.h>
#include <CGAL/Epick_d.h>
#include <CGAL/Epeck_d.h>

#include <cmath>  // float comparison
#include <limits>
#include <string>
#include <vector>

#include <gudhi/Alpha_complex.h>
// to construct a simplex_tree from Delaunay_triangulation
#include <gudhi/graph_simplicial_complex.h>
#include <gudhi/Simplex_tree.h>
#include <gudhi/Unitary_tests_utils.h>

// Use dynamic_dimension_tag for the user to be able to set dimension
typedef CGAL::Epeck_d< CGAL::Dynamic_dimension_tag > Exact_kernel_d;
// Use static dimension_tag for the user not to be able to set dimension
typedef CGAL::Epeck_d< CGAL::Dimension_tag<3> > Exact_kernel_s;
// Use dynamic_dimension_tag for the user to be able to set dimension
typedef CGAL::Epick_d< CGAL::Dynamic_dimension_tag > Inexact_kernel_d;
// Use static dimension_tag for the user not to be able to set dimension
typedef CGAL::Epick_d< CGAL::Dimension_tag<3> > Inexact_kernel_s;
// The triangulation uses the default instantiation of the TriangulationDataStructure template parameter

typedef boost::mpl::list<Exact_kernel_d, Exact_kernel_s, Inexact_kernel_d, Inexact_kernel_s> list_of_kernel_variants;

BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_from_OFF_file, TestedKernel, list_of_kernel_variants) {
  // ----------------------------------------------------------------------------
  //
  // Init of an alpha-complex from a OFF file
  //
  // ----------------------------------------------------------------------------
  std::string off_file_name("alphacomplexdoc.off");
  double max_alpha_square_value = 60.0;
  std::clog << "========== OFF FILE NAME = " << off_file_name << " - alpha²=" <<
      max_alpha_square_value << "==========" << std::endl;

  Gudhi::alpha_complex::Alpha_complex<TestedKernel> alpha_complex_from_file(off_file_name);

  Gudhi::Simplex_tree<> simplex_tree_60;
  BOOST_CHECK(alpha_complex_from_file.create_complex(simplex_tree_60, max_alpha_square_value));

  std::clog << "simplex_tree_60.dimension()=" << simplex_tree_60.dimension() << std::endl;
  BOOST_CHECK(simplex_tree_60.dimension() == 2);

  std::clog << "simplex_tree_60.num_vertices()=" << simplex_tree_60.num_vertices() << std::endl;
  BOOST_CHECK(simplex_tree_60.num_vertices() == 7);

  std::clog << "simplex_tree_60.num_simplices()=" << simplex_tree_60.num_simplices() << std::endl;
  BOOST_CHECK(simplex_tree_60.num_simplices() == 25);

  max_alpha_square_value = 59.0;
  std::clog << "========== OFF FILE NAME = " << off_file_name << " - alpha²=" <<
      max_alpha_square_value << "==========" << std::endl;

  Gudhi::Simplex_tree<> simplex_tree_59;
  BOOST_CHECK(alpha_complex_from_file.create_complex(simplex_tree_59, max_alpha_square_value));

  std::clog << "simplex_tree_59.dimension()=" << simplex_tree_59.dimension() << std::endl;
  BOOST_CHECK(simplex_tree_59.dimension() == 2);

  std::clog << "simplex_tree_59.num_vertices()=" << simplex_tree_59.num_vertices() << std::endl;
  BOOST_CHECK(simplex_tree_59.num_vertices() == 7);

  std::clog << "simplex_tree_59.num_simplices()=" << simplex_tree_59.num_simplices() << std::endl;
  BOOST_CHECK(simplex_tree_59.num_simplices() == 23);
}

// Use static dimension_tag for the user not to be able to set dimension
typedef CGAL::Epeck_d< CGAL::Dimension_tag<4> > Kernel_4;
typedef Kernel_4::Point_d Point_4;
typedef std::vector<Point_4> Vector_4_Points;

bool is_point_in_list(Vector_4_Points points_list, Point_4 point) {
  for (auto& point_in_list : points_list) {
    if (point_in_list == point) {
      return true;  // point found
    }
  }
  return false;  // point not found
}

BOOST_AUTO_TEST_CASE(Alpha_complex_from_points) {
  // ----------------------------------------------------------------------------
  // Init of a list of points
  // ----------------------------------------------------------------------------
  Vector_4_Points points;
  std::vector<double> coords = { 0.0, 0.0, 0.0, 1.0 };
  points.push_back(Point_4(coords.begin(), coords.end()));
  coords = { 0.0, 0.0, 1.0, 0.0 };
  points.push_back(Point_4(coords.begin(), coords.end()));
  coords = { 0.0, 1.0, 0.0, 0.0 };
  points.push_back(Point_4(coords.begin(), coords.end()));
  coords = { 1.0, 0.0, 0.0, 0.0 };
  points.push_back(Point_4(coords.begin(), coords.end()));

  // ----------------------------------------------------------------------------
  // Init of an alpha complex from the list of points
  // ----------------------------------------------------------------------------
  Gudhi::alpha_complex::Alpha_complex<Kernel_4> alpha_complex_from_points(points);

  std::clog << "========== Alpha_complex_from_points ==========" << std::endl;

  Gudhi::Simplex_tree<> simplex_tree;
  BOOST_CHECK(alpha_complex_from_points.create_complex(simplex_tree));

  // Another way to check num_simplices
  std::clog << "Iterator on alpha complex simplices in the filtration order, with [filtration value]:" << std::endl;
  int num_simplices = 0;
  for (auto f_simplex : simplex_tree.filtration_simplex_range()) {
    num_simplices++;
    std::clog << "   ( ";
    for (auto vertex : simplex_tree.simplex_vertex_range(f_simplex)) {
      std::clog << vertex << " ";
    }
    std::clog << ") -> " << "[" << simplex_tree.filtration(f_simplex) << "] ";
    std::clog << std::endl;
  }
  BOOST_CHECK(num_simplices == 15);
  std::clog << "simplex_tree.num_simplices()=" << simplex_tree.num_simplices() << std::endl;
  BOOST_CHECK(simplex_tree.num_simplices() == 15);

  std::clog << "simplex_tree.dimension()=" << simplex_tree.dimension() << std::endl;
  BOOST_CHECK(simplex_tree.dimension() == 3);
  std::clog << "simplex_tree.num_vertices()=" << simplex_tree.num_vertices() << std::endl;
  BOOST_CHECK(simplex_tree.num_vertices() == points.size());

  for (auto f_simplex : simplex_tree.filtration_simplex_range()) {
    switch (simplex_tree.dimension(f_simplex)) {
      case 0:
        GUDHI_TEST_FLOAT_EQUALITY_CHECK(simplex_tree.filtration(f_simplex), 0.0);
        break;
      case 1:
        GUDHI_TEST_FLOAT_EQUALITY_CHECK(simplex_tree.filtration(f_simplex), 1.0/2.0);
        break;
      case 2:
        GUDHI_TEST_FLOAT_EQUALITY_CHECK(simplex_tree.filtration(f_simplex), 2.0/3.0);
        break;
      case 3:
        GUDHI_TEST_FLOAT_EQUALITY_CHECK(simplex_tree.filtration(f_simplex), 3.0/4.0);
        break;
      default:
        BOOST_CHECK(false);  // Shall not happen
        break;
    }
  }

  Point_4 p0 = alpha_complex_from_points.get_point(0);
  std::clog << "alpha_complex_from_points.get_point(0)=" << p0 << std::endl;
  BOOST_CHECK(4 == p0.dimension());
  BOOST_CHECK(is_point_in_list(points, p0));

  Point_4 p1 = alpha_complex_from_points.get_point(1);
  std::clog << "alpha_complex_from_points.get_point(1)=" << p1 << std::endl;
  BOOST_CHECK(4 == p1.dimension());
  BOOST_CHECK(is_point_in_list(points, p1));

  Point_4 p2 = alpha_complex_from_points.get_point(2);
  std::clog << "alpha_complex_from_points.get_point(2)=" << p2 << std::endl;
  BOOST_CHECK(4 == p2.dimension());
  BOOST_CHECK(is_point_in_list(points, p2));

  Point_4 p3 = alpha_complex_from_points.get_point(3);
  std::clog << "alpha_complex_from_points.get_point(3)=" << p3 << std::endl;
  BOOST_CHECK(4 == p3.dimension());
  BOOST_CHECK(is_point_in_list(points, p3));

  // Test to the limit
  BOOST_CHECK_THROW (alpha_complex_from_points.get_point(4), std::out_of_range);
  BOOST_CHECK_THROW (alpha_complex_from_points.get_point(-1), std::out_of_range);
  BOOST_CHECK_THROW (alpha_complex_from_points.get_point(1234), std::out_of_range);

  // Test after prune_above_filtration
  bool modified = simplex_tree.prune_above_filtration(0.6);
  BOOST_CHECK(modified);

  // Another way to check num_simplices
  std::clog << "Iterator on alpha complex simplices in the filtration order, with [filtration value]:" << std::endl;
  num_simplices = 0;
  for (auto f_simplex : simplex_tree.filtration_simplex_range()) {
    num_simplices++;
    std::clog << "   ( ";
    for (auto vertex : simplex_tree.simplex_vertex_range(f_simplex)) {
      std::clog << vertex << " ";
    }
    std::clog << ") -> " << "[" << simplex_tree.filtration(f_simplex) << "] ";
    std::clog << std::endl;
  }
  BOOST_CHECK(num_simplices == 10);
  std::clog << "simplex_tree.num_simplices()=" << simplex_tree.num_simplices() << std::endl;
  BOOST_CHECK(simplex_tree.num_simplices() == 10);

  std::clog << "simplex_tree.dimension()=" << simplex_tree.dimension() << std::endl;
  BOOST_CHECK(simplex_tree.dimension() == 1);
  std::clog << "simplex_tree.num_vertices()=" << simplex_tree.num_vertices() << std::endl;
  BOOST_CHECK(simplex_tree.num_vertices() == 4);

  for (auto f_simplex : simplex_tree.filtration_simplex_range()) {
    switch (simplex_tree.dimension(f_simplex)) {
      case 0:
        GUDHI_TEST_FLOAT_EQUALITY_CHECK(simplex_tree.filtration(f_simplex), 0.0);
        break;
      case 1:
        GUDHI_TEST_FLOAT_EQUALITY_CHECK(simplex_tree.filtration(f_simplex), 1.0/2.0);
        break;
      default:
        BOOST_CHECK(false);  // Shall not happen
        break;
    }
  }

}

BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_from_empty_points, TestedKernel, list_of_kernel_variants) {
  std::clog << "========== Alpha_complex_from_empty_points ==========" << std::endl;

  // ----------------------------------------------------------------------------
  // Init of an empty list of points
  // ----------------------------------------------------------------------------
  std::vector<typename TestedKernel::Point_d> points;

  // ----------------------------------------------------------------------------
  // Init of an alpha complex from the list of points
  // ----------------------------------------------------------------------------
  Gudhi::alpha_complex::Alpha_complex<TestedKernel> alpha_complex_from_points(points);

  // Test to the limit
  BOOST_CHECK_THROW (alpha_complex_from_points.get_point(0), std::out_of_range);

  Gudhi::Simplex_tree<> simplex_tree;
  BOOST_CHECK(!alpha_complex_from_points.create_complex(simplex_tree));

  std::clog << "simplex_tree.num_simplices()=" << simplex_tree.num_simplices() << std::endl;
  BOOST_CHECK(simplex_tree.num_simplices() == 0);

  std::clog << "simplex_tree.dimension()=" << simplex_tree.dimension() << std::endl;
  BOOST_CHECK(simplex_tree.dimension() == -1);

  std::clog << "simplex_tree.num_vertices()=" << simplex_tree.num_vertices() << std::endl;
  BOOST_CHECK(simplex_tree.num_vertices() == points.size());
}

using Inexact_kernel_2 = CGAL::Epick_d< CGAL::Dimension_tag<2> >;
using Exact_kernel_2 = CGAL::Epeck_d< CGAL::Dimension_tag<2> >;
using list_of_kernel_2_variants = boost::mpl::list<Inexact_kernel_2, Exact_kernel_2>;

BOOST_AUTO_TEST_CASE_TEMPLATE(Alpha_complex_with_duplicated_points, TestedKernel, list_of_kernel_2_variants) {
  std::clog << "========== Alpha_complex_with_duplicated_points ==========" << std::endl;

  using Point = typename TestedKernel::Point_d;
  using Vector_of_points = std::vector<Point>;

  // ----------------------------------------------------------------------------
  // Init of a list of points
  // ----------------------------------------------------------------------------
  Vector_of_points points;
  points.push_back(Point(1.0, 1.0));
  points.push_back(Point(7.0, 0.0));
  points.push_back(Point(4.0, 6.0));
  points.push_back(Point(9.0, 6.0));
  points.push_back(Point(0.0, 14.0));
  points.push_back(Point(2.0, 19.0));
  points.push_back(Point(9.0, 17.0));
  // duplicated points
  points.push_back(Point(1.0, 1.0));
  points.push_back(Point(7.0, 0.0));

  // ----------------------------------------------------------------------------
  // Init of an alpha complex from the list of points
  // ----------------------------------------------------------------------------
  std::clog << "Init" << std::endl;
  Gudhi::alpha_complex::Alpha_complex<TestedKernel> alpha_complex_from_points(points);

  Gudhi::Simplex_tree<> simplex_tree;
  std::clog << "create_complex" << std::endl;
  BOOST_CHECK(alpha_complex_from_points.create_complex(simplex_tree));

  std::clog << "simplex_tree.num_vertices()=" << simplex_tree.num_vertices()
      << std::endl;
  BOOST_CHECK(simplex_tree.num_vertices() < points.size());
}


text:
// Copyright 2020 Jan Feitsma (Falcons)
// SPDX-License-Identifier: Apache-2.0
#include "ext/falconsCommonDirs.hpp"
#include "ext/falconsCommonEnv.hpp"
#include "ext/falconsCommonConfig.hpp"

#include <string>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>

std::string determineConfig(std::string key, std::string fileExtension)
{
    // determine config folder
    std::string cfgFolder = pathToConfig();
    // determine yaml file to load
    std::string target = key;
    if (isSimulatedEnvironment()) // simulator override?
    {
        std::string candidate = key + "Sim";
        std::string candidateFull = cfgFolder + "/" + candidate + fileExtension;
        if (boost::filesystem::exists(candidateFull))
        {
            target = candidate;
        }
        // test robot-specific
        candidate = key + "SimR" + boost::lexical_cast<std::string>(getRobotNumber());
        candidateFull = cfgFolder + "/" + candidate + fileExtension;
        if (boost::filesystem::exists(candidateFull))
        {
            target = candidate;
        }
    }
    else // not simulator
    {
        // test robot-specific
        std::string candidate = key + "R" + boost::lexical_cast<std::string>(getRobotNumber());
        std::string candidateFull = cfgFolder + "/" + candidate + fileExtension;
        if (boost::filesystem::exists(candidateFull))
        {
            target = candidate;
        }
    }
    // final check and return
    std::string result = cfgFolder + "/" + target + fileExtension;
    if (!boost::filesystem::exists(result))
    {
        printf("ERROR: could not resolve yaml file for %s\n", key.c_str());
    }
    else
    {
        printf("resolved yaml file %s -> %s\n", key.c_str(), result.c_str());
    }
    return result;
}

max_stars_repo_name: Falcons-Robocup/code

max_issues_repo_name: Falcons-Robocup/code

max_forks_repo_name: Falcons-Robocup/code


text:
// ----------------------------------------------------------------------------
//                              Apache License
//                        Version 2.0, January 2004
//                     http://www.apache.org/licenses/
//
// This file is part of binapi(https://github.com/niXman/binapi) project.
//
// Copyright (c) 2019-2021 niXman (github dot nixman dog pm.me). All rights reserved.
// ----------------------------------------------------------------------------

#include <binapi/pairslist.hpp>
#include <binapi/tools.hpp>
#include <binapi/types.hpp>

#include <boost/algorithm/string/predicate.hpp>

#include <cassert>

namespace binapi {

/*************************************************************************************************/

std::set<std::string> process_pairs(
     const std::string &whitelist
    ,const std::string &blacklist
    ,const binapi::rest::exchange_info_t &exinfo
) {
    std::set<std::string> res;

    assert(!whitelist.empty());

    if ( !whitelist.empty() ) {
        auto p = binapi::split_string(whitelist, ",");
        if ( p.size() == 1 && p.front() == "*" ) {
            for ( const auto &sit: exinfo.symbols ) {
                res.insert(sit.first);
            }
        } else {
            for ( auto &pit: p ) {
                if ( pit.front() == '*' ) { // *USDT
                    auto quoted = pit.substr(1);
                    for ( const auto &sit: exinfo.symbols ) {
                        if ( sit.second.quoteAsset == quoted ) {
                            res.insert(sit.first);
                        }
                    }
                } else if ( pit.back() == '*' ) { // BTC*
                    auto base = pit.substr(0, pit.length() - 1);
                    for ( const auto &sit: exinfo.symbols ) {
                        if ( sit.second.baseAsset == base ) {
                            res.insert(sit.first);
                        }
                    }
                } else {
                    assert(exinfo.symbols.count(pit));

                    res.insert(std::move(pit));
                }
            }
        }
    }

    // white list was applied, apply black list.
    if ( !res.empty() && !blacklist.empty() ) {
        auto p = binapi::split_string(blacklist, ",");
        if ( p.size() == 1 && p.front() == "*" ) {
            res.clear();
        } else {
            for ( auto &pit: p ) {
                if ( pit.front() == '*' ) { // *USDT
                    auto quoted = pit.substr(1);
                    for ( auto sit = res.begin(); sit != res.end(); ) {
                        if ( boost::algorithm::ends_with(*sit, quoted) ) {
                            sit = res.erase(sit);
                        } else {
                            ++sit;
                        }
                    }
                } else if ( pit.back() == '*' ) { // BTC*
                    auto base = pit.substr(0, pit.length() - 1);
                    for ( auto sit = res.begin(); sit != res.end();  ) {
                        if ( boost::algorithm::starts_with(*sit, base) ) {
                            sit = res.erase(sit);
                        } else {
                            ++sit;
                        }
                    }
                } else {
                    assert(exinfo.symbols.count(pit));

                    for ( auto sit = res.begin(); sit != res.end(); ) {
                        if ( pit == *sit ) {
                            sit = res.erase(sit);
                        } else {
                            ++sit;
                        }
                    }
                }
            }
        }

        // white list was not used - get pairs from
        // exchange and filter it using black list.
    } else if ( !blacklist.empty() ) {
        auto p = binapi::split_string(blacklist, ",");
        for ( auto &pit: p ) {
            if ( pit.front() == '*' ) { // *USDT
                auto quoted = pit.substr(1);
                for ( const auto &sit: exinfo.symbols ) {
                    if ( !boost::algorithm::ends_with(sit.first, quoted)) {
                        res.insert(sit.first);
                    }
                }
            } else if ( pit.back() == '*' ) { // BTC*
                auto base = pit.substr(0, pit.length() - 1);
                for ( const auto &sit: exinfo.symbols ) {
                    if ( !boost::algorithm::starts_with(sit.first, base)) {
                        res.insert(sit.first);
                    }
                }
            } else {
                for ( const auto &sit: exinfo.symbols ) {
                    if ( pit == sit.first ) continue;
                    res.insert(sit.first);
                }
            }
        }
    }

    return res;
}

/*************************************************************************************************/

bool pair_in_pairs(const std::set<std::string> &pairs, const std::string &pair) {
    return pairs.find(pair) != pairs.end();
}

/*************************************************************************************************/

void test_blackwhite_list() {
    struct pair_info {
        const char *pair;
        const char *base;
        const char *quote;
    };

#define __MAKE_PAIR(base, quoted) \
    {base quoted, base, quoted}

    static const pair_info pairs[] = {
         __MAKE_PAIR("ADA", "BNB")
        ,__MAKE_PAIR("ADA", "BTC")
        ,__MAKE_PAIR("BNB", "ADA")
        ,__MAKE_PAIR("BTC", "ADA")
    };

    binapi::rest::exchange_info_t exinfo{};
    for ( const auto &it: pairs ) {
        binapi::rest::exchange_info_t::symbol_t item{};
        item.symbol = it.pair;
        item.baseAsset = it.base;
        item.quoteAsset = it.quote;

        exinfo.symbols.emplace(it.pair, std::move(item));
    }

    auto list0 = process_pairs("*", "", exinfo);
    assert(
        list0.size() == 4 &&
        pair_in_pairs(list0, "ADABNB") &&
        pair_in_pairs(list0, "ADABTC") &&
        pair_in_pairs(list0, "BNBADA") &&
        pair_in_pairs(list0, "BTCADA")
    );

    auto list1 = process_pairs("ADA*", "", exinfo);
    assert(
        list1.size() == 2 &&
        pair_in_pairs(list1, "ADABNB") &&
        pair_in_pairs(list1, "ADABTC") &&
        !pair_in_pairs(list1, "BNBADA") &&
        !pair_in_pairs(list1, "BTCADA")
    );

    auto list2 = process_pairs("*ADA", "", exinfo);
    assert(
        list2.size() == 2 &&
        !pair_in_pairs(list2, "ADABNB") &&
        !pair_in_pairs(list2, "ADABTC") &&
        pair_in_pairs(list2, "BNBADA") &&
        pair_in_pairs(list2, "BTCADA")
    );

    auto list3 = process_pairs("BNBADA", "", exinfo);
    assert(
        list3.size() == 1 &&
        !pair_in_pairs(list3, "ADABNB") &&
        !pair_in_pairs(list3, "ADABTC") &&
        pair_in_pairs(list3, "BNBADA") &&
        !pair_in_pairs(list3, "BTCADA")
    );

    auto list4 = process_pairs("*", "*", exinfo);
    assert(list4.size() == 0);

    auto list5 = process_pairs("ADA*", "ADA*", exinfo);
    assert(list5.size() == 0);

    auto list6 = process_pairs("*ADA", "BNB*", exinfo);
    assert(
        list6.size() == 1 &&
        pair_in_pairs(list6, "BTCADA")
    );

    auto list7 = process_pairs("BNBADA", "BNBADA", exinfo);
    assert(list7.size() == 0);
}

/*************************************************************************************************/

} // ns binapi

max_stars_repo_name: ihsanturk/binapi

max_issues_repo_name: ihsanturk/binapi

max_forks_repo_name: ihsanturk/binapi


text:
/**
   @file launchfactory.cpp
   @brief This file is part of Kalinka mediaserver.
   @author Ivan Murashko <ivan.murashko@gmail.com>

   Copyright (c) 2007-2012 Kalinka Team

   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.

   CHANGE HISTORY

   @date
   - 2010/07/18 created by ipp (Ivan Murashko)
   - 2011/01/01 header was changed by header.py script
   - 2012/02/03 header was changed by header.py script
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <boost/assert.hpp>

#include "launchfactory.h"
#include "launchresources.h"
#include "launchmodfactory.h"
#include "launchmsgfactory.h"

using namespace klk;
using namespace klk::launcher;

//
// Factory class
//

klk::launcher::Factory* klk::launcher::Factory::m_instance = 0;

// Constructor
Factory::Factory(const std::string& appname, const std::string& module_id) :
    base::Factory(appname.c_str()), m_module_id(module_id),
    m_launcher(this, module_id)
{
}

// Destructor
Factory::~Factory()
{
}

// @return the factory instance
Factory* Factory::instance(const std::string& appname,
                           const std::string& module_id)
{
    if (m_instance == NULL)
    {
        m_instance = new Factory(appname, module_id);
    }
    return m_instance;
}

// @return the factory instance
Factory* Factory::instance()
{
    BOOST_ASSERT(m_instance);
    return m_instance;
}

/// Frees allocated resources
void Factory::destroy()
{
    KLKDELETE(m_instance);
}

// @copydoc klk::IFactory::getResources
IResources* Factory::getResources()
{
    Locker lock(&m_lock);
    if (m_resources == NULL)
    {
        // we should load configuration before
        // to access our settings stored at the db
        getConfig()->load();
        m_resources = new Resources(this);
    }
    return m_resources;
}

// Gets's module factory interface
// @return the module's factory
IModuleFactory* Factory::getModuleFactory()
{
    Locker lock(&m_lock);
    if (m_module_factory == NULL)
    {
        m_module_factory = new ModuleFactory(this);
    }
    return m_module_factory;
}

// Gets's message factory interface
// @return the message's factory
IMessageFactory* Factory::getMessageFactory()
{
    Locker lock(&m_lock);
    if (m_message_factory == NULL)
    {
        m_message_factory = new MessageFactory(this);
    }
    return m_message_factory;
}

max_stars_repo_name: ivanmurashko/kalinka

max_issues_repo_name: ivanmurashko/kalinka

max_forks_repo_name: ivanmurashko/kalinka


text:
#include <string>
#include <iostream>
#include <boost/parameter/name.hpp>
#include <boost/parameter/preprocessor.hpp>

using namespace std;

BOOST_PARAMETER_NAME(foo)
BOOST_PARAMETER_NAME(bar)
BOOST_PARAMETER_NAME(baz)
BOOST_PARAMETER_NAME(bonk)

BOOST_PARAMETER_FUNCTION(
    (int),  // the return type of the function, the parentheses are required.
    function_with_named_parameters, // the name of the function.
    tag,  // part of the deep magic. If you use BOOST_PARAMETER_NAME you need to put "tag" here.
    (required // names and types of all required parameters, parentheses are required.
     (foo, (int))
     (bar, (float))
    )
    (optional // names, types, and default values of all optional parameters.
     (baz, (bool) , false)
     (bonk, (std::string), "default value")
    )
    )
{
  if (baz && (bar > 1.0))
    cout << foo << endl;;
  cout << bonk.size() << endl;;
  return 0;
}

int main(void)
{
  function_with_named_parameters(1, 10.0);
  function_with_named_parameters(7, _bar = 3.14);
  function_with_named_parameters( _bar = 0.0, _foo = 42);
  function_with_named_parameters( _bar = 2.5, _bonk= "Hello", _foo = 9);
  function_with_named_parameters(9, 2.5, true, "Hello");
  return 0;
}


text:
/*
 * Copyright 2020 Robert Bosch GmbH
 *
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * \file      fable/environment.cpp
 * \see       fable/environment.hpp
 * \see       fable/environment_test.cpp
 */

#include <fable/environment.hpp>

#include <cstdlib>  // for getenv
#include <string>   // for string

#include <boost/optional.hpp>  // for optional<>

namespace fable {

namespace {

std::string slice(const std::string& s, size_t start, size_t end) {
  return s.substr(start, end - start);
}

std::string slice(const std::string& s, size_t start) { return s.substr(start); }

}  // anonymous namespace

boost::optional<std::string> Environment::get(const std::string& key, bool prefer_external) const {
  boost::optional<std::string> value;

  auto try_external = [&]() -> bool {
    char* s = std::getenv(key.c_str());
    if (s != nullptr) {
      value = std::string(s);
      return true;
    }
    return false;
  };

  auto try_internal = [&]() -> bool {
    if (defines_.count(key)) {
      value = defines_.at(key);
      return true;
    }
    return false;
  };

  if (prefer_external) {
    try_external() || try_internal();
  } else {
    try_internal() || try_external();
  }

  return value;
}

std::string Environment::require(const std::string& key, bool prefer_external) const {
  auto value = get(key, prefer_external);
  if (!value) {
    throw std::out_of_range("environment variable does not exist: " + key);
  }
  return *value;
}

std::string Environment::evaluate(const std::string& s, bool prefer_external,
                                  bool allow_undefined) const {
  size_t pos = s.find("-");
  std::string raw_key = (pos == std::string::npos ? s : slice(s, 0, pos));
  std::string key = interpolate(raw_key, prefer_external, allow_undefined);
  auto value = get(key, prefer_external);
  if (value) {
    return *value;
  } else if (pos != std::string::npos) {
    // The alternative will ONLY be processed if the initial key cannot be
    // found. This is not only good for avoiding work, it provides a kind of
    // shortcutting that allows alternatives to not be valid when the primary
    // key is available.
    return interpolate(slice(s, pos + 1), prefer_external, allow_undefined);
  } else if (allow_undefined) {
    return "";
  } else {
    if (raw_key == key) {
      throw std::out_of_range("environment variable does not exist: " + key);
    } else {
      throw std::out_of_range("nested environment variable does not exist: " + raw_key + " -> " +
                              key);
    }
  }
}

std::string Environment::interpolate(const std::string& s, bool prefer_external,
                                     bool allow_undefined) const {
  const size_t n = s.size();

  std::string output;
  size_t start = 0;
  size_t pos = 0;
  size_t depth = 0;
  while (pos != n) {
    switch (s[pos]) {
      case '$':
        if (pos + 1 == n) {
          throw std::invalid_argument("unterminated $ in string, expect one of $ or {");
        }
        switch (s[pos + 1]) {
          case '$':
            // Squash $$ into $ and write it to output.
            output += slice(s, start, pos);
            start = pos + 1;
            break;
          case '{':
            // Write text up until now to output and increase depth.
            if (depth == 0) {
              output += slice(s, start, pos);
              start = pos;
            }
            depth++;
            break;
          default:
            throw std::invalid_argument("unescaped $ in string, use $$ for a literal $");
        }
        pos++;
        break;
      case '}':
        if (depth > 0) {
          depth--;
          if (depth == 0) {
            auto token = slice(s, start + 2, pos);
            output += evaluate(token, prefer_external, allow_undefined);
            start = pos + 1;
          }
        }
        break;
      default:
        break;
    }
    pos++;
  }

  if (depth != 0) {
    throw std::invalid_argument("unterminated variable in string");
  }
  if (start != pos) {
    output += slice(s, start, pos);
  }
  return output;
}

}  // namespace fable

max_stars_repo_name: Sidharth-S-S/cloe

max_issues_repo_name: Sidharth-S-S/cloe

max_forks_repo_name: Sidharth-S-S/cloe


text:
// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <consensus/validation.h>
#include <key.h>
#include <validation.h>
#include <miner.h>
#include <pubkey.h>
#include <txmempool.h>
#include <random.h>
#include <script/standard.h>
#include <script/sign.h>
#include <test/test_bitcoin.h>
#include <util/time.h>
#include <core_io.h>
#include <keystore.h>
#include <policy/policy.h>

#include <boost/test/unit_test.hpp>

bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks);

BOOST_AUTO_TEST_SUITE(tx_validationcache_tests)

static bool
ToMemPool(const CMutableTransaction& tx)
{
    LOCK(cs_main);

    CValidationState state;
    return AcceptToMemoryPool(mempool, state, MakeTransactionRef(tx), nullptr /* pfMissingInputs */,
                              nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */);
}

// Run CheckInputs (using pcoinsTip) on the given transaction, for all script
// flags.  Test that CheckInputs passes for all flags that don't overlap with
// the failing_flags argument, but otherwise fails.
// CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY (and future NOP codes that may
// get reassigned) have an interaction with DISCOURAGE_UPGRADABLE_NOPS: if
// the script flags used contain DISCOURAGE_UPGRADABLE_NOPS but don't contain
// CHECKLOCKTIMEVERIFY (or CHECKSEQUENCEVERIFY), but the script does contain
// OP_CHECKLOCKTIMEVERIFY (or OP_CHECKSEQUENCEVERIFY), then script execution
// should fail.
// Capture this interaction with the upgraded_nop argument: set it when evaluating
// any script flag that is implemented as an upgraded NOP code.
static void ValidateCheckInputsForAllFlags(const CTransaction &tx, uint32_t failing_flags, bool add_to_cache) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
    PrecomputedTransactionData txdata(tx);
    // If we add many more flags, this loop can get too expensive, but we can
    // rewrite in the future to randomly pick a set of flags to evaluate.
    for (uint32_t test_flags=0; test_flags < (1U << 16); test_flags += 1) {
        CValidationState state;
        // Filter out incompatible flag choices
        if ((test_flags & SCRIPT_VERIFY_CLEANSTACK)) {
            // CLEANSTACK requires P2SH and WITNESS, see VerifyScript() in
            // script/interpreter.cpp
            test_flags |= SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS;
        }
        if ((test_flags & SCRIPT_VERIFY_WITNESS)) {
            // WITNESS requires P2SH
            test_flags |= SCRIPT_VERIFY_P2SH;
        }
        bool ret = CheckInputs(tx, state, pcoinsTip.get(), true, test_flags, true, add_to_cache, txdata, nullptr);
        // CheckInputs should succeed iff test_flags doesn't intersect with
        // failing_flags
        bool expected_return_value = !(test_flags & failing_flags);
        BOOST_CHECK_EQUAL(ret, expected_return_value);

        // Test the caching
        if (ret && add_to_cache) {
            // Check that we get a cache hit if the tx was valid
            std::vector<CScriptCheck> scriptchecks;
            BOOST_CHECK(CheckInputs(tx, state, pcoinsTip.get(), true, test_flags, true, add_to_cache, txdata, &scriptchecks));
            BOOST_CHECK(scriptchecks.empty());
        } else {
            // Check that we get script executions to check, if the transaction
            // was invalid, or we didn't add to cache.
            std::vector<CScriptCheck> scriptchecks;
            BOOST_CHECK(CheckInputs(tx, state, pcoinsTip.get(), true, test_flags, true, add_to_cache, txdata, &scriptchecks));
            BOOST_CHECK_EQUAL(scriptchecks.size(), tx.vin.size());
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: bitcoinnewyork/lava

max_issues_repo_name: bitcoinnewyork/lava

max_forks_repo_name: bitcoinnewyork/lava


text:
#pragma once

#include <cassert>
#include <chrono>
#include <cstddef>
#include <system_error>
#include <utility>
#include <boost/asio/ts/executor.hpp>
#include "pending_service.hpp"

namespace cppcon {
namespace test {

template<typename Executor,
         typename Clock = std::chrono::system_clock>
class waitable_timer {
private:
  using signature_type = void(std::error_code);
  using service_type = pending_service<signature_type>;
public:
  using executor_type = Executor;
  using clock_type = Clock;
  using duration = typename Clock::duration;
  using time_point = typename Clock::time_point;
  explicit waitable_timer(const executor_type& ex)
    : ex_     (ex),
      pending_(boost::asio::use_service<service_type>(ex.context()).acquire())
  {}
  ~waitable_timer() noexcept {
    boost::asio::use_service<service_type>(ex_.context()).release(pending_);
  }
  void complete(std::error_code ec = std::error_code()) {
    assert(pending());
    (*pending_)(ec);
  }
  template<typename CompletionToken>
  auto async_wait(CompletionToken&& token) {
    using async_completion_type = boost::asio::async_completion<CompletionToken,
                                                                signature_type>;
    async_completion_type completion(token);
    auto ex = boost::asio::get_associated_executor(completion.completion_handler,
                                                   get_executor());
    *pending_ = [g = boost::asio::make_work_guard(get_executor()),
                 g2 = boost::asio::make_work_guard(ex),
                 handler = std::move(completion.completion_handler)](std::error_code ec) mutable
                {
                  auto a = boost::asio::get_associated_allocator(handler);
                  auto ex = g2.get_executor();
                  auto f = [g = std::move(g),
                            g2 = std::move(g2),
                            handler = std::move(handler),
                            ec]() mutable
                           {
                             handler(ec);
                             g.reset();
                             g2.reset();
                           };
                  ex.post(std::move(f),
                          a);
                };
    return completion.result.get();
  }
  bool pending() const noexcept {
    return bool(*pending_);
  }
  std::size_t cancel() {
    if (!pending()) {
      return 0;
    }
    complete(make_error_code(std::errc::operation_canceled));
    return 1;
  }
  std::size_t expires_at(time_point when) {
    auto retr = cancel();
    when_ = when;
    return retr;
  }
  std::size_t expires_after(duration d) {
    return expires_at(Clock::now() + d);
  }
  time_point expiry() const noexcept {
    return when_;
  }
  auto get_executor() const noexcept {
    return ex_;
  }
private:
  executor_type         ex_;
  service_type::pointer pending_;
  time_point            when_;
};

}
}