text:
#pragma once

#include "IParamProxy.hpp"
#include <MetaObject/params/ITParam.hpp>

#include <Wt/Chart/WCartesianChart>
#include <Wt/Chart/WDataSeries>
#include <Wt/WDoubleSpinBox>
#include <Wt/WSpinBox>
#include <Wt/WStandardItemModel>

#include <boost/circular_buffer.hpp>
namespace mo
{
    namespace UI
    {
        namespace wt
        {
            template <class T>
            class TDataProxy<T,
                             typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value>::type>
            {
              public:
                static const bool IS_DEFAULT = false;
                TDataProxy() : _spin_box(nullptr) {}
                void CreateUi(IParamProxy* proxy, T& data, bool read_only)
                {
                    _spin_box = new Wt::WSpinBox(proxy);
                    _spin_box->setReadOnly(read_only);
                    _spin_box->setValue(data);
                    _spin_box->changed().connect(proxy, &IParamProxy::onUiUpdate);
                }
                void UpdateUi(const T& data) { _spin_box->setValue(data); }
                void onUiUpdate(T& data) { data = _spin_box->value(); }
                void SetTooltip(const std::string& tooltip) {}
              protected:
                Wt::WSpinBox* _spin_box;
            };
            template <class T>
            class TDataProxy<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
            {
              public:
                static const bool IS_DEFAULT = false;
                TDataProxy() : _spin_box(nullptr) {}
                void CreateUi(IParamProxy* proxy, T& data, bool read_only)
                {
                    _spin_box = new Wt::WDoubleSpinBox(proxy);
                    _spin_box->setReadOnly(read_only);
                    _spin_box->setValue(data);
                    _spin_box->changed().connect(proxy, &IParamProxy::onUiUpdate);
                }
                void UpdateUi(const T& data) { _spin_box->setValue(data); }
                void onUiUpdate(T& data) { data = _spin_box->value(); }
                void SetTooltip(const std::string& tooltip) {}
              protected:
                Wt::WDoubleSpinBox* _spin_box;
            };

            template <class T>
            class TPlotDataProxy<
                T,
                typename std::enable_if<std::is_floating_point<T>::value || std::is_integral<T>::value>::type>
            {
              public:
                static const bool IS_DEFAULT = false;
                TPlotDataProxy() : _chart(nullptr), _model(nullptr), _model_column(0)
                {
                    _data_history.set_capacity(1000);
                }
                void CreateUi(Wt::WContainerWidget* container, T& data, bool read_only, const std::string& name = "")
                {
                    IPlotProxy* proxy = dynamic_cast<IPlotProxy*>(container);

                    if (proxy)
                    {
                        auto other_chart = dynamic_cast<Wt::Chart::WCartesianChart*>(proxy->GetPlot());
                        if (other_chart)
                        {
                            _chart = other_chart;
                            _model = dynamic_cast<Wt::WStandardItemModel*>(_chart->model());
                            _model_column = _model->columnCount();
                            _model->appendColumn(std::vector<Wt::WStandardItem*>());
                        }
                    }
                    if (!_chart)
                    {
                        _chart = new Wt::Chart::WCartesianChart(container);
                        _model = new Wt::WStandardItemModel(1000, 2, container);
                        _chart->setModel(_model);
                        _model_column = 1;
                    }
                    _model->setHeaderData(_model_column, name);
                    _model->setHeaderData(0, Wt::WString("Time"));
                    _chart->setLegendEnabled(true);
                    _chart->setXSeriesColumn(0);
                    _chart->setType(Wt::Chart::ScatterPlot);
                    _chart->resize(800, 300);
                    _chart->setMargin(10, Wt::Top | Wt::Bottom);
                    _chart->setMargin(Wt::WLength::Auto, Wt::Left | Wt::Right);
                }

                void UpdateUi(const T& data, mo::Time ts)
                {
                    _data_history.push_back(std::make_pair(data, ts));
                    for (int i = 0; i < _data_history.size(); ++i)
                    {
                        _model->setData(i, 0, _data_history[i].second);
                        _model->setData(i, _model_column, _data_history[i].first);
                    }
                }
                void onUiUpdate(T& data) {}

                Wt::Chart::WCartesianChart* _chart;
                boost::circular_buffer<std::pair<T, mo::Time>> _data_history;
                Wt::WStandardItemModel* _model;
                int _model_column;
            };

            template <>
            class MO_EXPORTS TDataProxy<bool, void>
            {
              public:
                static const bool IS_DEFAULT = false;
                TDataProxy();
                void CreateUi(IParamProxy* proxy, bool& data, bool read_only);
                void UpdateUi(const bool& data);
                void onUiUpdate(bool& data);
                void SetTooltip(const std::string& tooltip);

              protected:
                Wt::WCheckBox* _check_box;
            };

        } // namespace wt
    }     // namespace UI
} // namespace mo

max_stars_repo_name: dtmoodie/MetaObject

max_issues_repo_name: dtmoodie/MetaObject

max_forks_repo_name: dtmoodie/MetaObject


text:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//

// Test that header file is self-contained.
#include <boost/beast/zlib/deflate_stream.hpp>

#include <boost/beast/core/string.hpp>
#include <boost/beast/_experimental/unit_test/suite.hpp>
#include <array>
#include <cstdint>
#include <numeric>
#include <random>

#include "zlib-1.2.11/zlib.h"

namespace boost {
namespace beast {
namespace zlib {

class deflate_stream_test : public beast::unit_test::suite
{
public:
    // Lots of repeats, limited char range
    static
    std::string
    corpus1(std::size_t n)
    {
        static std::string const alphabet{
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        };
        std::string s;
        s.reserve(n + 5);
        std::mt19937 g;
        std::uniform_int_distribution<std::size_t> d0{
            0, alphabet.size() - 1};
        std::uniform_int_distribution<std::size_t> d1{
            1, 5};
        while(s.size() < n)
        {
            auto const rep = d1(g);
            auto const ch = alphabet[d0(g)];
            s.insert(s.end(), rep, ch);
        }
        s.resize(n);
        return s;
    }

    // Random data
    static
    std::string
    corpus2(std::size_t n)
    {
        std::string s;
        s.reserve(n);
        std::mt19937 g;
        std::uniform_int_distribution<std::uint32_t> d0{0, 255};
        while(n--)
            s.push_back(static_cast<char>(d0(g)));
        return s;
    }

    static
    std::string
    compress(
        string_view const& in,
        int level,                  // 0=none, 1..9, -1=default
        int windowBits,             // 9..15
        int memLevel)               // 1..9 (8=default)
    {
        int const strategy = Z_DEFAULT_STRATEGY;
        int result;
        z_stream zs;
        memset(&zs, 0, sizeof(zs));
        result = deflateInit2(
            &zs,
            level,
            Z_DEFLATED,
            -windowBits,
            memLevel,
            strategy);
        if(result != Z_OK)
            throw std::logic_error{"deflateInit2 failed"};
        zs.next_in = (Bytef*)in.data();
        zs.avail_in = static_cast<uInt>(in.size());
        std::string out;
        out.resize(deflateBound(&zs,
            static_cast<uLong>(in.size())));
        zs.next_in = (Bytef*)in.data();
        zs.avail_in = static_cast<uInt>(in.size());
        zs.next_out = (Bytef*)&out[0];
        zs.avail_out = static_cast<uInt>(out.size());
        result = deflate(&zs, Z_FULL_FLUSH);
        if(result != Z_OK)
            throw std::logic_error("deflate failed");
        out.resize(zs.total_out);
        deflateEnd(&zs);
        return out;
    }

    static
    std::string
    decompress(string_view const& in)
    {
        int result;
        std::string out;
        z_stream zs;
        memset(&zs, 0, sizeof(zs));
        result = inflateInit2(&zs, -15);
        if(result != Z_OK)
            throw std::logic_error{"inflateInit2 failed"};
        try
        {
            zs.next_in = (Bytef*)in.data();
            zs.avail_in = static_cast<uInt>(in.size());
            for(;;)
            {
                out.resize(zs.total_out + 1024);
                zs.next_out = (Bytef*)&out[zs.total_out];
                zs.avail_out = static_cast<uInt>(
                    out.size() - zs.total_out);
                result = inflate(&zs, Z_SYNC_FLUSH);
                if( result == Z_NEED_DICT ||
                    result == Z_DATA_ERROR ||
                    result == Z_MEM_ERROR)
                {
                    throw std::logic_error("inflate failed");
                }
                if(zs.avail_out > 0)
                    break;
                if(result == Z_STREAM_END)
                    break;
            }
            out.resize(zs.total_out);
            inflateEnd(&zs);
        }
        catch(...)
        {
            inflateEnd(&zs);
            throw;
        }
        return out;
    }

    //--------------------------------------------------------------------------

    using self = deflate_stream_test;
    typedef void(self::*pmf_t)(
        int level, int windowBits, int memLevel,
        int strategy, std::string const&);

    static
    Strategy
    toStrategy(int strategy)
    {
        switch(strategy)
        {
        default:
        case 0: return Strategy::normal;
        case 1: return Strategy::filtered;
        case 2: return Strategy::huffman;
        case 3: return Strategy::rle;
        case 4: return Strategy::fixed;
        }
    }

    void
    doDeflate1_beast(
        int level, int windowBits, int memLevel,
        int strategy, std::string const& check)
    {
        std::string out;
        z_params zs;
        deflate_stream ds;
        ds.reset(
            level,
            windowBits,
            memLevel,
            toStrategy(strategy));
        out.resize(ds.upper_bound(
            static_cast<uLong>(check.size())));
        zs.next_in = (Bytef*)check.data();
        zs.avail_in = static_cast<uInt>(check.size());
        zs.next_out = (Bytef*)out.data();
        zs.avail_out = static_cast<uInt>(out.size());
        {
            bool progress = true;
            for(;;)
            {
                error_code ec;
                ds.write(zs, Flush::full, ec);
                if( ec == error::need_buffers ||
                    ec == error::end_of_stream) // per zlib FAQ
                    goto fin;
                if(! BEAST_EXPECTS(! ec, ec.message()))
                    goto err;
                if(! BEAST_EXPECT(progress))
                    goto err;
                progress = false;
            }
        }

    fin:
        out.resize(zs.total_out);
        BEAST_EXPECT(decompress(out) == check);

    err:
        ;
    }

    //--------------------------------------------------------------------------

