text:
#include "normal.h"

#include <iostream>

#include <boost/optional.hpp>

#include "../parserUtility.h"
#include "../line.h"
#include "../enviroment.h"

#include "multiLineComment.h"
#include "objectDefined.h"
#include "boolean.h"
#include "branch.h"
#include "defineFunction.h"
#include "callFunction.h"
#include "send.h"
#include "arrayAccessor.h"
#include "passTo.h"

using namespace std;

namespace parser
{

IParseMode::Result parseMember(Enviroment& env, Line& line)
{
    auto[nestNames, p] = parseName(line, 0);
    if (nestNames.empty()) {
        AWESOME_THROW(SyntaxException) << "found invalid character.";
    }

    auto opType = parseOperator(p, line, p);
    if (OperatorType::Unknown == opType) {
        AWESOME_THROW(SyntaxException) << "found unknown operater.";
    }

    // parse value
    p = line.skipSpace(p);
    if (OperatorType::Is == opType) {
        env.pushScope(std::make_shared<NormalScope>(nestNames, Value().init(Value::Type::None)));
        auto valueLine = Line(line.get(p), 0, line.length() - p);
        parseValue(env, valueLine);

    } else if (OperatorType::Are == opType) {
        env.pushScope(std::make_shared<NormalScope>(nestNames, Value().init(Value::Type::Array)));
        p = parseArrayElement(env, line, p);

    } else if (OperatorType::Judge == opType || OperatorType::Deny == opType) {
        //skip member name and operator in the line so that BooleanParseMode does not parse them.
        line.resize(p, 0);
        env.pushScope(std::make_shared<BooleanScope>(nestNames, OperatorType::Deny == opType));
        env.pushMode(std::make_shared<BooleanParseMode>());
        auto pMode = env.currentMode();
        return pMode->parse(env, line);

    } else if (OperatorType::Copy == opType) {
        env.pushScope(std::make_shared<NormalScope>(nestNames, Value().init(Value::Type::None)));
        auto[srcNestNameView, endPos] = parseName(line, p);
        if (srcNestNameView.empty()) {
            AWESOME_THROW(SyntaxException)
                << "found invalid character in source variable.";
        }
        std::list<std::string> srcNestName = toStringList(srcNestNameView);
        Value const* pValue = env.searchValue(srcNestName, false);
        env.currentScope().value() = *pValue;

    } else if (OperatorType::Receive == opType) {
        env.pushScope(std::make_shared<ArrayAccessorScope>(nestNames));
        auto arrayAccessorLine = Line(line, line.skipSpace(p));
        env.pushMode(std::make_shared<ArrayAccessorParseMode>());
        return env.currentMode()->parse(env, arrayAccessorLine);
    } else if (OperatorType::PushBack == opType) {
        // push reference scope
        std::list<std::string> targetNestName = toStringList(nestNames);
        Value* pValue = env.searchValue(targetNestName, false);
        if (Value::Type::Array != pValue->type) {
            AWESOME_THROW(SyntaxException) << "An attempt was made to add with a value other than an array.";
        }
        env.pushScope(std::make_shared<ReferenceScope>(targetNestName, *pValue, false));

        // push value scope of anonymous
        env.pushScope(std::make_shared<NormalScope>(std::list<std::string>{""}, Value().init(Value::Type::None)));
        auto valueLine = Line(line.get(p), 0, line.length() - p);
        parseValue(env, valueLine);

    } else if (OperatorType::Remove == opType) {
        //TODO?

    } else if (OperatorType::DefineFunction == opType) {
        line.resize(p, 0);
        env.pushScope(std::make_shared<NormalScope>(nestNames, Value().init(Value::Type::Function)));
        env.pushMode(std::make_shared<DefineFunctionParseMode>());
        auto pMode = env.currentMode();
        return pMode->parse(env, line);

    } else if (OperatorType::Extend == opType) {
        auto objectNameLine = Line(line.get(p), 0, line.length() - p);
        auto[objectNestName, endPos] = parseObjectName(line, p);

        Value const* pTypeDefined = env.searchTypeObject(objectNestName);
        if (pTypeDefined->type != Value::Type::ObjectDefined) {
            AWESOME_THROW(SyntaxException)
                << "'" << toNameString(objectNestName) << "' must be ObjectDefined... type=" << Value::toString(pTypeDefined->type);
        }

        Value objDefiend;
        objDefiend = pTypeDefined->get<ObjectDefined>();
        env.pushScope(std::make_shared<NormalScope>(nestNames, std::move(objDefiend)));
        env.pushMode(std::make_shared<ObjectDefinedParseMode>());

    } else {
        AWESOME_THROW(SyntaxException) << "Unknown operator type...";
    }

    return IParseMode::Result::Continue;
}

IParseMode::Result parseStatement(Enviroment& env, Line& line)
{
    auto statementEnd = line.incrementPos(0, [](auto line, auto pos) {
        return !isSpace(line.get(pos));
    });
    auto statement = toStatementType(line.substr(0, statementEnd));
    switch (statement) {
    case Statement::If: [[fallthrough]];
    case Statement::Unless:
    {
        auto pos = line.skipSpace(statementEnd);
        bool isSuccess = false;
        auto [nestNameView, nameEnd] = parseName(line, pos, isSuccess);
        Value const* pValue = nullptr;
        if (isSuccess) {
            pValue = env.searchValue(toStringList(nestNameView), false);
        }
        env.pushScope(std::make_shared<BranchScope>(env.currentScope(), pValue, Statement::Unless == statement));
        env.pushMode(std::make_shared<BranchParseMode>());
        break;
    }
    case Statement::EmptyLine:
        return IParseMode::Result::NextLine;
    case Statement::Send:
        env.pushScope(std::make_shared<SendScope>(false));
        env.pushMode(std::make_shared<SendParseMode>());

        return env.currentMode()->parse(env, Line(line, line.skipSpace(statementEnd)));
    case Statement::PassTo:
        env.pushScope(std::make_shared<PassToScope>(env.currentScope()));
        env.pushMode(std::make_shared<PassToParseMode>());

        return env.currentMode()->parse(env, Line(line, line.skipSpace(statementEnd)));

    case Statement::Finish:
        env.pushScope(std::make_shared<SendScope>(true));
        env.pushMode(std::make_shared<SendParseMode>());

        return env.currentMode()->parse(env, Line(line, line.skipSpace(statementEnd)));

    default:
    {
        auto[nestNames, p] = parseName(line, 0);
        auto pFunc = env.searchValue(toStringList(nestNames), false, nullptr);
        if (!pFunc || pFunc->type != Value::Type::Function) {
            AWESOME_THROW(SyntaxException) << "Don't found function... name='" << toNameString(nestNames) << "'";
        }

        env.pushScope(std::make_shared<CallFunctionScope>(env.currentScope(), *pFunc));
        env.pushMode(std::make_shared<CallFunctionParseMode>());
        return env.currentMode()->parse(env, Line(line, line.skipSpace(p)));
        break;
    }
    }
    return IParseMode::Result::Continue;
}

IParseMode::Result NormalParseMode::parse(Enviroment& env, Line& line)
{
    line.resize(line.skipSpace(0), 0);
    if (Value::Type::Object == env.currentScope().valueType()) {
        if (':' == *line.get(0)) {
            auto statementLine = line;
            statementLine.resize(1, 0);
            return parseStatement(env, statementLine);
        } else {
            return parseMember(env, line);
        }

    } else if (Value::Type::Array == env.currentScope().valueType()) {
        auto p = parseArrayElement(env, line, 0);

    } else if (Value::Type::String == env.currentScope().valueType()) {
        env.currentScope().value().appendStr(line.string_view());

    } else if (Value::Type::Number == env.currentScope().valueType()) {
        // Convert Number to String when scope is multiple line.
        auto str = Value().init(Value::Type::String);
        str = std::to_string(env.currentScope().value().get<Value::number>());
        env.currentScope().value() = str;

    } else {
        AWESOME_THROW(FatalException) << "unimplement...";
    }
    return Result::Continue;
}

}

max_stars_repo_name: tositeru/watagashi

max_issues_repo_name: tositeru/watagashi

max_forks_repo_name: tositeru/watagashi


text:
/*!
 * @file
 * Defines `react::computation::requiring`.
 */

#ifndef REACT_COMPUTATION_REQUIRING_HPP
#define REACT_COMPUTATION_REQUIRING_HPP

#include <react/computation/noop.hpp>
#include <react/detail/flatten_into_set.hpp>

#include <boost/mpl/vector.hpp>

namespace react { namespace computation {
    /*!
     * Computation implemented as a `noop` requiring other features.
     *
     * @tparam Requirements...
     *         A sequence of `Feature`s required by this computation. Any
     *         Boost.MPL `Sequence` encountered in `Requirements...` is
     *         flattened as-if its content was part of `Requirements...`.
     */
    template <typename ...Requirements>
    struct requiring : noop {
        using requirements = typename detail::flatten_into_set<
            typename boost::mpl::vector<Requirements...>::type
        >::type;
    };
}} // end namespace react::computation

#endif // !REACT_COMPUTATION_REQUIRING_HPP

ext: hpp

max_stars_repo_name: ldionne/react

max_issues_repo_name: ldionne/react

max_forks_repo_name: ldionne/react


text:
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_simple_class.cpp

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// 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)

// should pass compilation and execution

// invoke header for a custom archive test.

#include <boost/math/special_functions/next.hpp>
#include <boost/test/unit_test.hpp>
#include <cmath>
#include <cstddef> // NULL

#include "A.hpp"
#include "A.ipp"
#include "io_fixture.hpp"

BOOST_FIXTURE_TEST_CASE(simple_class, io_fixture)
{
    for (std::size_t i = 0; i < get_string_sample_count(); ++i)
    {
        for (std::size_t j = 0; j < get_wstring_sample_count(); ++j)
        {
            A a, another_a;
            a.y = get_string_sample(i);
#ifndef BOOST_NO_STD_WSTRING
            a.z = get_wstring_sample(j);
#endif
            const auto filename = get_filename() + "_" + std::to_string(i) +
                                  "_" + std::to_string(j) +
                                  ARCHIVE_FILENAME_EXTENSION;
            {
                test_ostream  os(filename.c_str(), STREAM_FLAGS);
                test_oarchive oa(os, ARCHIVE_FLAGS);
                oa << BOOST_SERIALIZATION_NVP(a);
            }
            {
                test_istream  is(filename.c_str(), STREAM_FLAGS);
                test_iarchive ia(is, ARCHIVE_FLAGS);
                ia >> boost::serialization::make_nvp("a", another_a);
            }
            BOOST_CHECK_EQUAL(a, another_a);
        }
    }
}