    void
    doDeflate2_beast(
        int level, int windowBits, int memLevel,
        int strategy, std::string const& check)
    {
        for(std::size_t i = 1; i < check.size(); ++i)
        {
            for(std::size_t j = 1;; ++j)
            {
                z_params zs;
                deflate_stream ds;
                ds.reset(
                    level,
                    windowBits,
                    memLevel,
                    toStrategy(strategy));
                std::string out;
                out.resize(ds.upper_bound(
                    static_cast<uLong>(check.size())));
                if(j >= out.size())
                    break;
                zs.next_in = (Bytef*)check.data();
                zs.avail_in = static_cast<uInt>(i);
                zs.next_out = (Bytef*)out.data();
                zs.avail_out = static_cast<uInt>(j);
                bool bi = false;
                bool bo = false;
                for(;;)
                {
                    error_code ec;
                    ds.write(zs,
                        bi ? Flush::full : Flush::none, ec);
                    if( ec == error::need_buffers ||
                        ec == error::end_of_stream) // per zlib FAQ
                        goto fin;
                    if(! BEAST_EXPECTS(! ec, ec.message()))
                        goto err;
                    if(zs.avail_in == 0 && ! bi)
                    {
                        bi = true;
                        zs.avail_in =
                            static_cast<uInt>(check.size() - i);
                    }
                    if(zs.avail_out == 0 && ! bo)
                    {
                        bo = true;
                        zs.avail_out =
                            static_cast<uInt>(out.size() - j);
                    }
                }

            fin:
                out.resize(zs.total_out);
                BEAST_EXPECT(decompress(out) == check);

            err:
                ;
            }
        }
    }

    //--------------------------------------------------------------------------

    void
    doMatrix(std::string const& check, pmf_t pmf)
    {
        for(int level = 0; level <= 9; ++level)
        {
            for(int windowBits = 8; windowBits <= 9; ++windowBits)
            {
                // zlib has a bug with windowBits==8
                if(windowBits == 8)
                    continue;
                for(int strategy = 0; strategy <= 4; ++strategy)
                {
                    for (int memLevel = 8; memLevel <= 9; ++memLevel)
                    {
                        (this->*pmf)(
                                level, windowBits, memLevel, strategy, check);
                    }
                }
            }
        }

        // Check default settings
        (this->*pmf)(compression::default_size, 15, 8, 0, check);
    }

    void
    testDeflate()
    {
        doMatrix("Hello, world!", &self::doDeflate1_beast);
        doMatrix("Hello, world!", &self::doDeflate2_beast);
        doMatrix(corpus1(56), &self::doDeflate2_beast);
        doMatrix(corpus1(1024), &self::doDeflate1_beast);
    }

    void testInvalidSettings()
    {
        except<std::invalid_argument>(
            []()
            {
                deflate_stream ds;
                ds.reset(-42, 15, 8, Strategy::normal);
            });
        except<std::invalid_argument>(
            []()
            {
                deflate_stream ds;
                ds.reset(compression::default_size, -1, 8, Strategy::normal);
            });
        except<std::invalid_argument>(
            []()
            {
                deflate_stream ds;
                ds.reset(compression::default_size, 15, -1, Strategy::normal);
            });
        except<std::invalid_argument>(
            []()
            {
                deflate_stream ds;
                ds.reset();
                z_params zp{};
                zp.avail_in = 1;
                zp.next_in = nullptr;
                error_code ec;
                ds.write(zp, Flush::full, ec);
            });
    }

    void
    testWriteAfterFinish()
    {
        z_params zp;
        deflate_stream ds;
        ds.reset();
        std::string out;
        out.resize(1024);
        string_view s = "Hello";
        zp.next_in = s.data();
        zp.avail_in = s.size();
        zp.next_out = &out.front();
        zp.avail_out = out.size();
        error_code ec;
        ds.write(zp, Flush::sync, ec);
        BEAST_EXPECT(!ec);
        zp.next_in = nullptr;
        zp.avail_in = 0;
        ds.write(zp, Flush::finish, ec);
        BEAST_EXPECT(ec == error::end_of_stream);
        zp.next_in = s.data();
        zp.avail_in = s.size();
        zp.next_out = &out.front();
        zp.avail_out = out.size();
        ds.write(zp, Flush::sync, ec);
        BEAST_EXPECT(ec == error::stream_error);
        ds.write(zp, Flush::finish, ec);
        BEAST_EXPECT(ec == error::need_buffers);
    }

    void
    testFlushPartial()
    {
        z_params zp;
        deflate_stream ds;
        ds.reset();
        std::string out;
        out.resize(1024);
        string_view s = "Hello";
        zp.next_in = s.data();
        zp.avail_in = s.size();
        zp.next_out = &out.front();
        zp.avail_out = out.size();
        error_code ec;
        ds.write(zp, Flush::none, ec);
        BEAST_EXPECT(!ec);
        ds.write(zp, Flush::partial, ec);
        BEAST_EXPECT(!ec);
    }

    void
    testFlushAtLiteralBufferFull()
    {
        struct fixture
        {
            explicit fixture(std::size_t n, Strategy s)
            {
                ds.reset(8, 15, 1, s);
                std::iota(in.begin(), in.end(), 0);
                out.resize(n);
                zp.next_in = in.data();
                zp.avail_in = in.size();
                zp.next_out = &out.front();
                zp.avail_out = out.size();
            }

            z_params zp;
            deflate_stream ds;
            std::array<std::uint8_t, 255> in;
            std::string out;
        };

        for (auto s : {Strategy::huffman, Strategy::rle, Strategy::normal})
        {
            {
                fixture f{264, s};
                error_code ec;
                f.ds.write(f.zp, Flush::finish, ec);
                BEAST_EXPECT(ec == error::end_of_stream);
                BEAST_EXPECT(f.zp.avail_out == 1);
            }

            {
                fixture f{263, s};
                error_code ec;
                f.ds.write(f.zp, Flush::finish, ec);
                BEAST_EXPECT(!ec);
                BEAST_EXPECT(f.zp.avail_out == 0);
            }

            {
                fixture f{20, s};
                error_code ec;
                f.ds.write(f.zp, Flush::sync, ec);
                BEAST_EXPECT(!ec);
            }

        }
    }

    void
    testRLEMatchLengthExceedLookahead()
    {
        z_params zp;
        deflate_stream ds;
        std::vector<std::uint8_t> in;
        in.resize(300);

        ds.reset(8, 15, 1, Strategy::rle);
        std::fill_n(in.begin(), 4, 'a');
        std::string out;
        out.resize(in.size() * 2);
        zp.next_in = in.data();
        zp.avail_in = in.size();
        zp.next_out = &out.front();
        zp.avail_out = out.size();

        error_code ec;
        ds.write(zp, Flush::sync, ec);
        BEAST_EXPECT(!ec);
    }

    void
    testFlushAfterDistMatch()
    {
        for (auto out_size : {144, 129})
        {
            z_params zp;
            deflate_stream ds;
            std::array<std::uint8_t, 256> in{};
            // 125 will mostly fill the lit buffer, so emitting a distance code
            // results in a flush.
            auto constexpr n = 125;
            std::iota(in.begin(), in.begin() + n, 0);
            std::iota(in.begin() + n, in.end(), 0);

            ds.reset(8, 15, 1, Strategy::normal);
            std::string out;
            out.resize(out_size);
            zp.next_in = in.data();
            zp.avail_in = in.size();
            zp.next_out = &out.front();
            zp.avail_out = out.size();

            error_code ec;
            ds.write(zp, Flush::sync, ec);
            BEAST_EXPECT(!ec);
        }
    }

    void
    run() override
    {
        log <<
            "sizeof(deflate_stream) == " <<
            sizeof(deflate_stream) << std::endl;

        testDeflate();
        testInvalidSettings();
        testWriteAfterFinish();
        testFlushPartial();
        testFlushAtLiteralBufferFull();
        testRLEMatchLengthExceedLookahead();
        testFlushAfterDistMatch();
    }
};

BEAST_DEFINE_TESTSUITE(beast,zlib,deflate_stream);

} // zlib
} // beast
} // boost

ext: cpp

max_stars_repo_name: eliot-exdev/boost-beast

max_issues_repo_name: eliot-exdev/boost-beast

max_forks_repo_name: eliot-exdev/boost-beast


text:
/*

Copyright (c) 2005-2017, University of Oxford.
All rights reserved.

University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.

This file is part of Chaste.

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 the University of Oxford nor the names of its
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef ABSTRACTSTIMULUSFACTORY_HPP_
#define ABSTRACTSTIMULUSFACTORY_HPP_

#include <boost/shared_ptr.hpp>

#include "AbstractStimulusFunction.hpp"
#include "AbstractTetrahedralMesh.hpp"
#include "AbstractIvpOdeSolver.hpp"
#include "ZeroStimulus.hpp"
#include "AbstractChasteRegion.hpp"
#include "BoundaryConditionsContainer.hpp"
#include "Node.hpp"

/**
 * Abstract class that specifies a stimulus factory.
 * The core method is CreateStimulusForNode which creates a stimulus object at each node in the mesh.
 * The default implementation (here) specifies a ZeroStimulus. child classes may override this method.
 *
 * The other crucial method is SetCompatibleExtracellularStimulus which ensures that the stimulus specified obeys compatibility conditions.
 * The implementation here is empty (compatible with ZeroStimulus which implicitly obeys compatibility conditions).
 * child classes may over-ride the method.
 */
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM = ELEMENT_DIM>
class AbstractStimulusFactory
{
protected:

    /**
     * The mesh, set by the problem class
     */
    AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* mpMesh;

    /**Vector of regions of nodes to be grounded*/
    std::vector<AbstractChasteRegion<SPACE_DIM>* > mGroundedRegions;

public:

    /**
     * @return a stimulus object for the given node.
     * Default implementation here returns a zero stimulus.
     *
     *  May be overridden by child classes.
     *
     * @param pNode  pointer to the node object
     */
    virtual boost::shared_ptr<AbstractStimulusFunction> CreateStimulusForNode(Node<SPACE_DIM>* pNode);

    /**
     * @return  The number of cells
     */
    virtual unsigned GetNumberOfCells();

    /**
     * Empty default implementation that is compatible with the
     * default implementation of CreateStimulusForNode (i.e., empty implementation for zero stimulus).
     *
     * If needed, over-ride this
     */
    virtual void SetCompatibleExtracellularStimulus();

    /**
     * Default constructor.
     */
    AbstractStimulusFactory();

    /**
     * Destructor
     */
     virtual ~AbstractStimulusFactory();

    /**
     * @param pMesh  the mesh for which to create stimuli.
     */
    void SetMesh(AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* pMesh);

    /**
     * @return  the mesh used to create the stimuli.
     */
    AbstractTetrahedralMesh<ELEMENT_DIM,SPACE_DIM>* GetMesh();

//    /*
//     * Allow specification of a chaste region where nodes have extracellular potential grounded
//     *
//     * @param pRegion the region to be grounded.
//     */
//    void SetRegionToBeGrounded(AbstractChasteRegion<SPACE_DIM>* pRegion);

    /**
     * @return access to the variable mGroundedRegions which
     * stores the regions to be grounded
     */
    std::vector<AbstractChasteRegion<SPACE_DIM>* > GetRegionsToBeGrounded();
};

#endif /*ABSTRACTSTIMULUSFACTORY_HPP_*/

ext: hpp

max_stars_repo_name: gonayl/Chaste

max_issues_repo_name: gonayl/Chaste

max_forks_repo_name: gonayl/Chaste


text:
#include <iostream>
#include <csignal>
#include <boost/program_options.hpp>
#include <kspp/topology_builder.h>
#include <kspp/sources/kafka_source.h>
#include <kspp/utils/env.h>
#include <kspp/utils/kafka_utils.h>
#include <kspp/connect/postgres/postgres_generic_avro_sink.h>
#include <kspp/processors/transform.h>
#include <kspp/metrics/prometheus_pushgateway_reporter.h>
#include <kspp/utils/string_utils.h>

#define SERVICE_NAME "kafka2postgres"

using namespace std::chrono_literals;
using namespace kspp;

static bool run = true;

static void sigterm(int sig) {
  run = false;
}

int main(int argc, char **argv) {
  FLAGS_logtostderr = 1;
  google::InitGoogleLogging(argv[0]);

  boost::program_options::options_description desc("options");
  desc.add_options()
      ("help", "produce help message")
      ("app_realm", boost::program_options::value<std::string>()->default_value(get_env_and_log("APP_REALM", "DEV")), "app_realm")
      ("topic", boost::program_options::value<std::string>(), "topic")
      ("partition_list", boost::program_options::value<std::string>()->default_value("[-1]"), "partition_list")
      ("start_offset", boost::program_options::value<std::string>()->default_value("OFFSET_BEGINNING"), "start_offset")
      ("postgres_host", boost::program_options::value<std::string>()->default_value(get_env_and_log("POSTGRES_HOST")), "postgres_host")
      ("postgres_port", boost::program_options::value<int32_t>()->default_value(5432), "postgres_port")
      ("postgres_user", boost::program_options::value<std::string>()->default_value(get_env_and_log("POSTGRES_USER")), "postgres_user")
      ("postgres_password", boost::program_options::value<std::string>()->default_value(get_env_and_log_hidden("POSTGRES_PASSWORD")), "postgres_password")
      ("postgres_dbname", boost::program_options::value<std::string>()->default_value(get_env_and_log("POSTGRES_DBNAME")), "postgres_dbname")
      ("postgres_max_items_in_insert", boost::program_options::value<int32_t>()->default_value(1000), "postgres_max_items_in_insert")
      ("postgres_warning_timeout", boost::program_options::value<int32_t>()->default_value(1000), "postgres_warning_timeout")
      ("postgres_disable_delete", boost::program_options::value<int32_t>(), "postgres_disable_delete")
      ("id_column", boost::program_options::value<std::string>()->default_value("id"), "id_column")
      ("table_prefix", boost::program_options::value<std::string>()->default_value("kafka_"), "table_prefix")
      ("character_encoding", boost::program_options::value<std::string>()->default_value("UTF8"), "character_encoding")
      ("table_name_override", boost::program_options::value<std::string>(), "table_name_override")
      ("consumer_group", boost::program_options::value<std::string>()->default_value(get_env_and_log("CONSUMER_GROUP", "")), "consumer_group")
      ("metrics_namespace", boost::program_options::value<std::string>()->default_value(get_env_and_log("METRICS_NAMESPACE", "bb")),"metrics_namespace")
      ;

  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
  boost::program_options::notify(vm);

  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return 0;
  }

  std::string consumer_group;
  if (vm.count("consumer_group")) {
    consumer_group = vm["consumer_group"].as<std::string>();
  }

  auto config = std::make_shared<kspp::cluster_config>(consumer_group);
  config->load_config_from_env();

  std::string app_realm;
  if (vm.count("app_realm")) {
    app_realm = vm["app_realm"].as<std::string>();
  }

  std::string topic;
  if (vm.count("topic")) {
    topic = vm["topic"].as<std::string>();
  } else {
    std::cout << "--topic must be specified" << std::endl;
    return 0;
  }

  std::vector<int> partition_list;
  if (vm.count("partition_list")) {
    auto s = vm["partition_list"].as<std::string>();
    partition_list = kspp::parse_partition_list(s);
  }

  kspp::start_offset_t start_offset=kspp::OFFSET_BEGINNING;
  try {
    if (vm.count("start_offset"))
      start_offset = kspp::to_offset(vm["start_offset"].as<std::string>());
  }
  catch(std::exception& e) {
    std::cerr << "start_offset must be one of OFFSET_BEGINNING / OFFSET_END / OFFSET_STORED";
    return -1;
  }

  std::string postgres_host;
  if (vm.count("postgres_host")) {
    postgres_host = vm["postgres_host"].as<std::string>();
  }

  int postgres_port;
  if (vm.count("postgres_port")) {
    postgres_port = vm["postgres_port"].as<int>();
  }

  std::string postgres_dbname;
  if (vm.count("postgres_dbname")) {
    postgres_dbname = vm["postgres_dbname"].as<std::string>();
  }

  std::string postgres_user;
  if (vm.count("postgres_user")) {
    postgres_user = vm["postgres_user"].as<std::string>();
  }

  std::string postgres_password;
  if (vm.count("postgres_password")) {
    postgres_password = vm["postgres_password"].as<std::string>();
  }

  int postgres_max_items_in_insert;
  if (vm.count("postgres_max_items_in_insert")) {
    postgres_max_items_in_insert = vm["postgres_max_items_in_insert"].as<int>();
  }

  int postgres_warning_timeout;
  if (vm.count("postgres_warning_timeout")) {
    postgres_warning_timeout = vm["postgres_warning_timeout"].as<int>();
  }

  std::string id_column;
  if (vm.count("id_column")) {
    id_column = vm["id_column"].as<std::string>();
  }

  std::string table_prefix;
  if (vm.count("table_prefix")) {
    table_prefix = vm["table_prefix"].as<std::string>();
  }

  std::string table_name_override;
  if (vm.count("table_name_override")) {
    table_name_override = vm["table_name_override"].as<std::string>();
  }

  std::string character_encoding;
  if (vm.count("character_encoding")) {
    character_encoding = vm["character_encoding"].as<std::string>();
  } else {
    std::cout << "--character_encoding must be specified" << std::endl;
    return 0;
  }

  bool postgres_disable_delete=false;
  if (vm.count("postgres_disable_delete")) {
    postgres_disable_delete = (vm["postgres_disable_delete"].as<int>() > 0);
  }

  std::string metrics_namespace;
  if (vm.count("metrics_namespace")) {
    metrics_namespace = vm["metrics_namespace"].as<std::string>();
  }

  config->set_producer_buffering_time(1000ms);
  config->set_consumer_buffering_time(500ms);
  config->validate();
  config->log();
  auto s= config->avro_serdes();

  std::string table_name = table_prefix + topic;

  if (table_name_override.size())
    table_name=table_name_override;

  LOG(INFO) << "app_realm                    : " << app_realm;
  LOG(INFO) << "topic                        : " << topic;
  LOG(INFO) << "start_offset                 : " << kspp::to_string(start_offset);
  LOG(INFO) << "postgres_host                : " << postgres_host;
  LOG(INFO) << "postgres_port                : " << postgres_port;
  LOG(INFO) << "postgres_dbname              : " << postgres_dbname;
  LOG(INFO) << "postgres_user                : " << postgres_user;
  LOG(INFO) << "postgres_password            : " << "[hidden]";
  LOG(INFO) << "postgres_max_items_in_insert : " << postgres_max_items_in_insert;
  LOG(INFO) << "id_column                    : " << id_column;
  LOG(INFO) << "postgres_warning_timeout     : " << postgres_warning_timeout;
  LOG(INFO) << "table_prefix                 : " << table_prefix;
  LOG(INFO) << "table_name_override          : " << table_name_override;
  LOG(INFO) << "table_name                   : " << table_name;
  LOG(INFO) << "character_encoding           : " << character_encoding;
  LOG(INFO) << "postgres_disable_delete      : " << postgres_disable_delete;
  LOG(INFO) << "pushgateway_uri              : " << config->get_pushgateway_uri();
  LOG(INFO) << "metrics_namespace            : " << metrics_namespace;

  kspp::connect::connection_params connection_params;
  connection_params.host = postgres_host;
  connection_params.port = postgres_port;
  connection_params.user = postgres_user;
  connection_params.password = postgres_password;
  connection_params.database_name = postgres_dbname;

  LOG(INFO) << "discovering facts...";

  auto nr_of_partitions = kspp::kafka::get_number_partitions(config, topic);
  if (partition_list.size() == 0 || partition_list[0] == -1)
    partition_list = kspp::get_partition_list(nr_of_partitions);
  LOG(INFO) << "partition_list   : " << kspp::partition_list_to_string(partition_list);
  kspp::topology_builder builder(config);
  auto topology = builder.create_topology();

  auto source0 = topology->create_processors<kspp::kafka_source<kspp::generic_avro, kspp::generic_avro, kspp::avro_serdes, kspp::avro_serdes>>(partition_list, topic, config->avro_serdes(), config->avro_serdes());
  /*https://www.postgresql.org/docs/9.3/static/multibyte.html*/
  /*auto transform = topology->create_processors<kspp::flat_map<kspp::generic_avro, kspp::generic_avro, kspp::generic_avro, kspp::generic_avro>>(
      source0, [](const kspp::krecord<kspp::generic_avro, kspp::generic_avro>& in, auto self) {
        insert(self, in);
      });
  */
  std::vector<std::string> keys = { id_column };

  topology->create_sink<kspp::postgres_generic_avro_sink>(source0, table_name, connection_params, keys, character_encoding, postgres_max_items_in_insert, postgres_disable_delete);

  std::string hostname = default_hostname();

  topology->add_labels( {
                            { "app_name", SERVICE_NAME },
                            { "app_realm", app_realm },
                            { "hostname", hostname },
                            { "db_host", postgres_host },
                            { "dst_table", table_name }
                        });

  topology->start(start_offset);

  std::signal(SIGINT, sigterm);
  std::signal(SIGTERM, sigterm);
  std::signal(SIGPIPE, SIG_IGN);

  LOG(INFO) << "status is up";

  {
    auto metrics_reporter = std::make_shared<kspp::prometheus_pushgateway_reporter>(metrics_namespace, config->get_pushgateway_uri()) << topology;
    int64_t next_exit_check = kspp::milliseconds_since_epoch() + 10000;
    while (run) {
      if (topology->process(kspp::milliseconds_since_epoch()) == 0) {
        std::this_thread::sleep_for(10ms);
        topology->commit(false);
      }

      if (kspp::milliseconds_since_epoch()>next_exit_check){
        if (!topology->good()){
          LOG(ERROR) << "NODES IN ERROR STATE - EXITING";
          run=false;
        }
        next_exit_check = kspp::milliseconds_since_epoch() + 10000;
      }
    }
  }

  topology->commit(true);
  topology->close();
  LOG(INFO) << "status is down";
  return 0;
}