ext: cpp

max_stars_repo_name: rwols/yaml-archive

max_issues_repo_name: rwols/yaml-archive

max_forks_repo_name: rwols/yaml-archive


text:
/* training_index.cc
   Jeremy Barnes, 18 February 2005
   Copyright (c) 2005 Jeremy Barnes.  All rights reserved.
   $Source$

   Implementation of training data indexes.
*/

#include "training_index.h"
#include "training_index_entry.h"
#include "feature_map.h"
#include "feature_space.h"
#include "training_data.h"
#include "jml/utils/sgi_numeric.h"
#include "jml/utils/vector_utils.h"
#include <boost/timer.hpp>
#include "jml/utils/string_functions.h"
#include "jml/arch/demangle.h"
#include <set>

using namespace std;

namespace ML {

/*****************************************************************************/
/* DATASET_INDEX                                                             */
/*****************************************************************************/

struct Dataset_Index::Itl {
    typedef Feature_Map<Index_Entry> index_type;
    index_type index;
    std::shared_ptr<const Feature_Space> feature_space;
    std::vector<Feature> all_features;
};

void
Dataset_Index::
init(const Training_Data & data,
     const std::vector<Feature> & features_)
{
    //boost::timer t;

    itl.reset(new Itl());
    itl->feature_space = data.feature_space();

    size_t nx = data.example_count();
    bool sparse = (data.feature_space()->type() == SPARSE);

    //cerr << "sparse = " << sparse << endl;

    /* Iterate through the data and index it one by one. */

    vector<Index_Entry *> entries;
    vector<Feature> features;

    std::set<Feature> keep_features(features_.begin(), features_.end());

    for (unsigned x = 0;  x < nx;  ++x) {
        //cerr << "x = " << x << " of " << nx << endl;
        const Feature_Set & fs = data[x];
        if (x == 0) {
            for (Feature_Set::const_iterator it = fs.begin();
                 it != fs.end();  ++it) {
                const Feature & feat = it.feature();

                itl->index[feat].used = keep_features.empty() || keep_features.count(feat);
                itl->index[feat].feature = feat;
                itl->index[feat].feature_space = itl->feature_space;
                itl->index[feat].initialized = true;
                features.push_back(feat);
                entries.push_back(&itl->index[feat]);
            }
        }

        //std::set<Feature> doneFeatures;

        int i = 0;
        for (Feature_Set::const_iterator it = fs.begin();
             it != fs.end();  ++it, ++i) {
            const Feature & feat = it.feature();
            float val = it.value();

#if 0 // debugging sort() problem
            if (doneFeatures.count(feat)) {
                //sleep(1);

                std::set<Feature> doneFeatures2;
                for (Feature_Set::const_iterator it = fs.begin();
                     it != fs.end();  ++it) {
                    const Feature & feat = it.feature();
                    if (doneFeatures2.count(feat))
                        throw Exception("doubled up twice on feature " + itl->feature_space->print(feat)
                                        + " on " + type_name(fs));  // debug
                    doneFeatures2.insert(feat);
                }

                throw Exception("doubled up temporarily feature " + itl->feature_space->print(feat)
                                + " on " + type_name(fs));  // debug
            }
            doneFeatures.insert(feat);
#endif

            /* Save a map lookup for the common case of always the same
               features or always the same ones at the start. */
            if (i < features.size() && features[i] == feat) {
                if (entries[i]->used)
                    entries[i]->insert(val, x, nx, sparse, fs);
            }
            else {
                Index_Entry & entry = itl->index[feat];
                if (!entry.initialized) {
                    entry.initialized = true;
                    entry.used = (keep_features.empty() || keep_features.count(feat));
                    entry.feature = feat;
                    entry.feature_space = itl->feature_space;
                }
                if (entry.used)
                    entry.insert(val, x, nx, sparse, fs);
            }
        }
    }

    itl->all_features.clear();
    itl->all_features.reserve(itl->index.size());

    /* Finalize the data structures. */
    for (Itl::index_type::iterator it = itl->index.begin();
         it != itl->index.end();  ++it) {
        Feature feature = it.key();
        itl->all_features.push_back(feature);
        if (!it->used) continue;

        //cerr << "finalizing feature " << itl->feature_space->print(feature)
        //     << endl;

        it->finalize(data.example_count(), feature, itl->feature_space);

        //cerr << "  " << it->print_info() << endl;
        //cerr << "  examples = " << it->examples.size() << endl;
        //cerr << "  values   = " << it->values.size() << endl;
    }

    std::sort(itl->all_features.begin(), itl->all_features.end());

    //cerr << "finalize features: " << t.elapsed() << "s" << endl;

    //cerr << "Dataset_Index::init(): " << format("%6.2fs", t.elapsed()) << endl;
}

void
Dataset_Index::
init(const Training_Data & data,
     const Feature & label,
     const std::vector<Feature> & features)
{
    vector<Feature> features2 = features;
    if (std::find(features.begin(), features.end(), label) == features.end())
        features2.push_back(label);
    init(data, features2);

    // Generate labels
    itl->index[label].get_labels();
}

const std::vector<Feature> & Dataset_Index::all_features() const
{
    return itl->all_features;
}

const Dataset_Index::Freqs &
Dataset_Index::freqs(const Feature & feature) const
{
    return itl->index[feature].get_freqs();
}

const Dataset_Index::Category_Freqs &
Dataset_Index::category_freqs(const Feature & feature) const
{
    size_t num_categories
        = itl->feature_space->info(feature).value_count();
    return itl->index[feature].get_category_freqs(num_categories);
}

const std::vector<Label> &
Dataset_Index::labels(const Feature & feature) const
{
    return itl->index[feature].get_labels();
}

const std::vector<float> &
Dataset_Index::values(const Feature & feature) const
{
    return itl->index[feature].get_values(BY_EXAMPLE);
}

Joint_Index
Dataset_Index::
joint(const Feature & target, const Feature & independent,
      Sort_By sort_by, unsigned contents, size_t num_buckets) const
{
    /* Normally if you have done this, you are trying to predict a label
       using itself, which is an error.
    */
    if (target == independent)
        throw Exception("Dataset_Index::joint(): distribution between "
                        "a feature and itself requested; use dist() if "
                        "this is really what you mean");

    bool want_buckets = (num_buckets > 0);
    bool want_labels = true;
    bool want_counts = true;
    bool want_examples = true;
    bool want_divisors = true;
    bool want_values = true;

    /* Labels are joint between two distributions. */
    const Label * labels = 0;
    const uint16_t * buckets = 0;
    const vector<float> * bucket_splits = 0;
    const unsigned * counts = 0;
    const unsigned * examples = 0;
    const float * divisors = 0;
    const float * values = 0;

    if (itl->index[independent].seen == 0) // unknown feature...
        return Joint_Index(values, buckets, labels, examples, counts, divisors,
                           0, bucket_splits);

    if (want_labels) {
        const vector<Label> & example_labels
            = itl->index[target].get_labels();
        //cerr << "example_labels = " << example_labels << endl;
        const vector<Label> & mapped_labels
            = itl->index[independent].get_mapped_labels(example_labels, target,
                                                        sort_by);
        //cerr << "mapped_labels = " << mapped_labels << endl;
        labels = &mapped_labels[0];
    }

    if (want_buckets) {
        const Bucket_Info & bucket_info
            = itl->index[independent].buckets(num_buckets);
        buckets = &bucket_info.buckets[0];
        bucket_splits = &bucket_info.splits;
    }

    if (want_counts) {
        const vector<unsigned> & counts_vector
            = itl->index[independent].get_counts(sort_by);
        if (!counts_vector.empty())
            counts = &counts_vector[0];
    }

    if (want_divisors) {
        const vector<float> & divisors_vector
            = itl->index[independent].get_divisors(sort_by);
        if (!divisors_vector.empty())
            divisors = &divisors_vector[0];
    }

    if (want_examples) {
        const vector<unsigned> & examples_vector
            = itl->index[independent].get_examples(sort_by);
        if (!examples_vector.empty())
            examples = &examples_vector[0];
    }

    if (want_values) {
        const vector<float> & values_vector
            = itl->index[independent].get_values(sort_by);
        values = &values_vector[0];
    }

    Joint_Index result(values, buckets, labels, examples, counts, divisors,
                       itl->index[independent].seen, bucket_splits);

#if 0
    if (itl->index[independent].found_twice > 0
        && itl->feature_space->print(independent) == "lemma-try") {
        cerr << "got joint distribution for feature "
             << itl->feature_space->print(independent) << endl;
        Index_Iterator it(&result, 0), end(&result, result.size());

        int i = 0;
        cerr << "  num    value m bckt labl exmp exct o div\n";
        while (it != end) {
            cerr << format("%5d %8g %1d %4d %4d %4d %4d %1d %4.2f\n",
                           i++, it->value(), it->missing(),
                           0/*it->bucket()*/,
                           it->label().operator int(),
                           it->example(), it->example_counts(),
                           it->one_example(), it->divisor());
            ++it;
        }
        cerr << endl;
    }
#endif

    return result;
}

Joint_Index
Dataset_Index::
dist(const Feature & feature, Sort_By sort_by, unsigned content,
     size_t num_buckets) const
{
    bool want_buckets = (num_buckets > 0);
    bool want_counts = true;
    bool want_divisors = true;
    bool want_examples = true;
    bool want_values = true;

    /* Labels are joint between two distributions. */
    const Label * labels = 0;
    const uint16_t * buckets = 0;
    const vector<float> * bucket_splits = 0;
    const unsigned * counts = 0;
    const float * divisors = 0;
    const unsigned * examples = 0;
    const float * values = 0;

    if (itl->index[feature].seen == 0) // unknown feature...
        return Joint_Index(values, buckets, labels, examples, counts, divisors,
                           0, bucket_splits);
    if (want_buckets) {
        const Bucket_Info & bucket_info
            = itl->index[feature].buckets(num_buckets);
        buckets = &bucket_info.buckets[0];
        bucket_splits = &bucket_info.splits;
    }

    if (want_counts) {
        const vector<unsigned> & counts_vector
            = itl->index[feature].get_counts(sort_by);
        if (!counts_vector.empty())
            counts = &counts_vector[0];
    }

    if (want_divisors) {
        const vector<float> & divisors_vector
            = itl->index[feature].get_divisors(sort_by);
        if (!divisors_vector.empty())
            divisors = &divisors_vector[0];
    }

    if (want_examples) {
        const vector<unsigned> & examples_vector
            = itl->index[feature].get_examples(sort_by);
        if (!examples_vector.empty())
            examples = &examples_vector[0];
    }

    if (want_values) {
        const vector<float> & values_vector
            = itl->index[feature].get_values(sort_by);
        values = &values_vector[0];
    }

    return Joint_Index(values, buckets, labels, examples, counts, divisors,
                       itl->index[feature].seen, bucket_splits);
}

double Dataset_Index::density(const Feature & feat) const
{
    return itl->index[feat].density();
}

bool Dataset_Index::exactly_one(const Feature & feat) const
{
    return itl->index[feat].exactly_one();
}

bool Dataset_Index::dense(const Feature & feat) const
{
    return itl->index[feat].dense();
}

bool Dataset_Index::only_one(const Feature & feat) const
{
    return itl->index[feat].only_one();
}

size_t Dataset_Index::count(const Feature & feat) const
{
    return itl->index[feat].seen;
}

std::pair<float, float> Dataset_Index::range(const Feature & feature) const
{
    return make_pair(itl->index[feature].min_value,
                     itl->index[feature].max_value);
}

bool Dataset_Index::constant(const Feature & feat) const
{
    std::pair<float, float> r = range(feat);
    return r.first == r.second;
}

bool Dataset_Index::integral(const Feature & feature) const
{
    return itl->index[feature].non_integral == 0;
}

Feature_Info Dataset_Index::
guess_info(const Feature & feat) const
{
    /* Algorithm: if there is just 1 and 0 values, we say it's boolean.
       If there is just a 1 value or missing, we say it's a presence
       feature.  If none are missing and all values are the same, we
       say it's inutile.  Otherwise, we say that it's real. */
    //return Feature_Info(PRESENCE);

    const Index_Entry & entry = itl->index[feat];

    string name = itl->feature_space->print(feat);
    bool debug = false;//(name == "AVG_FILLED_IN_CONF");

    if (debug) cerr << "guess_info for " << name << endl;
    if (debug) cerr << "entry: " << entry.print_info() << endl;

    Mutable_Feature_Info result;
    if (entry.seen == 0)
        result.set_type(INUTILE);
    else {
        bool dense = entry.dense();
        bool boolean = (entry.ones + entry.zeros == entry.seen);
        bool uniform_one = (entry.ones == entry.seen);
        bool one_example = (entry.exactly_one());
        bool one_value = (entry.max_value == entry.min_value);
        //bool all_integral = (entry.non_integral == 0);

        if (debug) {
            cerr << "feature " << name << ": "
                 << dense << " " << boolean << " " << uniform_one
                 << " " << one_example << " " << one_value << endl;
        }

        /* Uniformly the same value and none missing? */
        if (dense && one_example && one_value)
            result.set_type(INUTILE);
        else if (one_value && uniform_one) result.set_type(PRESENCE);
        else if (boolean) result.set_type(BOOLEAN);
        else if (itl->feature_space->info(feat).type()
                     == CATEGORICAL
                 || itl->feature_space->info(feat).type()
                     == STRING)
            result = itl->feature_space->info(feat);
#if 0
        else if (all_integral
                 && entry.min_value >= 0 && entry.max_value <= 255) {
            result.type = CATEGORICAL;
            result.categorical.reset
                (new Fixed_Categorical_Info((int)entry.max_value + 1));
            // TODO: detect categorical (?)
        }
#endif
        else result.set_type(REAL);
    }

    if (debug)
        cerr << "result is " << result << endl;

    if (debug) cerr << "result now " << result << endl;

    return result;
}

Feature_Info Dataset_Index::
guess_info_categorical(const Feature & feat) const
{
    const Index_Entry & entry = itl->index[feat];

    Mutable_Feature_Info result;
    if (entry.seen == 0)
        result.set_type(INUTILE);
    else {
        bool dense = entry.dense();
        bool boolean = (entry.ones + entry.zeros == entry.seen);
        bool uniform_one = (entry.ones == entry.seen);
        bool one_example = (entry.exactly_one());
        bool one_value = (entry.max_value == entry.min_value);
        bool all_integral = (entry.non_integral == 0);

        /* Uniformly the same value and none missing? */
        if (dense && one_example && one_value)
            result.set_type(INUTILE);
        else if (one_value && uniform_one)
            result.set_type(PRESENCE);
        else if (boolean) result.set_type(BOOLEAN);
        else if (itl->feature_space->info(feat).type()
                     == CATEGORICAL
                 || itl->feature_space->info(feat).type()
                     == STRING)
            result = itl->feature_space->info(feat);
        else if (all_integral && entry.min_value >= 0
                 && entry.max_value <= 255) {
            result.set_type(CATEGORICAL);
            result.set_categorical
                (new Mutable_Categorical_Info((int)entry.max_value + 1));
        }
        else result.set_type(REAL);
    }

    return result;
}

} // namespace ML