text: #include <boost/bimap/container_adaptor/list_adaptor.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

#include "primitives/transaction.h"
#include "main.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(main_tests)

CAmount nMoneySupplyPoWEnd = 30000000 * COIN;

BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
    CAmount nSum = 0;
    for (int nHeight = 0; nHeight < 1; nHeight += 1) {
        /* premine in block 1 */
        CAmount nSubsidy = GetBlockValue(nHeight);
        BOOST_CHECK(nSubsidy <= 100000 * COIN);
        nSum += nSubsidy;
    }

    for (int nHeight = 1; nHeight < 2000; nHeight += 1) {
        CAmount nSubsidy = GetBlockValue(nHeight);
        BOOST_CHECK(nSubsidy <= 1 * COIN);
        nSum += nSubsidy;
    }
    for (int nHeight = 2000; nHeight < 40000; nHeight += 1) {
        CAmount nSubsidy = GetBlockValue(nHeight);
        BOOST_CHECK(nSubsidy <= 2 * COIN);
        nSum += nSubsidy;
    }
    for (int nHeight = 40000; nHeight < 60000; nHeight += 1) {
        CAmount nSubsidy = GetBlockValue(nHeight);
        BOOST_CHECK(nSubsidy <= 10 * COIN);
        nSum += nSubsidy;

    }
    for (int nHeight = 60000; nHeight < 80000; nHeight += 1) {
        CAmount nSubsidy = GetBlockValue(nHeight);
        BOOST_CHECK(nSubsidy <= 7 * COIN);
        nSum += nSubsidy;

    }
	    for (int nHeight = 80000; nHeight < 1000000; nHeight += 1) {
        CAmount nSubsidy = GetBlockValue(nHeight);
        BOOST_CHECK(nSubsidy <= 5 * COIN);
        nSum += nSubsidy;

    }
	BOOST_CHECK(nSum > 0 && nSum <= nMoneySupplyPoWEnd);
}

BOOST_AUTO_TEST_SUITE_END()


text: #include <boost/type_erasure/dynamic_any_cast.hpp>


text:
//  Boost operations_test.cpp  ---------------------------------------------------------//

//  Copyright Alexander Grund 2020

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  Library home page: http://www.boost.org/libs/filesystem

#include <iostream>

#if defined(BOOST_FILESYSTEM_HAS_MKLINK)

#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>
#include <boost/core/lightweight_test.hpp>
#include <cstdlib>
#include <vector>

namespace fs = boost::filesystem;

struct TmpDir
{
    fs::path path;
    TmpDir(const fs::path& base) :
        path(fs::absolute(base) / fs::unique_path())
    {
        fs::create_directories(path);
    }
    ~TmpDir()
    {
        boost::system::error_code ec;
        fs::remove_all(path, ec);
    }
};

// Test fs::canonical for various path in a Windows directory junction point
// This failed before due to broken handling of absolute paths and ignored ReparseTag
int main()
{

    const fs::path cwd = fs::current_path();
    const TmpDir tmp(cwd);
    const fs::path junction = tmp.path / "junction";
    const fs::path real = tmp.path / "real";
    const fs::path subDir = "sub";
    fs::create_directories(real / subDir);
    fs::current_path(tmp.path);
    BOOST_TEST(std::system("mklink /j junction real") == 0);
    BOOST_TEST(fs::exists(junction));

    // Due to a bug there was a dependency on the current path so try the below for all:
    std::vector< fs::path > paths;
    paths.push_back(cwd);
    paths.push_back(junction);
    paths.push_back(real);
    paths.push_back(junction / subDir);
    paths.push_back(real / subDir);
    for (std::vector< fs::path >::iterator it = paths.begin(); it != paths.end(); ++it)
    {
        std::cout << "Testing in " << *it << std::endl;
        fs::current_path(*it);

        // Used by canonical, must work too
        BOOST_TEST(fs::read_symlink(junction) == real);

        BOOST_TEST(fs::canonical(junction) == real);
        BOOST_TEST(fs::canonical(junction / subDir) == real / subDir);
    }

    // Restore the original current directory so that temp directory can be removed
    fs::current_path(cwd);

    return boost::report_errors();
}

#else // defined(BOOST_FILESYSTEM_HAS_MKLINK)

int main()
{
    std::cout << "Skipping test as the target system does not support mklink." << std::endl;
    return 0;
}

#endif // defined(BOOST_FILESYSTEM_HAS_MKLINK)

max_stars_repo_name: Mu-L/arangodb

max_issues_repo_name: Mu-L/arangodb

max_forks_repo_name: Mu-L/arangodb


text:
/*
 (c) 2014 Glen Joseph Fernandes
 glenjofe at gmail dot com

 Distributed under the Boost Software
 License, Version 1.0.
 http://boost.org/LICENSE_1_0.txt
*/
#ifndef BOOST_ALIGN_DETAIL_ADDRESS_HPP
#define BOOST_ALIGN_DETAIL_ADDRESS_HPP

#include <boost/cstdint.hpp>
#include <cstddef>

namespace boost {
    namespace alignment {
        namespace detail {
#if defined(BOOST_HAS_INTPTR_T)
            typedef boost::uintptr_t address_t;
#else
            typedef std::size_t address_t;
#endif
        }
    }
}

#endif

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
// Copyright (C) 2011-2012 by the Bem++ Authors
//
// 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.

#include "../common/common.hpp"

// Keep IDEs happy
#include "default_local_assembler_for_local_operators_on_surfaces.hpp"

#include <boost/tuple/tuple_comparison.hpp>

namespace Fiber
{

template <typename BasisFunctionType, typename ResultType, typename GeometryFactory>
DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType, ResultType, GeometryFactory>::
DefaultLocalAssemblerForLocalOperatorsOnSurfaces(
    const shared_ptr<const GeometryFactory>& geometryFactory,
    const shared_ptr<const RawGridGeometry<CoordinateType> >& rawGeometry,
    const shared_ptr<const std::vector<const Basis<BasisFunctionType>*> >& testBases,
    const shared_ptr<const std::vector<const Basis<BasisFunctionType>*> >& trialBases,
    const shared_ptr<const CollectionOfBasisTransformations<CoordinateType> >& testTransformations,
    const shared_ptr<const CollectionOfBasisTransformations<CoordinateType> >& trialTransformations,
    const shared_ptr<const TestTrialIntegral<BasisFunctionType, ResultType> >& integral,
    const shared_ptr<const OpenClHandler>& openClHandler) :
    m_geometryFactory(geometryFactory),
    m_rawGeometry(rawGeometry),
    m_testBases(testBases),
    m_trialBases(trialBases),
    m_testTransformations(testTransformations),
    m_trialTransformations(trialTransformations),
    m_integral(integral),
    m_openClHandler(openClHandler)
{
    Utilities::checkConsistencyOfGeometryAndBases(*rawGeometry, *testBases);
    Utilities::checkConsistencyOfGeometryAndBases(*rawGeometry, *trialBases);
}

template <typename BasisFunctionType, typename ResultType, typename GeometryFactory>
void
DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType, ResultType, GeometryFactory>::
evaluateLocalWeakForms(
    CallVariant callVariant,
    const std::vector<int>& elementIndicesA,
    int elementIndexB,
    LocalDofIndex localDofIndexB,
    std::vector<arma::Mat<ResultType> >& result,
    CoordinateType nominalDistance)
{
    // Probably will never be called
    throw std::runtime_error("DefaultLocalAssemblerForLocalOperatorsOnSurfaces::"
                             "evaluateLocalWeakForms(): "
                             "this overload not implemented yet");
}

template <typename BasisFunctionType, typename ResultType, typename GeometryFactory>
void
DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType, ResultType, GeometryFactory>::
evaluateLocalWeakForms(
    const std::vector<int>& testElementIndices,
    const std::vector<int>& trialElementIndices,
    Fiber::_2dArray<arma::Mat<ResultType> >& result,
    CoordinateType nominalDistance)
{
    // Probably will never be called
    throw std::runtime_error("DefaultLocalAssemblerForLocalOperatorsOnSurfaces::"
                             "evaluateLocalWeakForms(): "
                             "this overload not implemented yet");
}

template <typename BasisFunctionType, typename ResultType, typename GeometryFactory>
void
DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType, ResultType, GeometryFactory>::
evaluateLocalWeakForms(
    const std::vector<int>& elementIndices,
    std::vector<arma::Mat<ResultType> >& result)
{
    // The only overload likely to be needed for identity operators
    typedef TestTrialIntegrator<BasisFunctionType, ResultType> Integrator;
    typedef Basis<BasisFunctionType> Basis;

    const int elementCount = elementIndices.size();
    result.resize(elementCount);

    // Select integrator for each element
    typedef boost::tuples::tuple<const Integrator*, const Basis*, const Basis*>
    QuadVariant;
    std::vector<QuadVariant> quadVariants(elementCount);
    for (int i = 0; i < elementCount; ++i) {
        const Integrator* integrator = &selectIntegrator(elementIndices[i]);
        quadVariants[i] = QuadVariant(integrator, (*m_testBases)[elementIndices[i]],
                                      (*m_trialBases)[elementIndices[i]]);
    }

    // Integration will proceed in batches of test elements having the same
    // "quadrature variant", i.e. integrator and bases

    // Find all the unique quadrature variants present
    typedef std::set<QuadVariant> QuadVariantSet;
    // Set of unique quadrature variants
    QuadVariantSet uniqueQuadVariants(quadVariants.begin(), quadVariants.end());

    std::vector<int> activeElementIndices;
    activeElementIndices.reserve(elementCount);

    // Now loop over unique quadrature variants
    for (typename QuadVariantSet::const_iterator it = uniqueQuadVariants.begin();
            it != uniqueQuadVariants.end(); ++it) {
        const QuadVariant activeQuadVariant = *it;
        const Integrator& activeIntegrator = *it->template get<0>();
        const Basis& activeTestBasis  = *it->template get<1>();
        const Basis& activeTrialBasis = *it->template get<2>();

        // Find all the test elements for which quadrature should proceed
        // according to the current quadrature variant
        activeElementIndices.clear();
        for (int e = 0; e < elementCount; ++e)
            if (quadVariants[e] == activeQuadVariant)
                activeElementIndices.push_back(elementIndices[e]);

        // Integrate!
        arma::Cube<ResultType> localResult;
        activeIntegrator.integrate(activeElementIndices,
                                   activeTestBasis, activeTrialBasis,
                                   localResult);

        // Distribute the just calculated integrals into the result array
        // that will be returned to caller
        int i = 0;
        for (int e = 0; e < elementCount; ++e)
            if (quadVariants[e] == activeQuadVariant)
                result[e] = localResult.slice(i++);
    }
}

template <typename BasisFunctionType,
          typename ResultType, typename GeometryFactory>
typename DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType,
    ResultType, GeometryFactory>::CoordinateType
DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType,
    ResultType, GeometryFactory>::
estimateRelativeScale(CoordinateType minDist) const
{
    return 1.;
}

template <typename BasisFunctionType, typename ResultType, typename GeometryFactory>
const TestTrialIntegrator<BasisFunctionType, ResultType>&
DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType, ResultType, GeometryFactory>::
selectIntegrator(int elementIndex)
{
    SingleQuadratureDescriptor desc;

    // Get number of corners of the specified element
    desc.vertexCount = m_rawGeometry->elementCornerCount(elementIndex);

    // Determine integrand's order and required quadrature order
    const int expressionOrder =
        (*m_testBases)[elementIndex]->order() +
        (*m_trialBases)[elementIndex]->order();
    desc.order = ((expressionOrder + 1) + 1 /* round up */) / 2;

    return getIntegrator(desc);
}

template <typename BasisFunctionType, typename ResultType, typename GeometryFactory>
const TestTrialIntegrator<BasisFunctionType, ResultType>&
DefaultLocalAssemblerForLocalOperatorsOnSurfaces<BasisFunctionType, ResultType, GeometryFactory>::
getIntegrator(const SingleQuadratureDescriptor& desc)
{
    typename IntegratorMap::iterator it = m_testTrialIntegrators.find(desc);
    if (it != m_testTrialIntegrators.end()) {
//            std::cout << "getIntegrator(: " << index << "): integrator found" << std::endl;
        return *it->second;
    }
//        std::cout << "getIntegrator(: " << index << "): integrator not found" << std::endl;

    // Integrator doesn't exist yet and must be created.
    arma::Mat<CoordinateType> points;
    std::vector<CoordinateType> weights;
    fillSingleQuadraturePointsAndWeights(desc.vertexCount, desc.order,
                                         points, weights);

    typedef NumericalTestTrialIntegrator<BasisFunctionType, ResultType,
            GeometryFactory> Integrator;
    std::auto_ptr<TestTrialIntegrator<BasisFunctionType, ResultType> > integrator(
        new Integrator(points, weights,
                       *m_geometryFactory, *m_rawGeometry,
                       *m_testTransformations, *m_trialTransformations,
                       *m_integral,
                       *m_openClHandler));

    return *m_testTrialIntegrators.insert(desc, integrator).first->second;
}

} // namespace Fiber

max_stars_repo_name: UCL/bempp

max_issues_repo_name: UCL/bempp

max_forks_repo_name: UCL/bempp


text:
#include "do_config_internal.h"

#include <cstdio> // popen
#include <cstdlib> // calloc
#if defined(DO_CLIENT_AGENT)
#include <cstring> // strncpy
#include <sstream>
#include <string>

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

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "do_persistence.h"
#include "do_version.h"
#elif defined(DO_CLIENT_DOSVC)
#include "do_errors.h" // msdo::errc::e_not_impl
#endif

namespace msdo = microsoft::deliveryoptimization;

#if defined(DO_CLIENT_AGENT)
namespace msdoutil = microsoft::deliveryoptimization::util::details;

const char* const g_dosvcBinName = DOSVC_BIN_NAME;
const char* const g_doPluginAptBinName = DO_PLUGIN_APT_BIN_NAME;

static int WriteIoTConnectionStringToConfigFile(const char* value) noexcept
{
    int returnValue = 0;
    // ptree's exceptions do not provide an error code, and SDK has no logging of its own.
    // Return specific errors as a workaround.
    boost::filesystem::path filePath{microsoft::deliveryoptimization::details::GetConfigFilePath()};
    boost::system::error_code ec;
    if (boost::filesystem::exists(filePath.parent_path(), ec))
    {
        try
        {
            boost::property_tree::ptree configTree;
            configTree.put("ADUC_IoTConnectionString", value);

            // No other configs are used at this time so overwrite the whole file here
            boost::property_tree::write_json(filePath.string(), configTree);

            return 0;
        }
        catch (const boost::property_tree::ptree_bad_data&)
        {
            returnValue = -1;
        }
        catch (const boost::property_tree::ptree_bad_path&)
        {
            returnValue = -2;
        }
        catch (const boost::property_tree::ptree_error& pe)
        {
            returnValue = -3;
        }
        catch (const std::exception&)
        {
            returnValue = -4;
        }
    }
    else
    {
        returnValue = ec.value();
    }
    return returnValue;
}

static std::string GetSdkVersion()
{
    return msdoutil::ComponentVersion(false);
}

static std::string GetBinaryVersion(const boost::filesystem::path& binaryFilePath)
{
    std::string version;
    if (boost::filesystem::exists(binaryFilePath))
    {
        FILE* fp = nullptr;
        try
        {
            const std::string command = binaryFilePath.string() + " --version";
            fp = popen(command.c_str(), "r");
            if (fp == nullptr)
            {
                throw std::exception();
            }

            char readBuffer[256];
            constexpr auto cchBuffer = sizeof(readBuffer) / sizeof(readBuffer[0]);
            while (fgets(readBuffer, cchBuffer, fp) != nullptr)
            {
                readBuffer[cchBuffer - 1] = '\0';
                version += readBuffer;
            }

            boost::erase_all(version, "\n");
        }
        catch (const std::exception&)
        {
        }

        if (fp != nullptr)
        {
            (void)pclose(fp);
            fp = nullptr;
        }
    }
    return version;
}

static void AppendBinaryVersion(const char* binFileName, std::stringstream& allVersions)
{
    // Our binaries are normally installed to /usr/local/bin. However, check /usr/bin also
    // to cover special cases (for example, installed not via our deb/rpm packages).
    // We do not use bp::search_path() in order to avoid executing a malicious program with the
    // same name and which appears earlier in the PATH environment variable.
    boost::filesystem::path binFilePath("/usr/local/bin");
    binFilePath /= binFileName;
    std::string version = GetBinaryVersion(binFilePath);
    if (version.empty())
    {
        binFilePath = "/usr/bin";
        binFilePath /= binFileName;
        version = GetBinaryVersion(binFilePath);
    }

    if (!version.empty())
    {
        allVersions << ',' << version;
    }
}

static char* GetAllVersions()
{
    std::string allVersions;
    try
    {
        std::stringstream ss;
        ss << GetSdkVersion();
        if (*g_dosvcBinName != '\0')
        {
            AppendBinaryVersion(g_dosvcBinName, ss);
        }
        if (*g_doPluginAptBinName != '\0')
        {
            AppendBinaryVersion(g_doPluginAptBinName, ss);
        }
        allVersions = ss.str();
        // Caller knows they are getting DO versions, erase the redundant DO prefix
        boost::erase_all(allVersions, "deliveryoptimization-");
    }
    catch (const std::exception&)
    {
    }

    const size_t bufSize = (allVersions.size() + 1) * sizeof(std::string::value_type);
    auto pBuffer = reinterpret_cast<char*>(calloc(1, bufSize));
    if (pBuffer != nullptr)
    {
        strncpy(pBuffer, allVersions.c_str(), bufSize / sizeof(*pBuffer));
        pBuffer[bufSize - 1] = '\0';
    }
    return pBuffer;
}

int internal_set_iot_connection_string(const char* value)
{
    return WriteIoTConnectionStringToConfigFile(value);
}

char* internal_get_components_version()
{
    return GetAllVersions();
}

void internal_free_version_buf(char** ppBuffer)
{
    if (*ppBuffer)
    {
        free(*ppBuffer);
        *ppBuffer = NULL;
    }
}

#else // End DO_CLIENT_AGENT

int internal_set_iot_connection_string(const char* value)
{
    return static_cast<int>(msdo::errc::e_not_impl);
}

char* internal_get_components_version()
{
    return nullptr;
}

void internal_free_version_buf(char** ppBuffer)
{
    if (*ppBuffer)
    {
        free(*ppBuffer);
        *ppBuffer = NULL;
    }
}

#endif // End !DO_CLIENT_AGENT


text:
///////////////////////////////////////////////////////////////////////////\file
///
///   Copyright 2018 SINTEF AS
///
///   This Source Code Form is subject to the terms of the Mozilla
///   Public License, v. 2.0. If a copy of the MPL was not distributed
///   with this file, You can obtain one at https://mozilla.org/MPL/2.0/
///
////////////////////////////////////////////////////////////////////////////////

#include <csignal>
#include <iostream>
#include <unistd.h>
#include <string>
#include <vector>
#include <memory>

#include <boost/program_options.hpp>

#define BOOST_LOG_DYN_LINK

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>

#include <i3ds/communication.hpp>

#include "remoteproc_bridge.hpp"
#include "remoteproc_imu.hpp"

namespace po = boost::program_options;
namespace logging = boost::log;

volatile bool running;

void signal_handler(int signum)
{
  BOOST_LOG_TRIVIAL(info) << "Stopping " << signum;
  running = false;
}

int main(int argc, char *argv[])
{
  unsigned int node_id;
  std::string device;

  po::options_description desc("Allowed camera control options");
  desc.add_options()
  ("help,h", "Produce this message")
  ("node,n", po::value<unsigned int>(&node_id)->default_value(310), "Node ID of IMU")
  ("device,d", po::value<std::string>(&device)->default_value("/dev/rpmsg0"), "RemoteProc device")
  ("verbose,v", "Print verbose output")
  ("quiet,q", "Quiet ouput");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  if (vm.count("help"))
    {
      std::cout << desc << std::endl;
      return -1;
    }

  if (vm.count("quiet"))
    {
      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::warning);
    }
  else if (!vm.count("verbose"))
    {
      logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);
    }

  po::notify(vm);

  BOOST_LOG_TRIVIAL(info) << "Using node ID: " << node_id;

  printf("\r\n I3DS R5 IMU bridge \r\n");

  sleep(1);

  printf("\r\n Open rpmsg dev! \r\n");

  if (i3ds::remoteproc_open(device))
    {
      BOOST_LOG_TRIVIAL(error) << "Failed to open remoteproc: " << device;
      return -1;
    }

  i3ds::Context::Ptr context = i3ds::Context::Create();
  i3ds::Server server(context);

  i3ds::RemoteProcIMU imu(context, node_id);

  imu.Attach(server);

  running = true;
  signal(SIGINT, signal_handler);

  server.Start();

  while (running)
    {
      sleep(1);
    }

  server.Stop();

  i3ds::remoteproc_close();

  printf("\r\n Quitting application .. \r\n");
  printf(" I3DS R5 IMU bridge end \r\n");

  return 0;
}