ext: cc

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: TuanTranEngineer/rtbkit

max_forks_repo_name: TuanTranEngineer/rtbkit


text:
#pragma once

#include <memory>
#include <stack>
#include <unordered_map>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/random_device.hpp>
#include <SFML/Graphics.hpp>
#include "GameLogic/HighScores.hpp"
#include "GameLogic/Options.hpp"
#include "GameLogic/SaveManager.hpp"
#include "HelperSrc/GameConstants.hpp"

class GameState;

class Game {
  public:
    // Konstruktor:
    Game();
    // Destruktor:
    ~Game();
    // Usunięte metody domyślne:
    Game( const Game &other ) = delete;
    Game &operator=( Game other ) = delete;
    // Obsługa stosu stanów:
    void pushState( std::unique_ptr< GameState > state );
    void popState();
    void changeState( std::unique_ptr< GameState > state );
    GameState *topState() const;
    // Uruchomienie i zakończenie gry:
    void run();
    void exit();
    // Składowe publiczne:
    boost::random::mt19937 mRandomGenerator;
    HighScores mHighScores;
    Options mOptions;
    SaveManager mSaveManager;
    sf::Font mFont;
    sf::VideoMode mVideoMode;
    sf::RenderWindow mWindow;
    std::unordered_map< unsigned, sf::Texture > mClassicAndHexTextures;
    std::unordered_map< unsigned, sf::Texture > mTriTextures;
    std::unordered_map< unsigned, sf::Texture > mReversedTriTextures;
    unsigned mBaseCharacterSize;
    float mBaseDistanceBetweenTextGraphics;
  protected:
    // Pomocnicze metody chronione:
    boost::random::mt19937 createTrueRandomSeededGenerator();
    void loadTexturesFromFile( const std::string &filepath,
                               std::unordered_map< unsigned, sf::Texture > &texturesContainer,
                               const unsigned texturesCount );
    void loadAllTexturesFromFiles();
    void loadDataFromFiles();
    void createWindow( sf::RenderWindow &window );
    // Składowe chronione:
    std::stack< std::unique_ptr< GameState > > mStates;
};


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

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "util/fingerprint.hpp"
#include "util/exception.hpp"
#include "util/exception_utils.hpp"
#include "util/version.hpp"

#include <boost/assert.hpp>
#include <boost/crc.hpp>

#include <cstring>

#include <algorithm>
#include <string>

namespace osrm
{
namespace util
{

/**
 * Constructs a valid fingerprint for the current (running) version of OSRM.
 * This can be compared to one read from a file to determine whether the
 * current code is compatible with the file being read.
 */
FingerPrint FingerPrint::GetValid()
{
    FingerPrint fingerprint;

    // 4 chars, 'O','S','R','N' - note the N instead of M, v1 of the fingerprint
    // used M, so we add one and use N to indicate the newer fingerprint magic number.
    // Bump this value if the fingerprint format ever changes.
    fingerprint.magic_number = {{'O', 'S', 'R', 'N'}};
    fingerprint.major_version = OSRM_VERSION_MAJOR;
    fingerprint.minor_version = OSRM_VERSION_MINOR;
    fingerprint.patch_version = OSRM_VERSION_PATCH;
    fingerprint.checksum = fingerprint.CalculateChecksum();

    return fingerprint;
}

int FingerPrint::GetMajorVersion() const { return major_version; }
int FingerPrint::GetMinorVersion() const { return minor_version; }
int FingerPrint::GetPatchVersion() const { return patch_version; }

/**
 * Calculates the CRC8 of the FingerPrint struct, using all bytes except the
 * final `checksum` field, which should be last in the struct (this function
 * checks that it is)
 */
std::uint8_t FingerPrint::CalculateChecksum() const
{
    // Verify that the checksum is a single byte (because we're returning an 8 bit checksum)
    // This assumes that a byte == 8 bits, which is mostly true these days unless you're doing
    // something really weird
    static_assert(sizeof(checksum) == 1, "Checksum needs to be a single byte");
    const constexpr int CRC_BITS = 8;

    // This constant comes from
    // https://en.wikipedia.org/wiki/Polynomial_representations_of_cyclic_redundancy_checks
    // CRC-8-CCITT normal polynomial value.
    const constexpr int CRC_POLYNOMIAL = 0x07;
    boost::crc_optimal<CRC_BITS, CRC_POLYNOMIAL> crc8;

    // Verify that the checksum is the last field, because we're going to CRC all the bytes
    // leading up to it
    static_assert(offsetof(FingerPrint, checksum) == sizeof(FingerPrint) - sizeof(checksum),
                  "Checksum must be the final field in the Fingerprint struct");

    // Calculate checksum of all bytes except the checksum byte, which is at the end.
    crc8.process_bytes(this, sizeof(FingerPrint) - sizeof(checksum));

    return crc8.checksum();
}

/**
 * Verifies that the fingerprint has the expected magic number, and the checksum is correct.
 */
bool FingerPrint::IsValid() const
{
    // Note: == on std::array compares contents, which is what we want here.
    return magic_number == GetValid().magic_number && checksum == CalculateChecksum();
}

/**
 * Determines whether two fingerprints are data compatible.
 * Our compatibility rules say that we maintain data compatibility for all PATCH versions.
 * A difference in either the MAJOR or MINOR version fields means the data is considered
 * incompatible.
 */
bool FingerPrint::IsDataCompatible(const FingerPrint &other) const
{
    return IsValid() && other.major_version == major_version &&
           other.minor_version == minor_version;
}
}
}