text:
/**
 * g++ condvar.cc -std=c++11 -lboost_thread -lboost_system -lpthread
 * from https://svn.boost.org/trac/boost/attachment/ticket/7422/test.cc
 */

#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>

#include <condition_variable>
#include <future>
#include <limits>
#include <cstdio>
#include <thread>
#include <mutex>

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

namespace {

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

class Stopwatch
{
public:
    typedef long long nsec_t;

    static nsec_t now() {
        timespec ts;
        if(clock_gettime(CLOCK_MONOTONIC, &ts))
            abort();
        return ts.tv_sec * nsec_t(1000000000) + ts.tv_nsec;
    }

    Stopwatch()
        : start_(now())
    {}

    nsec_t elapsed() const {
        return now() - start_;
    }

private:
    nsec_t start_;
};

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

struct BoostTypes
{
    typedef boost::condition_variable condition_variable;
    typedef boost::mutex mutex;
    typedef boost::mutex::scoped_lock scoped_lock;
};

struct StdTypes
{
    typedef std::condition_variable condition_variable;
    typedef std::mutex mutex;
    typedef std::unique_lock<std::mutex> scoped_lock;
};

template<class Types>
struct SharedData : Types
{
    unsigned const iterations;
    unsigned counter;
    unsigned semaphore;
    typename Types::condition_variable cnd;
    typename Types::mutex mtx;
    Stopwatch::nsec_t producer_time;

    SharedData(unsigned iterations, unsigned consumers)
        : iterations(iterations)
        , counter()
        , semaphore(consumers) // Initialize to the number of consumers. (*)
        , producer_time()
    {}
};

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

template<class S>
void producer_thread(S* shared_data) {
    Stopwatch sw;

    unsigned const consumers = shared_data->semaphore; // (*)
    for(unsigned i = shared_data->iterations; i--;) {
        {
            typename S::scoped_lock lock(shared_data->mtx);
            // Wait till all consumers signal.
            while(consumers != shared_data->semaphore)
                shared_data->cnd.wait(lock);
            shared_data->semaphore = 0;
            // Signal consumers.
            ++shared_data->counter;
        }
        shared_data->cnd.notify_all();
    }

    shared_data->producer_time = sw.elapsed();
}

template<class S>
void consumer_thread(S* shared_data) {
    unsigned counter = 0;
    while(counter != shared_data->iterations) {
        {
            typename S::scoped_lock lock(shared_data->mtx);
            // Wait till the producer signals.
            while(counter == shared_data->counter)
                shared_data->cnd.wait(lock);
            counter = shared_data->counter;
            // Signal the producer.
            ++shared_data->semaphore;
        }
        shared_data->cnd.notify_all();
    }
}

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

template<class Types>
Stopwatch::nsec_t benchmark_ping_pong(unsigned consumer_count) {
    typedef SharedData<Types> S;

    auto best_producer_time = std::numeric_limits<Stopwatch::nsec_t>::max();

    std::vector<std::thread> consumers{consumer_count};

    // Run the benchmark 3 times and report the best time.
    for(int times = 3; times--;) {
        S shared_data{100000, consumer_count};

        // Start the consumers.
        for(unsigned i = 0; i < consumer_count; ++i)
            consumers[i] = std::thread{consumer_thread<S>, &shared_data};
        // Start the producer and wait till it finishes.
        std::thread{producer_thread<S>, &shared_data}.join();
        // Wait till consumers finish.
        for(unsigned i = 0; i < consumer_count; ++i)
            consumers[i].join();

        best_producer_time = std::min(best_producer_time, shared_data.producer_time);
    }

    return best_producer_time;
}

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

} // namespace

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

// sudo chrt -f 99 /usr/bin/time -f "\n***\ntime: %E\ncontext switches: %c\nwaits: %w" /home/max/otsquant/build/Linux-x86_64-64.g++-release/test/test

/*

Producer-consumer ping-pong tests. It aims to benchmark condition variables with and without
thread cancellation support by comparing the time it took to complete the benchmark.

Condition variable with thread cancellation support is boost::condition_variable from
boost-1.51. Without - std::condition_variable that comes with gcc-4.7.2.

One producer, one to CONSUMER_MAX consumers. The benchmark calls
condition_variable::notify_all() without holding a mutex to maximize contention within this
function. Each benchmark for a number of consumers is run three times and the best time is
picked to get rid of outliers.

The results are reported for each benchmark for a number of consumers. The most important number
is (std - boost) / std * 100. Positive numbers are when boost::condition_variable is faster,
negative it is slower.

 */

int main() {
    enum { CONSUMER_MAX = 20 };

    struct {
        Stopwatch::nsec_t boost, std;
    } best_times[CONSUMER_MAX] = {};

    for(unsigned i = 1; i <= CONSUMER_MAX; ++i) {
        auto& b = best_times[i - 1];
        b.std = benchmark_ping_pong<StdTypes>(i);
        b.boost = benchmark_ping_pong<BoostTypes>(i);

        std::printf("consumers:                 %4d\n", i);
        std::printf("best std producer time:   %15.9fsec\n", b.std * 1e-9);
        std::printf("best boost producer time: %15.9fsec\n", b.boost * 1e-9);
        std::printf("(std - boost) / std:       %7.2f%%\n", (b.std - b.boost) * 100. / b.std);
    }

    printf("\ncsv:\n\n");
    printf("consumers,(std-boost)/std,std,boost\n");
    for(unsigned i = 1; i <= CONSUMER_MAX; ++i) {
        auto& b = best_times[i - 1];
        printf("%d,%f,%lld,%lld\n", i, (b.std - b.boost) * 100. /  b.std, b.std, b.boost);
    }
}

max_stars_repo_name: sanjosh/smallprogs

max_issues_repo_name: sanjosh/smallprogs

max_forks_repo_name: sanjosh/smallprogs


text:
#pragma once

#include <xpeed/lib/numbers.hpp>
#include <xpeed/lib/utility.hpp>
#include <xpeed/secure/common.hpp>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/thread.hpp>

#include <condition_variable>
#include <deque>
#include <mutex>

namespace xpeed
{
class node;
class vote_generator
{
public:
	vote_generator (xpeed::node &, std::chrono::milliseconds);
	void add (xpeed::block_hash const &);
	void stop ();

private:
	void run ();
	void send (std::unique_lock<std::mutex> &);
	xpeed::node & node;
	std::mutex mutex;
	std::condition_variable condition;
	std::deque<xpeed::block_hash> hashes;
	std::chrono::milliseconds wait;
	bool stopped;
	bool started;
	boost::thread thread;

	friend std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_generator & vote_generator, const std::string & name);
};

std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_generator & vote_generator, const std::string & name);
class cached_votes
{
public:
	std::chrono::steady_clock::time_point time;
	xpeed::block_hash hash;
	std::vector<std::shared_ptr<xpeed::vote>> votes;
};
class votes_cache
{
public:
	void add (std::shared_ptr<xpeed::vote> const &);
	std::vector<std::shared_ptr<xpeed::vote>> find (xpeed::block_hash const &);
	void remove (xpeed::block_hash const &);

private:
	std::mutex cache_mutex;
	boost::multi_index_container<
	xpeed::cached_votes,
	boost::multi_index::indexed_by<
	boost::multi_index::ordered_non_unique<boost::multi_index::member<xpeed::cached_votes, std::chrono::steady_clock::time_point, &xpeed::cached_votes::time>>,
	boost::multi_index::hashed_unique<boost::multi_index::member<xpeed::cached_votes, xpeed::block_hash, &xpeed::cached_votes::hash>>>>
	cache;
	static size_t constexpr max_cache = (xpeed::is_test_network) ? 2 : 1000;

	friend std::unique_ptr<seq_con_info_component> collect_seq_con_info (votes_cache & votes_cache, const std::string & name);
};

std::unique_ptr<seq_con_info_component> collect_seq_con_info (votes_cache & votes_cache, const std::string & name);
}

max_stars_repo_name: xpeedcurrency/xpeed-node

max_issues_repo_name: xpeedcurrency/xpeed-node

max_forks_repo_name: xpeedcurrency/xpeed-node


text:
/* (c) 2016, 2021 FFF Services. For details refers to LICENSE.txt */
/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#pragma once

#include <boost/container/flat_set.hpp>

#include <fc/monitoring.hpp>

#include <graphene/chain/protocol/asset.hpp>
#include <graphene/chain/message_object.hpp>
#include <graphene/chain/operation_history_object.hpp>
#include <graphene/net/node.hpp>
#include <graphene/net/core_messages.hpp>
#include <graphene/app/database_api.hpp>

/**
 * @defgroup HistoryAPI History API
 * @defgroup Network_broadcastAPI Network broadcast API
 * @defgroup Network_NodeAPI Network Node API
 * @defgroup CryptoAPI Crypto API
 * @defgroup MessagingAPI Messaging API
 * @defgroup MonitoringAPI Monitoring API
 * @defgroup LoginAPI Login API
 */
namespace graphene { namespace app {

   class application;

   struct asset_array
   {
      chain::asset asset0;
      chain::asset asset1;
   };

    struct balance_change_result
    {
       chain::operation_history_object hist_object;
       asset_array balance;
       chain::asset fee;
       fc::time_point_sec timestamp;
       chain::transaction_id_type transaction_id;
    };

    struct network_node_info
    {
       fc::ip::endpoint listening_on;
       net::node_id_t node_public_key;
       net::node_id_t node_id;
       net::firewalled_state firewalled;
       uint32_t connection_count;
    };

    struct advanced_node_parameters
    {
       uint32_t peer_connection_retry_timeout;
       uint32_t desired_number_of_connections;
       uint32_t maximum_number_of_connections;
       unsigned maximum_number_of_blocks_to_handle_at_one_time;
       unsigned maximum_number_of_sync_blocks_to_prefetch;
       unsigned maximum_blocks_per_peer_during_syncing;
    };

   /**
    * @brief The history_api class implements the RPC API for account history
    *
    * This API contains methods to access account histories
    */
   class history_api : public fc::api_base<history_api>
   {
      public:
         history_api(application& app):_app(app){}

         /**
          * @brief Get the name of the API.
          * @return the name of the API
          * @ingroup HistoryAPI
          */
         std::string info() const { return get_api_name(); }

         /**
          * @brief Get operations relevant to the specificed account.
          * @param account the account whose history should be queried
          * @param stop ID of the earliest operation to retrieve
          * @param limit maximum number of operations to retrieve (must not exceed 100)
          * @param start ID of the most recent operation to retrieve
          * @return a list of operations performed by account, ordered from most recent to oldest
          * @ingroup HistoryAPI
          */
         std::vector<chain::operation_history_object> get_account_history(
            chain::account_id_type account, chain::operation_history_id_type stop, unsigned limit, chain::operation_history_id_type start) const;

         /**
          * @brief Get operations relevant to the specified account referenced
          * by an event numbering specific to the account. The current number of operations
          * for the account can be found in the account statistics (or use 0 for start).
          * @note The sequence number of the oldest operation is 1 and the operations are in increasing order,
          * from the oldest operation to the most recent.
          * @param account The account whose history should be queried
          * @param stop Sequence number of earliest operation. 0 is default and will
          * query 'limit' number of operations
          * @param limit Maximum number of operations to retrieve (must not exceed 100)
          * @param start Sequence number of the most recent operation to retrieve
          * 0 is default, which will start querying from the most recent operation
          * @return A list of operations performed by account, ordered from most recent to oldest
          * @ingroup HistoryAPI
          */
         std::vector<chain::operation_history_object> get_relative_account_history(chain::account_id_type account, uint32_t stop, unsigned limit, uint32_t start) const;

         /**
          * @brief Returns the most recent balance operations on the named account.
          * This returns a list of operation history objects, which describe activity on the account.
          * @param account_id the account whose history should be queried
          * @param assets_list list of asset_ids to filter assets or empty for all assets
          * @param partner_account_id partner account_id to filter transfers to speccific account or empty
          * @param from_block filtering parameter, starting block number (can be determined by from time) or zero when not used
          * @param to_block filtering parameter, ending block number or zero when not used
          * @param start_offset starting offset from zero
          * @param limit the number of entries to return (starting from the most recent)
          * @return a list of balance operation history objects
          * @ingroup HistoryAPI
          */
         std::vector<balance_change_result> search_account_balance_history(
            chain::account_id_type account_id, const boost::container::flat_set<chain::asset_id_type>& assets_list, fc::optional<chain::account_id_type> partner_account_id,
            uint32_t from_block, uint32_t to_block, uint32_t start_offset, unsigned limit) const;

         /**
          * @brief Returns balance operation on the named account and transaction_id.
          * @param account_id the account whose history should be queried
          * @param operation_history_id the operation_history_id whose history should be queried
          * @return balance operation history object or empty when not found
          * @ingroup HistoryAPI
          */
         fc::optional<balance_change_result> get_account_balance_for_transaction(chain::account_id_type account_id, chain::operation_history_id_type operation_history_id) const;

      private:
           application& _app;
   };

   /**
    * @brief The network_broadcast_api class allows broadcasting of transactions.
    */
   class network_broadcast_api : public std::enable_shared_from_this<network_broadcast_api>, public fc::api_base<network_broadcast_api>
   {
      public:
         network_broadcast_api(application& a);

         struct transaction_confirmation
         {
            chain::transaction_id_type   id;
            uint32_t              block_num;
            uint32_t              trx_num;
            chain::processed_transaction trx;
         };

         typedef std::function<void(fc::variant/*transaction_confirmation*/)> confirmation_callback;

         /**
          * @brief Get the name of the API.
          * @return the name of the API
          * @ingroup Network_broadcastAPI
          */
         std::string info() const { return get_api_name(); }

         /**
          * @brief Broadcast a transaction to the network.
          * @param trx the transaction to broadcast
          * @note the transaction will be checked for validity in the local database prior to broadcasting. If it fails to
          * apply locally, an error will be thrown and the transaction will not be broadcast
          * @ingroup Network_broadcastAPI
          */
         void broadcast_transaction(const chain::signed_transaction& trx) const;

         /**
          * @brief This version of broadcast transaction registers a callback method that will be called when the transaction is
          * included into a block.  The callback method includes the transaction id, block number, and transaction number in the
          * block.
          * @param cb callback function
          * @param trx the transaction to broadcast
          * @ingroup Network_broadcastAPI
          */
         void broadcast_transaction_with_callback(confirmation_callback cb, const chain::signed_transaction& trx);

         /**
          * @brief Broadcast a block to the network.
          * @param block the signed block to broadcast
          * @ingroup Network_broadcastAPI
          */
         void broadcast_block(const chain::signed_block& block) const;

      private:
         /**
          * @brief Not reflected, thus not accessible to API clients.
          * This function is registered to receive the applied_block
          * signal from the chain database when a block is received.
          * It then dispatches callbacks to clients who have requested
          * to be notified when a particular txid is included in a block.
          * @param b the signed block
          * @ingroup Network_broadcastAPI
          */
         void on_applied_block(const chain::signed_block& b);

         boost::signals2::scoped_connection             _applied_block_connection;
         std::map<chain::transaction_id_type, confirmation_callback> _callbacks;
         application&                                   _app;
   };

   /**
    * @brief The network_node_api class allows maintenance of p2p connections.
    */
   class network_node_api : public fc::api_base<network_node_api>
   {
      public:
         network_node_api(application& a);

         /**
          * @brief Get the name of the API.
          * @return the name of the API
          * @ingroup Network_NodeAPI
          */
         std::string info() const { return get_api_name(); }

         /**
          * @brief Returns general network information, such as p2p port.
          * @return general network information
          * @ingroup Network_NodeAPI
          */
         network_node_info get_info() const;

         /**
          * @brief Connects to a new peer.
          * @param ep the IP/Port of the peer to connect to
          * @ingroup Network_NodeAPI
          */
         void add_node(const fc::ip::endpoint& ep) const;

         /**
          * @brief Get status of all current connections to peers.
          * @return status of all connected peers
          * @ingroup Network_NodeAPI
          */
         std::vector<net::peer_status> get_connected_peers() const;

         /**
          * @brief Get advanced node parameters, such as desired and max number of connections.
          * @return advanced node parameters
          * @ingroup Network_NodeAPI
          */
         advanced_node_parameters get_advanced_node_parameters() const;

         /**
          * @brief Set advanced node parameters, such as desired and max number of connections.
          * @param params a JSON object containing the name/value pairs for the parameters to set
          * @ingroup Network_NodeAPI
          */
         void set_advanced_node_parameters(const advanced_node_parameters& params) const;

         /**
          * @brief Get a list of potential peers we can connect to.
          * @return a list of potential peers
          * @ingroup Network_NodeAPI
          */
         std::vector<net::potential_peer_record> get_potential_peers() const;

      private:
         application& _app;
   };

   /**
    * @brief The crypto_api class implements cryptograhic operations
    */
   class crypto_api : public fc::api_base<crypto_api>
   {
      public:
         crypto_api(application& a);

         /**
          * @brief Get the name of the API.
          * @return the name of the API
          * @ingroup CryptoAPI
          */
         std::string info() const { return get_api_name(); }

         /**
          * @brief Convert wif key to public key.
          * @param wif the wif key to convert
          * @return corresponding public key
          * @ingroup CryptoAPI
          */
         chain::public_key_type wif_to_public_key(const std::string &wif) const;

         /**
          * @brief Convert wif key to private key.
          * @param wif the wif key to convert
          * @return private key
          * @ingroup CryptoAPI
          */
         chain::private_key_type wif_to_private_key(const std::string &wif) const;

         /**
          * @brief Sign transaction with given private key.
          * @param trx the transaction to sign
          * @param key the private key to sign the given transaction
          * @return signed transaction
          * @ingroup CryptoAPI
          */
         chain::signed_transaction sign_transaction(const chain::transaction& trx, const chain::private_key_type &key) const;

         /**
          * @brief Encrypt message.
          * @param message the message to encrypt
          * @param key the private key of sender
          * @param pub the public key of receiver
          * @param nonce the salt number to use for message encryption (will be generated if zero)
          * @return encrypted memo data
          * @ingroup CryptoAPI
          */
         chain::memo_data encrypt_message(const std::string &message, const chain::private_key_type &key, const chain::public_key_type &pub, uint64_t nonce) const;

         /**
          * @brief Decrypt message.
          * @param message the message to decrypt
          * @param key the private key of sender/receiver
          * @param pub the public key of receiver/sender
          * @param nonce the salt number used for message encryption
          * @return decrypted message
          * @ingroup CryptoAPI
          */
         std::string decrypt_message(const chain::memo_data::message_type &message, const chain::private_key_type &key, const chain::public_key_type &pub, uint64_t nonce) const;

      private:
         application& _app;
   };

   /**
   * @brief The messaging_api class implements instant messaging
   */
   class messaging_api : public fc::api_base<messaging_api>
   {
   public:
      messaging_api(application& a);

      /**
       * @brief Get the name of the API.
       * @return the name of the API
       * @ingroup MessagingAPI
       */
      std::string info() const { return get_api_name(); }

      /**
       * @brief Receives message objects by sender and/or receiver.
       * @note You need to specify at least one account.
       * @param sender message sender account - pass null if you dont want to filter by sender
       * @param receiver message receiver account - pass null if you dont want to filter by receiver
       * @param max_count maximal number of messages to be returned
       * @return a vector of message objects
       * @ingroup MessagingAPI
       */
      std::vector<chain::message_object> get_message_objects(fc::optional<chain::account_id_type> sender, fc::optional<chain::account_id_type> receiver, uint32_t max_count) const;

      /**
       * @brief Get a list of messages by ID.
       * @note This function has semantics identical to \c get_objects().
       * @param message_ids IDs of the messages to retrieve
       * @return the messages corresponding to the provided IDs
       * @ingroup MessagingAPI
       */
      std::vector<fc::optional<chain::message_object>> get_messages(const std::vector<chain::message_id_type>& message_ids) const;

   private:
      application& _app;
   };

   /**
   * @brief The monitoring_api class provides access to monitoring counters
   */
   class monitoring_api : public fc::api_base<monitoring_api>
   {
   public:
      monitoring_api();

      /**
      * @brief Get the name of the API.
      * @return the name of the API
      * @ingroup MonitoringAPI
      */
      std::string info() const { return get_api_name(); }