max_stars_repo_name: asaveljevs/osrm-backend

max_issues_repo_name: serarca/osrm-backend

max_forks_repo_name: serarca/osrm-backend


text:
#pragma once

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

namespace cuttle {
	namespace fileui {
		class file_not_found_error : public std::runtime_error {
		public:
            explicit file_not_found_error(const boost::filesystem::path &path)
					: runtime_error("File '" + path.string() + "' was not found") {}
		};
	}
}

max_stars_repo_name: cuttle-system/cuttle-fileui

max_issues_repo_name: cuttle-system/cuttle-fileui

max_forks_repo_name: cuttle-system/cuttle-fileui


text:
#pragma once
#include <deip/protocol/asset.hpp>

#include "deip_object_types.hpp"

#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/hashed_index.hpp>

#include <numeric>

namespace deip{
namespace chain{

using deip::protocol::asset;

class reward_pool_object : public object<reward_pool_object_type, reward_pool_object>
{

    reward_pool_object() = delete;

public:

    template <typename Constructor, typename Allocator>
    reward_pool_object(Constructor &&c, allocator<Allocator> a)
    {
        c(*this);
    }

    reward_pool_id_type id;
    research_content_id_type research_content_id;
    discipline_id_type discipline_id;

    asset balance = asset(0, DEIP_SYMBOL);
    share_type expertise;
};

struct by_research_content;
struct by_content_and_discipline;

typedef multi_index_container<reward_pool_object,
                indexed_by<ordered_unique<tag<by_id>,
                            member<reward_pool_object,
                                    reward_pool_id_type,
                                    &reward_pool_object::id>>,
                           ordered_non_unique<tag<by_research_content>,
                            member<reward_pool_object,
                                    research_content_id_type,
                                    &reward_pool_object::research_content_id>>,
                           ordered_unique<tag<by_content_and_discipline>,
                           composite_key<reward_pool_object,
                                  member<reward_pool_object,
                                   research_content_id_type,
                                    &reward_pool_object::research_content_id>,
                                  member<reward_pool_object,
                                          discipline_id_type,
                                    &reward_pool_object::discipline_id>>>>,
        allocator<reward_pool_object>>
        reward_pool_index;
}
}

FC_REFLECT(deip::chain::reward_pool_object,
                        (id)(research_content_id)(discipline_id)(balance)(expertise)
            )

CHAINBASE_SET_INDEX_TYPE(deip::chain::reward_pool_object, deip::chain::reward_pool_index)

max_stars_repo_name: DEIPworld/deip-chain

max_issues_repo_name: DEIPworld/deip-chain

max_forks_repo_name: DEIPworld/deip-chain


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

#include "dbmanager.h"
#include <boost/test/unit_test.hpp>
#include <fstream>

struct DbCleanupFixture
{
    DbCleanupFixture()
        : fileName("dbtest.dat")
    {
    }
    void RemoveFile() const
    {
        boost::filesystem::remove(GetDataDir() / fileName);
    }
    std::string fileName;
};

// Test class which has minimal required functions to use Load and Dump
struct DbTest
{
    DbTest()
        : m_testData(15)
        , m_checkedAndRemoved(false)
        , m_cleared(false)
    {
    }

    ADD_SERIALIZE_METHODS;
    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        READWRITE(m_testData);
    }
    void Clear()
    {
        m_cleared = true;
    }
    void CheckAndRemove()
    {
        m_checkedAndRemoved = true;
    }
    std::string ToString() const
    {
        return "DbTest";
    }
    bool operator == (const DbTest& dbTest)
    {
        return dbTest.m_testData == this->m_testData;
    }

    int m_testData;
    bool m_checkedAndRemoved;
    bool m_cleared;
};

// An exception is thrown during serialization to test 'IncorrectFormat' error
struct DbTestWithSerializeException : public DbTest
{
    ADD_SERIALIZE_METHODS;
    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
    {
        throw std::runtime_error("Error");
    }
};

BOOST_FIXTURE_TEST_SUITE(db_tests, DbCleanupFixture)

    BOOST_AUTO_TEST_CASE(FileError)
    {
        // File doesn't exist
        DbTest db;
        ::details::ReadResult readResult = ::details::Read(db, fileName, "MagicMessage");
        BOOST_CHECK_EQUAL(readResult, ::details::FileError);
    }

    BOOST_AUTO_TEST_CASE(HashReadError)
    {
        DbTest db;

        // Create an empty file
        std::fstream fs;
        fs.open((GetDataDir() / fileName).string().c_str(), std::ios::out);
        fs.close();

        ::details::ReadResult readResult = ::details::Read(db, fileName, "MagicMessage");
        BOOST_CHECK_EQUAL(readResult, ::details::HashReadError);
        RemoveFile();
    }

    BOOST_AUTO_TEST_CASE(IncorrectMagicMessage)
    {
        DbTest db;
        Dump(db, fileName, "MagicMessage");

        // Try to read data with incorrect magic message
        ::details::ReadResult readResult = ::details::Read(db, fileName, "IncorrectMagicMessage");
        BOOST_CHECK_EQUAL(readResult, ::details::IncorrectMagicMessage);
        RemoveFile();
    }

    BOOST_AUTO_TEST_CASE(IncorrectMagicNumber)
    {
        DbTest db;
        Dump(db, fileName, "MagicMessage");
        const CBaseChainParams::Network prevParams = Params().NetworkID();
        // Change network params for magic number to be different
        SelectParams(CBaseChainParams::REGTEST);
        ::details::ReadResult readResult = ::details::Read(db, fileName, "MagicMessage");
        BOOST_CHECK_EQUAL(readResult, ::details::IncorrectMagicNumber);

        // Revert back network params
        SelectParams(prevParams);
        RemoveFile();
    }

    BOOST_AUTO_TEST_CASE(IncorrectFormat)
    {
        DbTest db;
        Dump(db, fileName, "MagicMessage");

        DbTestWithSerializeException dbWithException;
        ::details::ReadResult readResult = ::details::Read(dbWithException, fileName, "MagicMessage");
        BOOST_CHECK_EQUAL(readResult, ::details::IncorrectFormat);
        BOOST_CHECK(dbWithException.m_cleared);
        RemoveFile();
    }

    BOOST_AUTO_TEST_CASE(DbDumpAndLoad)
    {
        DbTest dbDump;
        BOOST_CHECK(Dump(dbDump, fileName, "MagicMessage"));

        DbTest dbLoad;
        BOOST_CHECK(Load(dbLoad, fileName, "MagicMessage"));

        BOOST_CHECK(dbDump == dbLoad);
        BOOST_CHECK(dbLoad.m_checkedAndRemoved);
        RemoveFile();
    }

BOOST_AUTO_TEST_SUITE_END()


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE netwhere_test
#include <boost/test/unit_test.hpp>

#include "object_set.hpp"

using namespace std;

class TestObject {
public:
  TestObject(int key) : _key(key) {
	instances++;
  }
  ~TestObject() {
	instances--;
  }

  int key() { return _key; }

  static void reset() { instances = 0; }
  static int get_instances() { return instances; }

private:
  static int instances;
  int _key;
};

int TestObject::instances = 0;

BOOST_AUTO_TEST_CASE( auto_dynamic_map_insert ) {
  ObjectSet<int, TestObject> map;

  auto value1 = map.insert(1);
  BOOST_CHECK_EQUAL(value1.second, true);

  auto value2 = map.insert(1);
  BOOST_CHECK_EQUAL(value2.second, false);
  BOOST_CHECK_EQUAL(value2.first->key(), 1);

  BOOST_CHECK(value1.first == value2.first);
}

BOOST_AUTO_TEST_CASE( auto_dynamic_map_destructor ) {
  TestObject::reset();
  {
    ObjectSet<int, TestObject> map;

    map.insert(1);
  }

  BOOST_CHECK_EQUAL(TestObject::get_instances(), 0);

  TestObject::reset();
  {
    ObjectSet<int, TestObject> map;

    map.insert(1);
	map.insert(2);
	map.insert(3);
	map.insert(4);

	BOOST_CHECK_EQUAL(TestObject::get_instances(), 4);
  }

  BOOST_CHECK_EQUAL(TestObject::get_instances(), 0);
}

BOOST_AUTO_TEST_CASE( auto_dynamic_map_erase ) {
  TestObject::reset();

  ObjectSet<int, TestObject> map;

  map.insert(1);
  map.insert(2);
  map.insert(3);

  BOOST_CHECK_EQUAL(TestObject::get_instances(), 3);

  map.erase(1);

  BOOST_CHECK_EQUAL(TestObject::get_instances(), 2);

  map.erase(3);

  BOOST_CHECK_EQUAL(TestObject::get_instances(), 1);
}

max_stars_repo_name: benhsmith/netwhere

max_issues_repo_name: benhsmith/netwhere

max_forks_repo_name: benhsmith/netwhere


text:
//          Copyright John W. Wilkinson 2007 - 2011
// Distributed under the MIT License, see accompanying file LICENSE.txt

// json spirit version 4.05

#include "value_test.h"
#include "utils_test.h"
#include <json_spirit/value.h>
#include <limits.h>
#include <list>
#include <boost/assign/list_of.hpp>
#include <boost/integer_traits.hpp>

using namespace json_spirit;
using namespace std;
using namespace boost;
using namespace boost::assign;

namespace
{
#ifdef JSON_SPIRIT_VALUE_ENABLED