      /**
      * @brief Reset persistent monitoring counters by names. It has not impact on non-persistent counters.
      * @param names Counter names. Pass empty vector to reset all counters.
      * @ingroup MonitoringAPI
      */
      void reset_counters(const std::vector<std::string>& names) const;

      /**
      * @brief Retrieves monitoring counters by names.
      * @param names Counter names. Pass epmty vector to retrieve all counters.
      * @return Vector of monitoring counters. Persistent counters which was not reset yet or non-persisten counters shows datetime of reset equal to begin of epoch.
      * @ingroup MonitoringAPI
      */
      std::vector<monitoring::counter_item> get_counters(const std::vector<std::string>& names) const;
   };

   /**
    * @brief The login_api class implements the bottom layer of the RPC API
    *
    * All other APIs must be requested from this API.
    */
   class login_api : public fc::api_base<login_api>
   {
      public:
         login_api(application& a);
         ~login_api();

         /**
          * @brief Get the name of the API.
          * @return the name of the API
          * @ingroup LoginAPI
          */
         std::string info() const { return get_api_name(); }

         /**
          * @brief Authenticate to the RPC server.
          * @note This must be called prior to requesting other APIs. Other APIs may not be accessible until the client
          * has sucessfully authenticated.
          * @param user username to login with
          * @param password password to login with
          * @return \c true if logged in successfully, \c false otherwise
          * @ingroup LoginAPI
          */
         bool login(const std::string& user, const std::string& password);

         /**
          * @brief Retrieve the network broadcast API.
          * @ingroup LoginAPI
          */
         fc::api<network_broadcast_api> network_broadcast() const;

         /**
          * @brief Retrieve the database API.
          * @ingroup LoginAPI
          */
         fc::api<database_api> database() const;

         /**
          * @brief Retrieve the history API.
          * @ingroup LoginAPI
          */
         fc::api<history_api> history() const;

         /**
          * @brief Retrieve the network node API.
          * @ingroup LoginAPI
          */
         fc::api<network_node_api> network_node() const;

         /**
          * @brief Retrieve the cryptography API.
          * @ingroup LoginAPI
          */
         fc::api<crypto_api> crypto() const;

         /**
         * @brief Retrieve the messaging API.
         * @ingroup LoginAPI
         */
         fc::api<messaging_api> messaging() const;

         /**
         * @brief Retrieve the monitoring API.
         * @ingroup LoginAPI
         */
         fc::api<monitoring_api> monitoring() const;

      private:
         /**
          * @brief Called to enable an API, not reflected.
          * @param api_name name of the API we are trying to enable
          * @ingroup LoginAPI
          */
         void enable_api(const std::string& api_name);

         application& _app;
         fc::optional<fc::api<database_api>> _database_api;
         fc::optional<fc::api<network_broadcast_api>> _network_broadcast_api;
         fc::optional<fc::api<network_node_api>> _network_node_api;
         fc::optional<fc::api<history_api>>  _history_api;
         fc::optional<fc::api<crypto_api>> _crypto_api;
         fc::optional<fc::api<messaging_api>> _messaging_api;
         fc::optional<fc::api<monitoring_api>> _monitoring_api;
   };

}}  // graphene::app

FC_REFLECT( graphene::app::network_broadcast_api::transaction_confirmation, (id)(block_num)(trx_num)(trx) )
FC_REFLECT( graphene::app::asset_array, (asset0)(asset1) )
FC_REFLECT( graphene::app::balance_change_result, (hist_object)(balance)(fee)(timestamp)(transaction_id) )
FC_REFLECT( graphene::app::network_node_info, (listening_on)(node_public_key)(node_id)(firewalled)(connection_count) )
FC_REFLECT( graphene::app::advanced_node_parameters, (peer_connection_retry_timeout)(desired_number_of_connections)(maximum_number_of_connections)(maximum_number_of_blocks_to_handle_at_one_time)(maximum_number_of_sync_blocks_to_prefetch)(maximum_blocks_per_peer_during_syncing) )

FC_API(graphene::app::history_api,
       (info)
       (get_account_history)
       (get_relative_account_history)
       (search_account_balance_history)
       (get_account_balance_for_transaction)
     )
FC_API(graphene::app::network_broadcast_api,
       (info)
       (broadcast_transaction)
       (broadcast_transaction_with_callback)
       (broadcast_block)
     )
FC_API(graphene::app::network_node_api,
       (info)
       (get_info)
       (add_node)
       (get_connected_peers)
       (get_potential_peers)
       (get_advanced_node_parameters)
       (set_advanced_node_parameters)
     )
FC_API(graphene::app::crypto_api,
       (info)
       (wif_to_public_key)
       (wif_to_private_key)
       (sign_transaction)
       (encrypt_message)
       (decrypt_message)
     )
FC_API(graphene::app::messaging_api,
       (info)
       (get_message_objects)
       (get_messages)
     )
FC_API(graphene::app::monitoring_api,
   (info)
      (reset_counters)
      (get_counters)
   )
FC_API(graphene::app::login_api,
       (info)
       (login)
       (network_broadcast)
       (database)
       (history)
       (network_node)
       (crypto)
       (messaging)
       (monitoring)
     )


text:
#include <easycc/LexicalConfig.h>
#include <rapidjson/istreamwrapper.h>
#include <rapidjson/writer.h>
#include <fstream>
#include <sstream>
#include <iostream>
#include <boost/algorithm/string/predicate.hpp>

namespace ecc{

    // Define line separators
    const std::string LexicalConfig::LF = "LF";
    const std::string LexicalConfig::CR = "CR";
    const std::string LexicalConfig::CRLF = "CRLF";

    std::shared_ptr<LexicalConfig> LexicalConfig::buildConfig(rapidjson::Document &d) {

        // Configuration JSON format
        const char* NEWLINE = "newline";
        const char* IGNORE = "ignore";
        const char* ERROR = "error";
        const char* RESERVED = "reserved";
        const char* PREFIX = "prefix";
        const char* SUFFIX = "suffix";
        const char* INCLUDE = "include";
        const char* EXCLUDE = "exclude";

        // Prepare a new LexicalConfig
        std::shared_ptr<LexicalConfig> config = std::make_shared<LexicalConfig>();

        // Get the newline separator
        std::string configNewline = std::string(d[NEWLINE].GetString());
        if(configNewline != LF && configNewline != CR &&  configNewline != CRLF) {
            throw std::runtime_error("Configuration error! newline has to be: LF, CR or CRLF");
        }

        // Store newline
        config->m_newLine = configNewline;

        // Ignore object
        config->m_ignorePrefix = d[IGNORE][PREFIX].GetString();
        config->m_ignoreSuffix = d[IGNORE][SUFFIX].GetString();
        for(auto i=d[IGNORE][INCLUDE].Begin(); i!=d[IGNORE][INCLUDE].End(); i++) {
            config->m_ignoreInclude.insert((*i).GetString());
        }
        for(auto i=d[IGNORE][EXCLUDE].Begin(); i!=d[IGNORE][EXCLUDE].End(); i++) {
            config->m_ignoreExclude.insert((*i).GetString());
        }

        // Error object
        config->m_errorPrefix = d[ERROR][PREFIX].GetString();
        config->m_errorSuffix = d[ERROR][SUFFIX].GetString();
        for(auto i=d[ERROR][INCLUDE].Begin(); i!=d[ERROR][INCLUDE].End(); i++) {
            config->m_errorInclude.insert((*i).GetString());
        }
        for(auto i=d[ERROR][EXCLUDE].Begin(); i!=d[ERROR][EXCLUDE].End(); i++) {
            config->m_errorExclude.insert((*i).GetString());
        }

        // Reserved object
        for(auto i=d[RESERVED].MemberBegin(); i!=d[RESERVED].MemberEnd(); i++) {
            const char* tokenName = (*i).name.GetString();
            for(auto j=d[RESERVED][tokenName].MemberBegin(); j!= d[RESERVED][tokenName].MemberEnd(); j++) {
                config->m_reservedTokens[tokenName][j->name.GetString()] = j->value.GetString();
            }
        }
        return config;
    }

    std::shared_ptr<LexicalConfig> LexicalConfig::buildConfigFromFile(std::string configFileName) {
        std::ifstream ifs(configFileName);
        rapidjson::IStreamWrapper isw(ifs);
        rapidjson::Document d;
        d.ParseStream(isw);
        return buildConfig(d);
    }

    std::shared_ptr<LexicalConfig> LexicalConfig::buildConfigFromString(std::string data) {
        rapidjson::Document d;
        d.Parse(data.c_str());
        return buildConfig(d);
    }

    bool LexicalConfig::mustIgnoreToken(std::string tokenName) {
        // If token name is in the exclude set
        if(this->m_ignoreExclude.find(tokenName) != this->m_ignoreExclude.end()) {
            return false;
        }

        // If token name is in the include set
        if(this->m_ignoreInclude.find(tokenName) != this->m_ignoreInclude.end()) {
            return true;
        }

        // If token name starts with the prefix
        if(m_ignorePrefix.size() > 0 && boost::algorithm::starts_with(tokenName, m_ignorePrefix)) {
            return true;
        }

        // If token name ends with the suffix
        return m_ignoreSuffix.size() > 0 && boost::algorithm::ends_with(tokenName, m_ignoreSuffix);
    }

    bool LexicalConfig::isErrorToken(std::string tokenName) {
        // If token name is in the exclude set
        if(this->m_errorExclude.find(tokenName) != this->m_errorExclude.end()) {
            return false;
        }

        // If token name is in the include set
        if(this->m_errorInclude.find(tokenName) != this->m_errorInclude.end()) {
            return true;
        }

        // If token name starts with the prefix
        if(m_errorPrefix.size() > 0 && boost::algorithm::starts_with(tokenName, m_errorPrefix)) {
            return true;
        }

        // If token name ends with the suffix
        return m_errorSuffix.size() > 0 && boost::algorithm::ends_with(tokenName, m_errorSuffix);
    }

    std::string LexicalConfig::updateTokenName(std::string tokenName, std::string tokenValue) {

        // If token name does not have any check entry
        if(this->m_reservedTokens.count(tokenName) == 0) {
            return tokenName;
        }

        // If token value exist in the map
        if(this->m_reservedTokens[tokenName].count(tokenValue) == 0) {
            return tokenName;
        }

        // Return new token name
        return this->m_reservedTokens[tokenName][tokenValue];
    }
}

max_stars_repo_name: amirbawab/EasyCCC-

max_issues_repo_name: amirbawab/EasyCCC-

max_forks_repo_name: amirbawab/EasyCCC-