    const int64_t max_int64   = integer_traits< int64_t  >::max();
    const uint64_t max_uint64 = integer_traits< uint64_t >::max();

    void test_obj_value()
    {
        const Object::value_type p1( "name1", "value1" );
        const Object::value_type p3( "name3", "value3" );

        Object obj_1; obj_1.insert( p1 );
        Object obj_2; obj_2.insert( p1 );
        Object obj_3; obj_3.insert( p3 );

        Value v1( obj_1 );
        Value v2( obj_2 );
        Value v3( obj_3 );

        ASSERT_EQ( v1.type(), Value::OBJECT_TYPE );
        ASSERT_EQ ( v1, v2 );
        ASSERT_NEQ( v1, v3 );

        ASSERT_EQ( v1.getObject(), obj_1 );
        ASSERT_EQ( v3.getObject(), obj_3 );
    }

    void test_array_value()
    {
        Array array_1; array_1.push_back( 1 ); array_1.push_back( "2" );
        Array array_2; array_2.push_back( 1 ); array_2.push_back( "2" );
        Array array_3; array_3.push_back( 1 ); array_3.push_back( "X" );

        Value v1( array_1 );
        Value v2( array_2 );
        Value v3( array_3 );

        ASSERT_EQ( v1.type(), Value::ARRAY_TYPE );
        ASSERT_EQ ( v1, v2 );
        ASSERT_NEQ( v1, v3 );

        ASSERT_EQ( v1.getArray(), array_1 );
        ASSERT_EQ( v3.getArray(), array_3 );
    }

    void test_bool_value()
    {
        Value v1( true );
        Value v2( true );
        Value v3( false );

        ASSERT_EQ( v1.type(), Value::BOOL_TYPE );
        ASSERT_EQ ( v1, v2 );
        ASSERT_NEQ( v1, v3 );

        assert( v1.getBool() );
        assert( !v3.getBool() );
    }

    void test_int_value()
    {
        Value v1( 1 );
        Value v2( 1 );
        Value v3( INT_MAX );

        ASSERT_EQ( v1.type(), Value::INT_TYPE );
        ASSERT_EQ ( v1, v2 );
        ASSERT_EQ( v3.type(), Value::INT_TYPE );
        ASSERT_NEQ( v1, v3 );

        unsigned int uint_max = INT_MAX;

        ASSERT_EQ( v1.getInt(),    1 );
        ASSERT_EQ( v1.getInt64(),  1 );
        ASSERT_EQ( v1.getUInt64(), 1u );
        ASSERT_EQ( v3.getInt(),    INT_MAX );
        ASSERT_EQ( v3.getInt64(),  INT_MAX );
        ASSERT_EQ( v3.getUInt64(), uint_max );

        Value v5( max_int64 );

        ASSERT_EQ( v5.getInt64(), max_int64 );
        ASSERT_EQ( v5.getUInt64(), static_cast< uint64_t >( max_int64 ) );

        const uint64_t max_int64_plus_1 = max_int64 + uint64_t( 1 );

        Value v6( max_int64_plus_1 );

        ASSERT_EQ( v6.getUInt64(), max_int64_plus_1 );

        Value v7( max_uint64 );

        ASSERT_EQ( v7.getUInt64(), max_uint64 );

        Value v8( 0 );

        ASSERT_EQ( v8.getInt(),    0 );
        ASSERT_EQ( v8.getInt64(),  0 );
        ASSERT_EQ( v8.getUInt64(), 0u );

        Value v9( -1 );

        ASSERT_EQ( v9.getInt(),   -1 );
        ASSERT_EQ( v9.getInt64(), -1 );
        ASSERT_EQ( v9.getUInt64(), max_uint64 );
    }

    void test_real_value()
    {
        Value v1( 1.0 );
        Value v2( 1.0 );
        Value v3( 2.0 );

        ASSERT_EQ( v1.type(), Value::REAL_TYPE );
        ASSERT_EQ ( v1, v2 );
        ASSERT_NEQ( v1, v3 );

        ASSERT_EQ( v1.getReal(), 1.0 );
        ASSERT_EQ( v3.getReal(), 2.0 );
    }

    void test_null_value()
    {
        Value v1;
        Value v2;

        ASSERT_EQ( v1.type(), Value::NULL_TYPE );
        ASSERT_EQ( v1.isNull(), true );
        ASSERT_EQ( v1, v2 );
        ASSERT_EQ( v1.isNull(), true );
        ASSERT_EQ( Value( 1 ).isNull(), false );
    }

    template< typename T >
    void test_get_value( const T& t )
    {
        ASSERT_EQ( Value( t ).getValue< T >(), t );
    }

    void test_get_value()
    {
        test_get_value( 123 );
        test_get_value( max_int64 );
        test_get_value( 1.23 );
        test_get_value( true );
        test_get_value( false );
        test_get_value( string( "test" ) );

        Array a; a.push_back( 1 ); a.push_back( "2" );

        test_get_value( a );

        Object obj; obj.insert( Object::value_type( "name1", "value1" ) );

        test_get_value( obj );
    }

    void assert_array_eq( const Value& v, const Array& a )
    {
        ASSERT_EQ( v.getArray(), a );
    }

    void assert_obj_eq( const Value& v, const Object& obj )
    {
        ASSERT_EQ( v.getObject(), obj );
    }

    template< typename T >
    void check_copy( const T& t )
    {
        const Value v1( t );
        const Value v2( v1 );
        Value v3;
        v3 = v1;

        ASSERT_EQ( v1, v2 );
        ASSERT_EQ( v1, v3 );

        ASSERT_EQ( v2.getValue< T >(), t );
        ASSERT_EQ( v3.getValue< T >(), t );

        ASSERT_EQ( v1.isUInt64(), v2.isUInt64() );
        ASSERT_EQ( v1.isUInt64(), v3.isUInt64() );
    }

    void check_copying_null()
    {
        const Value v1;
        const Value v2( v1 );
        Value v3;
        v3 = v1;

        ASSERT_EQ( v2.type(), Value::NULL_TYPE );
        ASSERT_EQ( v3.type(), Value::NULL_TYPE );
    }

    void test_copying()
    {
        {
            const Array array_1 = list_of(1)(2);

            Value v1( array_1 );
            const Value v2( v1 );

            assert_array_eq( v1, array_1 );
            assert_array_eq( v2, array_1 );

            v1.getArray()[0] = 3;

            assert_array_eq( v1, list_of(3)(2) );
            assert_array_eq( v2, array_1 );
        }
        {
            const Object obj_1 = map_list_of( "a", 1 )( "b", 2 );

            Value v1( obj_1 );
            Value v2;

            v2 = v1;

            assert_obj_eq( v1, obj_1 );
            assert_obj_eq( v2, obj_1 );
        }
        {
            LOG_TEST(check_copy( 1 ));
            LOG_TEST(check_copy( 2.0 ));
            LOG_TEST(check_copy( max_int64 ));
            LOG_TEST(check_copy( max_uint64 ));
            LOG_TEST(check_copy( string("test") ));
            LOG_TEST(check_copy( true ));
            LOG_TEST(check_copy( false ));
            const Array array_1 = list_of(1)(2);
            LOG_TEST(check_copy( array_1 ));
            const Object obj_1 = map_list_of( "a", 1 )( "b", 2 );
            LOG_TEST(check_copy( obj_1 ));
            LOG_TEST(check_copying_null());
        }
    }

    template< typename ObjectType > void check_pair_typedefs( ObjectType &object )
    {
        typename ObjectType::key_type name = object.begin()->first;
        typename ObjectType::value_type::second_type value = object.begin()->second;
    }

    void check_pair_typedefs()
    {
        Object o;
        check_pair_typedefs( o );

#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
        wObject wo;
        check_pair_typedefs( wo );
#endif
    }

    void test_obj_map_implemention()
    {
#ifdef JSON_SPIRIT_VALUE_ENABLED
        Object obj;

        obj[ "name 1" ] = 1;
        obj[ "name 2" ] = "two";

        ASSERT_EQ( obj.size(), 2u );

        ASSERT_EQ( obj.find( "name 1" )->second.getInt(), 1 );
        ASSERT_EQ( obj.find( "name 2" )->second.getString(), "two" );
#endif
    }

    template< typename Int >
    void check_an_int_is_a_real( Int i, bool expected_result )
    {
        ASSERT_EQ( Value( i ).isUInt64(), expected_result );
    }

    void test_is_uint64()
    {
        LOG_TEST(check_an_int_is_a_real( 1,                            false ));
        LOG_TEST(check_an_int_is_a_real( static_cast< int64_t  >( 1 ), false ));
        LOG_TEST(check_an_int_is_a_real( static_cast< uint64_t >( 1 ), true ));
    }

    template< typename Int >
    void check_an_int_is_a_real( Int i, double expected_result )
    {
        ASSERT_EQ( Value( i ).getReal(), expected_result );
    }

    void test_an_int_is_a_real()
    {
        LOG_TEST(check_an_int_is_a_real( -1, -1.0 ));
        LOG_TEST(check_an_int_is_a_real(  0,  0.0 ));
        LOG_TEST(check_an_int_is_a_real(  1,  1.0 ));
        LOG_TEST(check_an_int_is_a_real( max_int64,  9223372036854775800.0 ));
        LOG_TEST(check_an_int_is_a_real( max_uint64, 18446744073709552000.0 ));
    }

    template< typename T >
    void check_wrong_type_exceptions( const Value::Type vtype )
    {
        Value v;

        ASSERT_EQ( v.type(), Value::NULL_TYPE );

        try
        {
            v.getValue< T >();

            assert( false );
        }
        catch( const runtime_error& e )
        {
            ostringstream os;

            os << "value type is " << (int)Value::NULL_TYPE << " not " << (int)vtype;

            ASSERT_EQ( e.what(), os.str() );
        }
    }

    void test_wrong_type_exceptions()
    {
        LOG_TEST(check_wrong_type_exceptions< Object >( Value::OBJECT_TYPE ));
        LOG_TEST(check_wrong_type_exceptions< Array >( Value::ARRAY_TYPE ));
        LOG_TEST(check_wrong_type_exceptions< string >( Value::STRING_TYPE ));
        LOG_TEST(check_wrong_type_exceptions< bool >( Value::BOOL_TYPE ));
        LOG_TEST(check_wrong_type_exceptions< boost::int64_t >( Value::INT_TYPE ));
        LOG_TEST(check_wrong_type_exceptions< int >( Value::INT_TYPE ));
        LOG_TEST(check_wrong_type_exceptions< double >( Value::REAL_TYPE ));
    }

void test_path_contains() {
    // Construct a hierarchy of objects for tests
    const Object bar = map_list_of( "a", 1 )( "b", 2 );
    const Object foo = map_list_of( "bar", Value(bar) )( "c", 3 );
    const Object obj1 = map_list_of( "foo", Value(foo))( "d", 4 );
    const Value v1(obj1);

    // Top level get of a value
    ASSERT_EQ(v1.contains("d"), true);
    ASSERT_EQ(v1.contains("not there"), false);

    // Two level
    ASSERT_EQ(v1.contains("foo.c"), true);
    ASSERT_EQ(v1.contains("foo.not there"), false);

    // Three level
    ASSERT_EQ(v1.contains("foo.bar.a"), true);
    ASSERT_EQ(v1.contains("foo.bar.not there"), false);
}

void test_path_get() {
    // Construct a hierarchy of objects for tests
    const Object bar = map_list_of( "a", 1 )( "b", 2 );
    const Object foo = map_list_of( "bar", Value(bar) )( "c", 3 );
    const Object obj1 = map_list_of( "foo", Value(foo))( "d", 4 );
    const Value v1(obj1);

    // Top level get of a value
    const Value& dval = v1.get("d");
    ASSERT_EQ(dval.type(), Value::INT_TYPE);
    ASSERT_EQ(dval.getInt(), 4);

    // Two level
    const Value& cval = v1.get("foo.c");
    ASSERT_EQ(cval.type(), Value::INT_TYPE);
    ASSERT_EQ(cval.getInt(), 3);

    // Three level
    const Value& aval = v1.get("foo.bar.a");
    ASSERT_EQ(aval.type(), Value::INT_TYPE);
    ASSERT_EQ(aval.getInt(), 1);

    // Mutable access
    Value v2(obj1);
    Value& subval1 = v2.get("foo.bar");
    ASSERT_EQ(subval1.type(), Value::OBJECT_TYPE);
    subval1.insert("x", "val");
    ASSERT_EQ(subval1.getObject()["x"].getString(), "val");
}

void check_get_path_error_exception(const Value& v, const std::string& path, const Value::PathError& expected_error) {
    try {
        v.get(path);
    }
    catch(const Value::PathError& e) {
        ASSERT_EQ(expected_error, e);
        return;
    }
    assert(false);
}

void test_path_get_exceptions() {
    // Construct a hierarchy of objects for tests
    const Object bar = map_list_of( "a", 1 )( "b", 2 );
    const Object foo = map_list_of( "bar", Value(bar) )( "c", 3 );
    const Object obj1 = map_list_of( "foo", Value(foo))( "d", 4 );
    const Value v1(obj1);

    // Non-object
    const Value vint(2);
    LOG_TEST(check_get_path_error_exception(vint, "x", Value::PathError("x", "<root>")));

    // Non-existent path component
    LOG_TEST(check_get_path_error_exception(v1, "shazaam", Value::PathError("shazaam", "shazaam")));

    // Empty subpath
    LOG_TEST(check_get_path_error_exception(v1, "foo..a", Value::PathError("foo..a", "")));

    // Non-object in path
    LOG_TEST(check_get_path_error_exception(v1, "foo.d.c", Value::PathError("foo.d.c", "d")));
}

void test_path_get_helpers() {
    // Test the helpers that extract values directly by path. Provide
    // one of each type
    const Object obj = map_list_of("a", 2)("b", 3);
    const Array arr = list_of(2)(3);
    const Object foo = map_list_of
        ("string", Value("a string"))
        ("object", obj)
        ("array", arr)
        ("bool", true)
        ("int", 42)
        ("real", 52.3)
        ("realint", 12)
        ;
    Value v(foo);

    ASSERT_EQ(v.getString("string"), "a string");
    ASSERT_EQ(v.getObject("object"), obj);
    ASSERT_EQ(v.getArray("array"), arr);
    ASSERT_EQ(v.getBool("bool"), true);
    ASSERT_EQ(v.getInt("int"), 42);
    ASSERT_EQ(v.getInt64("int"), (boost::int64_t)42);
    ASSERT_EQ(v.getUInt64("int"), (boost::uint64_t)42);
    ASSERT_EQ(v.getReal("realint"), 12.f);
}

// Test that get helpers *don't* get defaults when the values are available
void test_path_get_helpers_not_defaults() {
    // Test the helpers that extract values directly by path. Provide
    // one of each type
    const Object obj = map_list_of("a", 2)("b", 3);
    const Array arr = list_of(2)(3);
    const Object foo = map_list_of
        ("string", Value("a string"))
        ("object", obj)
        ("array", arr)
        ("bool", true)
        ("int", 42)
        ("real", 52.3)
        ("realint", 12)
        ;
    Value v(foo);

    const Object bad_obj = map_list_of("x", 4)("y", 5);
    const Array bad_arr = list_of(7)(8);

    ASSERT_EQ(v.getString("string", "not a string"), "a string");
    ASSERT_EQ(v.getObject("object", bad_obj), obj);
    ASSERT_EQ(v.getArray("array", bad_arr), arr);
    ASSERT_EQ(v.getBool("bool", false), true);
    ASSERT_EQ(v.getInt("int", 0), 42);
    ASSERT_EQ(v.getInt64("int", (boost::int64_t)0), (boost::int64_t)42);
    ASSERT_EQ(v.getUInt64("int", (boost::uint64_t)0), (boost::uint64_t)42);
    ASSERT_EQ(v.getReal("realint", 0.f), 12.f);
}

// Test defaults are retrieved when fields are not available
void test_path_get_helpers_defaults() {
    // Test the helpers that extract values directly by path. Provide
    // one of each type
    const Object foo = map_list_of("x", 2);
    Value v(foo);

    const Object default_obj = map_list_of("x", 4)("y", 5);
    const Array default_arr = list_of(7)(8);

    ASSERT_EQ(v.getString("string", "not a string"), "not a string");
    ASSERT_EQ(v.getObject("object", default_obj), default_obj);
    ASSERT_EQ(v.getArray("array", default_arr), default_arr);
    ASSERT_EQ(v.getBool("bool", false), false);
    ASSERT_EQ(v.getInt("int", 0), 0);
    ASSERT_EQ(v.getInt64("int", (boost::int64_t)0), (boost::int64_t)0);
    ASSERT_EQ(v.getUInt64("int", (boost::uint64_t)0), (boost::uint64_t)0);
    ASSERT_EQ(v.getReal("realint", 0.f), 0.f);
}

void test_path_insert() {
    Object n;
    Value v1(n);
    ASSERT_EQ( v1.type(), Value::OBJECT_TYPE);

    bool inserted;

    // Single element path, integer
    inserted = v1.insert("a", 7);
    ASSERT_EQ(inserted, true);
    assert( v1.getObject().find("a") != v1.getObject().end());
    ASSERT_EQ( v1.getObject()["a"].type(), Value::INT_TYPE );
    ASSERT_EQ( v1.getObject()["a"].getInt(), 7);

    // Two element path, string
    inserted = v1.insert("b.cd", "XXX");
    ASSERT_EQ(inserted, true);
    assert( v1.getObject().find("b") != v1.getObject().end());
    ASSERT_EQ( v1.getObject()["b"].type(), Value::OBJECT_TYPE );
    assert( v1.getObject()["b"].getObject().find("cd") != v1.getObject()["b"].getObject().end());
    ASSERT_EQ( v1.getObject()["b"].getObject()["cd"].type(), Value::STRING_TYPE);
    ASSERT_EQ( v1.getObject()["b"].getObject()["cd"].getString(), "XXX");

    // Two elements, preserve previous elements
    inserted = v1.insert("b.e", "YYY");
    ASSERT_EQ(inserted, true);
    ASSERT_EQ( v1.getObject()["b"].getObject()["cd"].getString(), "XXX");
    assert( v1.getObject()["b"].getObject().find("e") != v1.getObject()["b"].getObject().end());
    ASSERT_EQ( v1.getObject()["b"].getObject()["e"].type(), Value::STRING_TYPE);
    ASSERT_EQ( v1.getObject()["b"].getObject()["e"].getString(), "YYY");

    // Fail to insert over existing element
    inserted = v1.insert("b.e", "ZZZ");
    ASSERT_EQ(inserted, false);
    ASSERT_EQ( v1.getObject()["b"].getObject()["e"].getString(), "YYY");
}

void test_path_put() {
    // Assume test_path_insert() passes. We only need to check the changes in
    // behavior: overwriting data.

    Object n;
    Value v1(n);
    ASSERT_EQ( v1.type(), Value::OBJECT_TYPE);

    // Prep some test data
    v1.put("b.e", "YYY");
    assert( v1.getObject()["b"].getObject().find("e") != v1.getObject()["b"].getObject().end());
    ASSERT_EQ( v1.getObject()["b"].getObject()["e"].type(), Value::STRING_TYPE);
    ASSERT_EQ( v1.getObject()["b"].getObject()["e"].getString(), "YYY");

    // Overwrite test
    v1.put("b.e", 2);
    assert( v1.getObject()["b"].getObject().find("e") != v1.getObject()["b"].getObject().end());
    ASSERT_EQ( v1.getObject()["b"].getObject()["e"].type(), Value::INT_TYPE);
    ASSERT_EQ( v1.getObject()["b"].getObject()["e"].getInt(), 2);
}

template<typename T>
void check_insert_path_error_exception(Value& v, const std::string& path, const T& val, const Value::PathError& expected_error) {
    try {
        v.insert(path, val);
    }
    catch(const Value::PathError& e) {
        ASSERT_EQ(expected_error, e);
        return;
    }
    assert(false);
}

void test_path_insert_error() {
    // Non-object values
    Value v1(2);
    LOG_TEST(check_insert_path_error_exception(v1, "foo", 2, Value::PathError("foo", "<root>")));

    Object n;
    Value v2(n);

    // Empty subpath
    LOG_TEST(check_insert_path_error_exception(v2, "foo..bar", 2, Value::PathError("foo..bar", "")));

    // baz isn't an object
    v2.insert("foo.baz", 2);
    LOG_TEST(check_insert_path_error_exception(v2, "foo.baz.bar", 2, Value::PathError("foo.baz.bar", "baz")));

}

#endif

    template< class Config_type >
    class Container_constructor_runner
    {
    public:

        Container_constructor_runner()
        {
            vector< double > vd = list_of( 1.2 )( 1.3 );  LOG_TEST(test_container_constructor( vd ));
            {
                vector< int >    vi = list_of( 1 );           LOG_TEST(test_container_constructor( vi ));
            }
            {
                vector< int >    vi = list_of( 1 )( 2 );      LOG_TEST(test_container_constructor( vi ));
            }
            {
                vector< int >    vi = list_of( 1 )( 2 )( 3 ); LOG_TEST(test_container_constructor( vi ));
            }
            list< double >   ld = list_of( 1.2 )( 1.3 );  LOG_TEST(test_container_constructor( ld ));
            {
                list< int >      li = list_of( 1 );           LOG_TEST(test_container_constructor( li ));
            }
            {
                list< int >      li = list_of( 1 )( 2 );      LOG_TEST(test_container_constructor( li ));
            }
            {
                list< int >      li = list_of( 1 )( 2 )( 3 ); LOG_TEST(test_container_constructor( li ));
            }
        }

    private:

        typedef typename Config_type::Array_type Array_type;
        typedef typename Config_type::ValueType ValueType;

        template< class Cont >
        void test_container_constructor( const Cont& cont )
        {
            typedef typename Cont::value_type Cont_value_type;
            const ValueType val( cont.begin(), cont.end() );
            const Array_type& arr = val.getArray();
            Cont result;
            for( unsigned int i = 0; i < arr.size(); ++i )
            {
                result.push_back( arr[i].template getValue< Cont_value_type>() );
            }
            ASSERT_EQ( result, cont );
        }
    };

    void test_container_constructor()
    {
#ifdef JSON_SPIRIT_VALUE_ENABLED
       Container_constructor_runner< Config >();
#endif
#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
        Container_constructor_runner< wConfig >();
#endif
    }

    template< class Config_type >
    class Variant_constructor_runner
    {
    public:

        Variant_constructor_runner()
        {
            LOG_TEMPLATE_TEST();
            test_variant_constructor< variant< int, double > >( 1.23 );
            LOG_TEMPLATE_TEST();
            test_variant_constructor< variant< int, double > >( 123 );
            LOG_TEMPLATE_TEST();
            test_variant_constructor< variant< int, double, String_type > >( to_str< String_type >( "foo" ) );
            LOG_TEMPLATE_TEST();
            test_variant_constructor< variant< int, double, String_type, bool > >( true );
            LOG_TEMPLATE_TEST();
            test_variant_constructor< variant< int, double, String_type, bool, boost::int64_t > >( boost::int64_t( 123 ) );
            LOG_TEMPLATE_TEST();
            test_variant_constructor< variant< int, double, String_type, bool, boost::uint64_t > >( boost::uint64_t( 123 ) );

            {
                variant< int, Null > variant = Null();
                const ValueType val( variant );
                assert( val.isNull() );
            }

            vector< double > vd = list_of( 1.2 )( 1.3 );   LOG_TEST(test_variant_array_constructor< double > ( vd ));
            {
                vector< int >    vi = list_of( 1 );            LOG_TEST(test_variant_array_constructor< int >( vi ));
            }
            {
                vector< int >    vi = list_of( 1 )( 2 );       LOG_TEST(test_variant_array_constructor< int >( vi ));
            }
            {
                vector< int >    vi = list_of( 1 )( 2 )( 3 );  LOG_TEST(test_variant_array_constructor< int >( vi ));
            }
            list< double >   ld = list_of( 1.2 )( 1.3 );   LOG_TEST(test_variant_array_constructor< double >( ld ));
            {
                list< int >      li = list_of( 1 );            LOG_TEST(test_variant_array_constructor< int >( li ));
            }
            {
                list< int >      li = list_of( 1 )( 2 );       LOG_TEST(test_variant_array_constructor< int >( li ));
            }
            {
                list< int >      li = list_of( 1 )( 2 )( 3 );  LOG_TEST(test_variant_array_constructor< int >( li ));
            }
        }

    private:

        typedef typename Config_type::String_type String_type;
        typedef typename Config_type::Array_type Array_type;
        typedef typename Config_type::ValueType ValueType;

        template< class Variant_t, typename T >
        void test_variant_constructor( const T& t )
        {
            const Variant_t variant( t );
            const ValueType val( variant );
            ASSERT_EQ( val.template getValue< T >(), t );
        }

        template< typename T, typename A, template< typename, typename > class Cont >
        void test_variant_array_constructor( const Cont< T, A >& cont )
        {
            const variant< int, Cont< T, A > > variant = cont;
            const ValueType val( variant );
            const Array_type& arr = val.getArray();
            Cont< T, A > result;
            for( unsigned int i = 0; i < arr.size(); ++i )
            {
                result.push_back( arr[i].template getValue< T >() );
            }
            ASSERT_EQ( result, cont );
        }
    };

    void test_variant_constructor()
    {
#ifdef JSON_SPIRIT_VALUE_ENABLED
        Variant_constructor_runner< Config >();
#endif
#if defined( JSON_SPIRIT_WVALUE_ENABLED ) && !defined( BOOST_NO_STD_WSTRING )
       Variant_constructor_runner< wConfig >();
#endif
    }
}

void json_spirit::test_value()
{
#ifdef JSON_SPIRIT_VALUE_ENABLED
    Object obj;
    Value value_str ( "value" );
    Value value_obj ( obj );
    Value value_bool( true );

    Value value_str_2 ( string( "value" ) );
    Value value_obj_2 ( obj );
    Value value_bool_2( false );

    const char* str( "value" );
    Value value_str_2b ( str );

    ASSERT_EQ( value_str, value_str );
    ASSERT_EQ( value_str, value_str_2 );
    ASSERT_EQ( value_str, value_str_2b );
    ASSERT_EQ( value_obj, value_obj );
    ASSERT_EQ( value_obj, value_obj_2 );
    ASSERT_NEQ( value_str, value_obj );
    ASSERT_NEQ( value_str, value_bool );

    Object obj_2;
    obj_2.insert( Object::value_type( "name", value_str ) );
    Value value_str_3( "xxxxx" );
    Value value_obj_3( obj_2 );

    ASSERT_NEQ( value_str, value_str_3 );
    ASSERT_NEQ( value_obj, value_obj_3 );

    RUN_TEST(test_obj_value());
    RUN_TEST(test_array_value());
    RUN_TEST(test_bool_value());
    RUN_TEST(test_int_value());
    RUN_TEST(test_real_value());
    RUN_TEST(test_null_value());
    RUN_TEST(test_get_value());
    RUN_TEST(test_copying());
    RUN_TEST(test_obj_map_implemention());
    RUN_TEST(test_is_uint64());
    RUN_TEST(test_an_int_is_a_real());
    RUN_TEST(test_wrong_type_exceptions());
    RUN_TEST(test_path_contains());
    RUN_TEST(test_path_get());
    RUN_TEST(test_path_get_exceptions());
    RUN_TEST(test_path_get_helpers());
    RUN_TEST(test_path_insert());
    RUN_TEST(test_path_put());
    RUN_TEST(test_path_insert_error());
#endif
    RUN_TEST(test_container_constructor());
    RUN_TEST(test_variant_constructor());
}

max_stars_repo_name: sirikata/json-spirit

max_issues_repo_name: sirikata/json-spirit

max_forks_repo_name: sirikata/json-spirit


text:
#include <boost_adaptbx/tests/tst_optional_copy.h>
#include <vector>
#include <iostream>
#include <cstdio>

struct empty {};

int main(int argc, char* argv[])
{
  unsigned long n_iter = 1;
  if (argc == 2) {
    std::sscanf(argv[1], "%lu", &n_iter);
  }
  for(unsigned long i_iter=0;i_iter==0||i_iter<n_iter;)
  {
    {
      using tbxx::optional_copy;
      optional_copy<int> oc_int;
      TBXX_ASSERT(!oc_int);
      oc_int = 1;
      TBXX_ASSERT(oc_int);
      TBXX_ASSERT(*oc_int == 1);
    }
    {
      using tbxx::optional_copy;
      optional_copy<empty> oc_empty;
      TBXX_ASSERT(!oc_empty);
      oc_empty = empty();
      TBXX_ASSERT(oc_empty);
    }
    {
      std::size_t n = 1;
      std::vector<int> v1(n, 1);
      std::vector<int> v4(n, 4);
      using boost_adaptbx::tst_optional_copy::exercise;
      exercise(v1, v4, /*value_is_shared*/ false);
    }
    if (n_iter != 0) i_iter++;
  }
  std::cout << "OK\n";
  return 0;
}


text:
#pragma once

#include <memory>
#include <mutex>

#include <boost/asio/steady_timer.hpp>

#include <nexus/quic/settings.hpp>

struct lsquic_engine;
struct lsquic_conn;
struct lsquic_stream;
struct lsquic_out_spec;

namespace nexus::quic::detail {

struct connection_impl;
struct stream_impl;
struct socket_impl;

struct engine_deleter { void operator()(lsquic_engine* e) const; };
using lsquic_engine_ptr = std::unique_ptr<lsquic_engine, engine_deleter>;

struct engine_impl {
  mutable std::mutex mutex;
  boost::asio::any_io_executor ex;
  boost::asio::steady_timer timer;
  lsquic_engine_ptr handle;
  // pointer to client socket or null if server
  socket_impl* client;
  uint32_t max_streams_per_connection;
  bool is_http;

  void process(std::unique_lock<std::mutex>& lock);
  void reschedule(std::unique_lock<std::mutex>& lock);
  void on_timer();

  engine_impl(const boost::asio::any_io_executor& ex, socket_impl* client,
              const settings* s, unsigned flags);
  ~engine_impl();

  using executor_type = boost::asio::any_io_executor;
  executor_type get_executor() const { return ex; }

  void close();

  int send_packets(const lsquic_out_spec *specs, unsigned n_specs);

  stream_impl* on_new_stream(connection_impl& c, lsquic_stream* stream);
};

} // namespace nexus::quic::detail

max_stars_repo_name: cbodley/nexus

max_issues_repo_name: cbodley/nexus

max_forks_repo_name: cbodley/nexus


text:
/*  Sirikata
 *  SerializationCheck.hpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  All rights reserved.
 *
 *  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.
 *  * Neither the name of Sirikata 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 OWNER
 * 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.
 */

#ifndef _SIRIKATA_SERIALIZATION_CHECK_HPP_
#define _SIRIKATA_SERIALIZATION_CHECK_HPP_

#include "util/Platform.hpp"
#include <boost/thread/thread.hpp>

namespace Sirikata {

/** Verifies that code blocks you expect to be handled in a serialized
 *  fashion (i.e. non-concurrently) are actually handled that way.
 *  Mark these sections with calls to serializedEnter() and
 *  serializedExit() at the beinning and end respectively and those
 *  calls will assert in debug mode if this condition is violated.
 *  This can be used recursively within a thread -- multiple calls
 *  to serializedEnter() from the same thread will not result in
 *  an error.
 */
class SerializationCheck {
public:
    // Used to mark an entire scope as
    class Scoped {
    public:
        Scoped(SerializationCheck* p)
         : parent(p)
        {
            parent->serializedEnter();
        }

        ~Scoped() {
            parent->serializedExit();
        }
    private:
        Scoped();
        Scoped(Scoped& rhs);
        Scoped& operator=(Scoped& rhs);

        SerializationCheck* parent;
    };

    SerializationCheck()
     : mAccessors(0),
       mThreadID()
    {
    }

    inline void serializedEnter() {
        int32 val = ++mAccessors;

        assert(val >= 1);

        if (val == 1) {
            // We're the first ones in here, we need to setup the thread id
            mThreadID = boost::this_thread::get_id();
        }
        else {
            // We got in here later on.  This is only valid if we were in the
            // same thread, so the thread had better already be marked and
            // match ours
            assert(mThreadID == boost::this_thread::get_id());
        }
    }

    inline void serializedExit() {
        if (mAccessors == (int32)1) {
            // We should be the only one left accessing this and a
            // serializedEnter should *not* be getting called, so we
            // can erase the thread ID now.
            mThreadID = boost::thread::id();
        }

        int32 val = --mAccessors;
        assert(val >= 0);
    }
private:
    // Implementation Note: Technically this isn't all thread safe.  However,
    // the core component which tracks the number of accessors and their order
    // off access is thread safe. Any thread-unsafe accesses should only result
    // in a bad comparison, which should result in an assertion anyway since the
    // whole point of this class is to verify that multiple threads are not trying
    // to access shared data (including this object) at the same time.
    AtomicValue<int32> mAccessors;
    boost::thread::id mThreadID;
};

} // namespace Sirikata

#endif //_SIRIKATA_SERIALIZATION_CHECK_HPP_

max_stars_repo_name: danielrh/sirikata

max_issues_repo_name: danielrh/sirikata

max_forks_repo_name: danielrh/sirikata


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

#include <boost/property_tree/ptree.hpp>

#include "clotho/cuda/data_spaces/basic_data_space.hpp"
#include "clotho/cuda/analysis/sequence_hamming_weight_kernel.hpp"

#include "clotho/cuda/device_state_object.hpp"

#ifndef HAMMING_VERSION
#define HAMMING_VERSION 5
#endif  // HAMMING_VERSION

class SequenceHammingWeight : public clotho::utility::iStateObject {
public:

    typedef basic_data_space< unsigned int >                    space_type;
    typedef clotho::utility::algo_version< HAMMING_VERSION >    algo_version_type;

    SequenceHammingWeight( boost::property_tree::ptree & config ) :
        dWeights( NULL )
    {
        create_space( dWeights );
        parse_configuration( config );
    }

    template < class PopulationSpaceType >
    void evaluate( PopulationSpaceType * pop ) {
        _resize_space_to<<< 1, 1 >>>( dWeights, pop->sequences.get_device_space() );
        CHECK_LAST_KERNEL_EXEC

        algo_version_type * ver = NULL;
        dim3 blocks( pop->seq_count, 1, 1), threads( 32, 32, 1);
        sequence_hamming_weight_kernel<<< blocks, threads >>>( pop->sequences.get_device_space(), dWeights, ver );
        CHECK_LAST_KERNEL_EXEC
    }

    void get_state( boost::property_tree::ptree & state ) {
        boost::property_tree::ptree w;
        get_device_object_state( w, dWeights );
        state.add_child( "sequence_degree_spectrum", w );
    }

    virtual ~SequenceHammingWeight() {
        delete_space( dWeights );
    }

protected:
    void parse_configuration( boost::property_tree::ptree & config ) {

    }

    space_type * dWeights;
};

#endif  // SEQUENCE_HAMMING_WEIGHT_HPP_

max_stars_repo_name: putnampp/clotho

max_issues_repo_name: putnampp/clotho

max_forks_repo_name: putnampp/clotho


text:
#ifndef RODIN_CORE_GEOMETRY_SEGMENT2D_IPP
#define RODIN_CORE_GEOMETRY_SEGMENT2D_IPP

#include <Eigen/Core>

#include "Point2D.h"
#include "Circle.h"

#include "LineSegment2D.h"

namespace Rodin::Plot::Geometry
{

  template <class T>
  constexpr
  LineSegment2D<T>::LineSegment2D(
      const Point2D<T>& start, const Point2D<T>& end)
    : m_start(start), m_end(end)
  {
    assert(start != end);
  }

  template <class T>
  inline
  constexpr
  Point2D<T> LineSegment2D<T>::operator()(const T& t) const
  {
    return start() + t * (end() - start());
  }

  template <class T>
  inline
  constexpr
  T LineSegment2D<T>::length() const
  {
    return (m_end - m_start).norm();
  }

  template <class T>
  inline
  constexpr
  Magnum::Math::Vector2<T> LineSegment2D<T>::direction() const
  {
    return (m_end - m_start).normalized();
  }

  template <class T>
  inline
  constexpr
  Point2D<T> LineSegment2D<T>::start() const
  {
    return m_start;
  }

  template <class T>
  inline
  constexpr
  Point2D<T> LineSegment2D<T>::end() const
  {
    return m_end;
  }

  template <class T>
  inline
  constexpr
  LineSegment2D<T>& LineSegment2D<T>::setStart(const Point2D<T>& start)
  {
    m_start = start;
    return *this;
  }

  template <class T>
  inline
  constexpr
  LineSegment2D<T>& LineSegment2D<T>::setEnd(const Point2D<T>& end)
  {
    m_end = end;
    return *this;
  }

  template <class T>
  inline
  constexpr
  LineSegment2D<T> LineSegment2D<T>::reverse() const
  {
    return LineSegment2D<T>(end(), start());
  }

  template <class T>
  inline
  constexpr
  std::optional<Point2D<T>> LineSegment2D<T>::intersect(const
      LineSegment2D<T>& other)
  const
  {
    auto det = (end().x() - start().x()) * (other.start().y() - other.end().y()) -
      (end().y() - start().y()) * (other.start().x() - other.end().x());

    if (det == T{0})
      return {};
    else
    {
      auto s0 = (other.start().y() - other.end().y()) * (other.start().x() - start().x())
            + (other.end().x() - other.start().x()) * (other.start().y() - start().y());
      s0 /= det;

      auto t0 = (start().y() - end().y()) * (other.start().x() - start().x())
            + (end().x() - start().x()) * (other.start().y() - start().y());
      t0 /= det;

      if (T{0} <= s0 && s0 <= T{1} && T{0} <= t0 && t0 <= T{1})
        return other(t0);
      else
        return {};
    }
  }
}

#endif

max_stars_repo_name: carlos-brito-pacheco/rodin

max_issues_repo_name: cbritopacheco/rodin

max_forks_repo_name: cbritopacheco/rodin


text:
//####### Test module for mathematical constants ##################

//Define Module name
 #define BOOST_TEST_MODULE "math/constants"

#include <cmath>

//Include Boost unit tests library & library for floating point comparison
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>

#include "math_constants.h"

using namespace picsar::multi_physics::math;

// ------------- Tests --------------

// ***Test math constants

template<typename RealType>
void test_case_const_math()
{
    const auto exp_pi =
        static_cast<RealType>(3.14159265358979323846264338327950288);

    const auto exp_zero = static_cast<RealType>(0.0);
    const auto exp_half = static_cast<RealType>(0.5);
    const auto exp_one = static_cast<RealType>(1.0);
    const auto exp_two = static_cast<RealType>(2.0);
    const auto exp_three = static_cast<RealType>(3.0);
    const auto exp_four = static_cast<RealType>(4.0);
    const auto exp_one_third = static_cast<RealType>(1.0/3.0);
    const auto exp_two_thirds = static_cast<RealType>(2.0/3.0);
    const auto exp_five_thirds = static_cast<RealType>(5.0/3.0);

    BOOST_CHECK_EQUAL(pi<RealType>, exp_pi);
    BOOST_CHECK_EQUAL(zero<RealType>, exp_zero);
    BOOST_CHECK_EQUAL(half<RealType>, exp_half);
    BOOST_CHECK_EQUAL(one<RealType>, exp_one);
    BOOST_CHECK_EQUAL(two<RealType>, exp_two);
    BOOST_CHECK_EQUAL(three<RealType>, exp_three);
    BOOST_CHECK_EQUAL(four<RealType>, exp_four);
    BOOST_CHECK_EQUAL(one_third<RealType>, exp_one_third);
    BOOST_CHECK_EQUAL(two_thirds<RealType>, exp_two_thirds);
    BOOST_CHECK_EQUAL(five_thirds<RealType>, exp_five_thirds);
}

BOOST_AUTO_TEST_CASE( picsar_const_math )
{
    test_case_const_math<double>();
    test_case_const_math<float>();
}

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

max_stars_repo_name: LDAmorim/picsar

max_issues_repo_name: LDAmorim/picsar

max_forks_repo_name: LDAmorim/picsar