text:
// Copyright (C) 2004-2006 The Trustees of Indiana University.

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor
//           Nick Edmonds
//           Andrew Lumsdaine
#include <boost/property_map/parallel/distributed_property_map.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/bind.hpp>

#ifndef BOOST_GRAPH_USE_MPI
#error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included"
#endif

namespace boost { namespace parallel {

PBGL_DISTRIB_PMAP_TEMPLATE
template<typename Reduce>
PBGL_DISTRIB_PMAP
::distributed_property_map(amplusplus::transport& trans, const GlobalMap& global,
                           const StorageMap& pm, const Reduce& reduce,
			   MessageGenerator message_gen)
  : data(new data_t(trans, global, pm, reduce, reduce,
		    Reduce::non_default_resolver, message_gen))
{
  data->ghost_cells.reset(new GhostCellStorage());
  data->reset = &data_t::template do_reset<Reduce>;
  data->ghost_cells->unset_limit();
  data->setup_messages();
}

PBGL_DISTRIB_PMAP_TEMPLATE
PBGL_DISTRIB_PMAP::~distributed_property_map() { }

PBGL_DISTRIB_PMAP_TEMPLATE
template<typename Reduce>
void
PBGL_DISTRIB_PMAP::set_reduce(const Reduce& reduce)
{
  data->get_default_value = reduce;
  data->reduce = reduce;
  data->has_default_resolver = Reduce::non_default_resolver;
  int model = data->model;
  data->reset = &data_t::template do_reset<Reduce>;
  set_consistency_model(model);
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::prune_one_ghost_cell(const key_type& key, const value_type& value) const
{
  if (data->model & cm_flush) {
    // We need to flush values when we evict them.
    std::pair<key_type, value_type> const victim(key, value);
    data->put_msg.send(victim);
  }
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::prune_ghost_cells() const
{
  data->ghost_cells->prune(this);
}

PBGL_DISTRIB_PMAP_TEMPLATE
typename PBGL_DISTRIB_PMAP::value_type&
PBGL_DISTRIB_PMAP::cell(const key_type& key, bool request_if_missing) const
{
  bool found;
  value_type* value_ptr;
  data->ghost_cells->get_cell(key, value_ptr, found);

  value_type value;

  // Search for the ghost cell by key, and project back to the sequence
  if (!found) {
    if (data->has_default_resolver)
      // Since we have a default resolver, use it to create a default
      // value for this ghost cell.
      value = data->get_default_value(key);
    else { value = value_type(); }
      // TODO (NGE): Should we throw an exception when get() is called without a default resolver?

    typename PBGL_DISTRIB_PMAP::value_type& v = data->ghost_cells->insert_cell(key, value, this);

    if (request_if_missing)
      // Request the actual value of this key from its owner
      data->get_msg.send(std::make_pair(key,data->transport.rank()));
    return v;
  } else {
    return *value_ptr;
  }
}

PBGL_DISTRIB_PMAP_TEMPLATE
void
PBGL_DISTRIB_PMAP::data_t::
atomic_put_handler::operator() (const std::pair<key_type, value_type>& req) const
{
  using boost::get;

  owner_local_pair p = get(self->global, req.first);
  assert(p.first == self->transport.rank());

  put(self->storage, p.second,
      self->reduce(req.first, get(self->storage, p.second), req.second));

//   value_type oldval, newval;

//   do {
//     oldval = get(self->storage, p.second);
//     newval = self->reduce(req.first, oldval, req.second);
//   } while(!maybe_exchange(self->storage, p.second, oldval, newval));
}

PBGL_DISTRIB_PMAP_TEMPLATE
void
PBGL_DISTRIB_PMAP::data_t::
put_handler::operator() (const std::pair<key_type, value_type>& req) const
{
  using boost::get;

  owner_local_pair p = get(self->global, req.first);
  assert(p.first == self->transport.rank());

  detail::maybe_put(self->storage, p.second,
                    self->reduce(req.first,
				 get(self->storage, p.second),
				 req.second));
}

PBGL_DISTRIB_PMAP_TEMPLATE
void
PBGL_DISTRIB_PMAP::data_t::
get_handler::operator() (const std::pair<key_type, rank_type>& msg) const
{
  using boost::get;

  rank_type source = msg.second;
  key_type key = msg.first;
  owner_local_pair p = get(self->global, key);
  value_type value = get(self->storage, p.second);

  self->get_reply_msg.send(boost::make_tuple(source, key, value));
}

PBGL_DISTRIB_PMAP_TEMPLATE
void
PBGL_DISTRIB_PMAP::data_t::
get_reply_handler::operator() (const boost::tuple<rank_type, key_type, value_type>& msg) const
{
  rank_type source = msg.template get<0>();
  key_type key = msg.template get<1>();
  value_type value = msg.template get<2>();

  value_type* value_ptr;
  bool found;
  self->ghost_cells->get_cell(key, value_ptr, found);
  if (found)
    *value_ptr = value;
}

PBGL_DISTRIB_PMAP_TEMPLATE
void
PBGL_DISTRIB_PMAP::data_t::
setup_messages()
{
  put_msg.set_handler(put_handler(*this));
  atomic_put_msg.set_handler(atomic_put_handler(*this));
  get_msg.set_handler(get_handler(*this));
  get_reply_msg.set_handler(get_reply_handler(*this));
}

PBGL_DISTRIB_PMAP_TEMPLATE
void
PBGL_DISTRIB_PMAP::set_consistency_model(int model)
{
  data->model = model;

  if (model & cm_backward) {
    // For backward consistency to work, we absolutely cannot throw
    // away any ghost cells.
    data->ghost_cells->unset_limit();
  }
}

PBGL_DISTRIB_PMAP_TEMPLATE
void
PBGL_DISTRIB_PMAP::set_max_ghost_cells(std::size_t max_ghost_cells)
{
  if ((data->model & cm_backward) && max_ghost_cells > 0)
      boost::throw_exception(std::runtime_error("distributed_property_map::set_max_ghost_cells: "
                                                "cannot limit ghost-cell usage with a backward "
                                                "consistency model"));

  data->ghost_cells->set_limit(max_ghost_cells, this);
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::clear()
{
  data->clear();
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::data_t::clear()
{
  ghost_cells->clear();
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::reset()
{
  if (data->reset) ((*data).*data->reset)();
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::flush()
{
  data->flush();
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::data_t::refresh_ghost_cells()
{
  using boost::get;

  // Collect the set of keys for which we will request values
  for (typename GhostCellStorage::iterator i = ghost_cells->begin();
       i != ghost_cells->end(); ++i)
    get_msg.send(std::make_pair(GhostCellStorage::get_key(i), transport.rank()));
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::data_t::flush()
{
  using boost::get;

  // Collect all of the flushed values
  for (typename GhostCellStorage::iterator i = ghost_cells->begin(); i != ghost_cells->end(); ++i)
    put_msg.send(std::make_pair(GhostCellStorage::get_key(i), GhostCellStorage::get_value(i)));
}

PBGL_DISTRIB_PMAP_TEMPLATE
void PBGL_DISTRIB_PMAP::synchronize()
{
  // Flush results
  if (data->model & cm_flush) {
    amplusplus::scoped_epoch epoch(data->transport);
    data->flush();
  }

  // Backward consistency
  if (data->model & cm_backward && !(data->model & (cm_clear | cm_reset))) {
    amplusplus::scoped_epoch epoch(data->transport);
    data->refresh_ghost_cells();
  }

  // Optionally clear results
  if (data->model & cm_clear)
    data->clear();

  // Optionally reset results
  if (data->model & cm_reset) {
    if (data->reset) ((*data).*data->reset)();
  }
}

PBGL_DISTRIB_PMAP_TEMPLATE
template<typename Resolver>
void PBGL_DISTRIB_PMAP::data_t::do_reset()
{
  Resolver* resolver = reduce.template target<Resolver>();
  assert(resolver);

  for (typename GhostCellStorage::iterator i = ghost_cells->begin(); i != ghost_cells->end(); ++i)
    GhostCellStorage::get_value(i) = (*resolver)(GhostCellStorage::get_key(i));
}

} } // end namespace boost::parallel

max_stars_repo_name: thejkane/AGM

max_issues_repo_name: thejkane/AGM

max_forks_repo_name: thejkane/AGM


text:
#ifndef CONNECTION_MANAGER_HPP
#define CONNECTION_MANAGER_HPP

#include <boost/core/noncopyable.hpp>

#include "connection.hpp"

class connection_manager
    : private boost::noncopyable
{
public:

    void start(std::shared_ptr<tcp_connection> connection)
    {
        connections_.insert(connection);
        connection->start();
    }

    void stop(std::shared_ptr<tcp_connection> connection)
    {
        connections_.erase(connection);
        // TODO:
        // connection->stop();
    }
    // TODO: stop_all

private:
    std::set<std::shared_ptr<tcp_connection>> connections_;

};

#endif

ext: hpp

max_stars_repo_name: MatthewOrd/mndb

max_issues_repo_name: MatthewOrd/mndb

max_forks_repo_name: MatthewOrd/mndb


text:
// Autogenerated from KST: please remove this line if doing any edits by hand!

#include <boost/test/unit_test.hpp>
#include "expr_io_pos.h"
#include <iostream>
#include <fstream>
#include <vector>

BOOST_AUTO_TEST_CASE(test_expr_io_pos) {
    std::ifstream ifs("src/expr_io_pos.bin", std::ifstream::binary);
    kaitai::kstream ks(&ifs);
    expr_io_pos_t* r = new expr_io_pos_t(&ks);

    BOOST_CHECK_EQUAL(r->substream1()->my_str(), std::string("CURIOSITY"));
    BOOST_CHECK_EQUAL(r->substream1()->body(), std::string("\x11\x22\x33\x44", 4));
    BOOST_CHECK_EQUAL(r->substream1()->number(), 66);
    BOOST_CHECK_EQUAL(r->substream2()->my_str(), std::string("KILLED"));
    BOOST_CHECK_EQUAL(r->substream2()->body(), std::string("\x61\x20\x63\x61\x74", 5));
    BOOST_CHECK_EQUAL(r->substream2()->number(), 103);

    delete r;
}

ext: cpp


text:
#include "vr/io/cap/cap_reader.h"
#include "vr/io/files.h"
#include "vr/io/net/IP_.h"
#include "vr/io/net/pcap_.h"
#include "vr/io/net/UDP_.h"
#include "vr/io/stream_factory.h"
#include "vr/io/streams.h"
#include "vr/market/books/asx/market_data_listener.h"
#include "vr/market/books/asx/market_data_view.h"
#include "vr/market/books/book_event_context.h"
#include "vr/market/rt/cfg/agent_cfg.h"
#include "vr/market/ref/asx/ref_data.h"
#include "vr/market/sources/asx/itch/ITCH_filters.h"
#include "vr/market/sources/asx/itch/ITCH_pipeline.h"
#include "vr/market/sources/asx/market_data.h"
#include "vr/rt/cfg/resources.h"
#include "vr/util/di/container.h"

#include "vr/test/configure.h"
#include "vr/test/files.h"
#include "vr/test/utility.h"

#include <boost/preprocessor/logical/or.hpp>

//----------------------------------------------------------------------------
namespace vr
{
using namespace io;
using namespace io::net;

namespace market
{
namespace ASX
{
//............................................................................
//............................................................................
namespace
{

template<typename LIMIT_ORDER_BOOK, typename CTX>
class book_checker: public ITCH_visitor<book_checker<LIMIT_ORDER_BOOK, CTX> >
{
    private: // ..............................................................

        using super         = ITCH_visitor<book_checker<LIMIT_ORDER_BOOK, CTX> >;

        vr_static_assert (has_field<_book_, CTX> ()); // how the book reference is communicated

    public: // ...............................................................

        book_checker ()     = default;

        book_checker (arg_map const & args) :
            book_checker { }
        {
        }

        // overridden ITCH visits:

        using super::visit;

        // run the books internal consistency checks following any visit that may have modified them:

        VR_ASSUME_HOT void visit (post_message const msg_type, CTX & ctx) // override
        {
            super::visit (msg_type, ctx); // [chain]

            LIMIT_ORDER_BOOK const * const book = static_cast<LIMIT_ORDER_BOOK const *> (field<_book_> (ctx));
            if (book) book->check ();
        }

}; // end of class
//............................................................................

string_vector
reservoir_sample (string_vector const data, int32_t const size, uint32_t rnd)
{
    assert_positive (size);

    string_vector r { };

    int32_t const di_limit = data.size ();

    int32_t i = 0;
    int32_t di = 0;

    for ( ; (i < size) && (di < di_limit); ++ i, ++ di)
    {
        r.push_back (data [di]);
    }

    for ( ; (di < di_limit); ++ i, ++ di)
    {
        int32_t const j = (test::next_random (rnd) % i);
        if (j < size)
            r [j] = data [di];
    }

    return r;
}

} // end of anonymous
//............................................................................
//............................................................................

using scenarios     = gt::Types
<
    util::int32_<1>, // tests ASX-55 fix
    util::int32_<VR_IF_THEN_ELSE (BOOST_PP_OR (VR_FULL_TESTS, VR_RELEASE))(100, 10)> // very time-consuming when many books are checked on every event
>;

template<typename T> struct ASX_market_data_view_test: public gt::Test { };
TYPED_TEST_CASE (ASX_market_data_view_test, scenarios);

/*
 * run captured data through a pipeline with
 *  - instrument selector
 *  - book listener as supplied by a 'market_data_view'
 *  - view/book verifier
 */
TYPED_TEST (ASX_market_data_view_test, capture_replay)
{
    using scenario      = TypeParam; // test parameter

    constexpr int32_t view_size_limit   = scenario::value;

    uint32_t rnd { test::env::random_seed<uint32_t> () };

    fs::path const test_input = test::find_capture (source::ASX, "<"_rop, util::current_date_in ("Australia/Sydney"));
    LOG_info << "using test data in " << print (test_input);

    string_vector const universe = io::read_json (rt::resolve_as_uri ("asx/symbols.asx300.json"));
    string_vector const symbols = reservoir_sample (universe, view_size_limit, rnd);

    util::di::container app { join_as_name ("APP", test::current_test_name ()) };
    {
        test::configure_app_ref_data (app, symbols);
    }

    app.start ();
    {
        ref_data const & rd = app ["ref_data"];
        agent_cfg const & ac = app ["agents"];

        int32_t const view_size     = symbols.size ();
        int64_t const record_limit  = ((VR_FULL_TESTS || (view_size == 1)) ? std::numeric_limits<int64_t>::max () : 5000000);

        LOG_info << "creating view with " << view_size << " instrument(s), record limit: " << record_limit;
        LOG_info << "test symbol(s): " << print (symbols);

        using book_type         = limit_order_book<price_si_t, oid_t, level<_qty_, _order_count_>>;
        using view              = market_data_view<book_type>;

        view mdv // note that the same book instances owned by 'mdv' live through both glimpse and mcast eval runs
        {
            {
                { "ref_data",   std::cref (rd) },
                { "agents",     std::cref (ac) }
            }
        };

        mdv.check (); // initial consistency after construction

        using reader            = cap_reader;

        // start with glimpse snapshot state:
        {
            using visit_ctx         = book_event_context<_book_, _ts_origin_, _packet_index_, _partition_>;

            using selector          = view::instrument_selector<visit_ctx>;
            using listener          = market_data_listener<this_source (), book_type, visit_ctx>;
            using checker           = book_checker<book_type, visit_ctx>;

            using pipeline          = ITCH_pipeline
                                    <
                                        selector,
                                        listener,
                                        checker
                                    >;

            using visitor           = Soup_frame_<io::mode::recv, pipeline>;

            for (int32_t pix = 0; pix < partition_count (); ++ pix) // consume all glimpse data
            {
                visitor v
                {
                    {
                        { "view", std::cref (mdv) },
                    }
                };

                visit_ctx ctx { };

                std::string const filename = "glimpse.recv.203.0.119.213_2180" + string_cast (pix + 1) + ".soup";

                std::unique_ptr<std::istream> const in = stream_factory::open_input (test_input / filename);

                reader r { * in, cap_format::wire };

                r.evaluate (ctx, v);
            }
        }

        mdv.check ();

        // continue by consuming mcast data:
        {
            using visit_ctx         = book_event_context<_book_, _ts_origin_, _packet_index_, _partition_, _ts_local_, _ts_local_delta_, _seqnum_,  _dst_port_>;

            using selector          = view::instrument_selector<visit_ctx>;
            using listener          = market_data_listener<this_source (), book_type, visit_ctx>;
            using checker           = book_checker<book_type, visit_ctx>;

            using pipeline          = ITCH_pipeline
                                    <
                                        selector,
                                        listener,
                                        checker
                                    >;

            using visitor           = pcap_<IP_<UDP_<Mold_frame_<pipeline>>>>;

            visitor v
            {
                {
                    { "view", std::cref (mdv) },
                }
            };

            visit_ctx ctx { };

            std::unique_ptr<std::istream> const in = stream_factory::open_input (test_input / "mcast.recv.p1p2.pcap.zst");

            reader r { * in, cap_format::pcap };

            r.evaluate (ctx, v, record_limit);
        }

        mdv.check ();
    }
    app.stop ();
}

} // end of 'ASX
} // end of 'market'
} // end of namespace
//----------------------------------------------------------------------------

max_stars_repo_name: vladium/vrt

max_issues_repo_name: vladium/vrt

max_forks_repo_name: vladium/vrt


text:
// Эта программа получает доступ к системному семафору
// и увеличивает его значение на 1, чтобы разблокировать программу 1

#include <iostream>
#include <string>
#include <algorithm>

#include <boost/interprocess/sync/named_semaphore.hpp>

using namespace std;
using namespace boost::interprocess;

int main()
{
    try
    {
        named_semaphore sem (open_or_create,
                             "lab10_sem", 0
                             );

        cout << "Semaphore increase." << endl;

        sem.post();

        cout << "Semaphore increased!" << endl;
    }
    catch (interprocess_exception &ex)
    {
        cout << "Error: " << ex.what() << endl;
        return 1;
    }

    return 0;

}

max_stars_repo_name: SgAkErRu/labs

max_issues_repo_name: SgAkErRu/labs

max_forks_repo_name: SgAkErRu/labs


text:
// MIT License
//
// Copyright (c) 2018 Michal Siedlaczek
//
// 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.

//! \file
//! \author     Michal Siedlaczek
//! \copyright  MIT License

#pragma once

#include <algorithm>
#include <numeric>

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/iterator/permutation_iterator.hpp>
#include <boost/range/iterator_range.hpp>
#include <cppitertools/itertools.hpp>
#include <pstl/algorithm>
#include <pstl/execution>
#include <pstl/numeric>
#include <spdlog/spdlog.h>

#include <irkit/algorithm/transform.hpp>
#include <irkit/assert.hpp>
#include <irkit/index.hpp>
#include <irkit/index/source.hpp>
#include <irkit/index/types.hpp>
#include <irkit/list/standard_block_list.hpp>

namespace irk {

using boost::filesystem::filesystem_error;
using boost::filesystem::path;
using index::document_t;
using index::frequency_t;
using index::term_id_t;
using iter::enumerate;
using iter::zip;

namespace index {

    /// A writer for posting-related vectors, such as offsets, max scores,
    /// collection term frequencies, etc.
    struct posting_vectors {
        std::vector<term_id_t> term_ids;
        std::vector<offset_t> document_offsets;
        std::vector<offset_t> frequency_offsets;
        std::vector<std::vector<offset_t>> score_offsets;
        std::vector<std::vector<inverted_index_view::score_type>> max_scores;
        std::vector<frequency_t> term_frequencies;
        std::vector<frequency_t> term_occurrences;

        frequency_t total_occurrences = 0;

        offset_t cur_document_offset = 0;
        offset_t cur_frequency_offset = 0;
        std::vector<offset_t> cur_score_offsets;
        std::vector<std::string> score_names;

        posting_vectors(std::vector<std::string> score_names = {})
            : score_offsets(score_names.size()),
              max_scores(score_names.size()),
              cur_score_offsets(score_names.size(), 0),
              score_names(std::move(score_names))
        {}

        template<typename Range>
        void write(
            const boost::filesystem::path& input_dir,
            const boost::filesystem::path& output_dir,
            int lex_keys_per_block,
            const Range& score_names)
        {
            write_terms(input_dir, output_dir, lex_keys_per_block);
            build_offset_table(document_offsets)
                .serialize(doc_ids_off_path(output_dir));
            build_offset_table(frequency_offsets)
                .serialize(doc_counts_off_path(output_dir));
            for (const auto& [idx, name] : iter::enumerate(score_names)) {
                auto paths = index::score_paths(output_dir, name);
                build_offset_table(score_offsets[idx]).serialize(paths.offsets);
                using score_type = inverted_index_view::score_type;
                build_compact_table<score_type>(max_scores[idx])
                    .serialize(paths.max_scores);
            }
            build_compact_table<frequency_t>(term_frequencies)
                .serialize(term_doc_freq_path(output_dir));
            build_compact_table<frequency_t>(term_occurrences)
                .serialize(term_occurrences_path(output_dir));
        }

        /// Accumulates data for a term.
        ///
        /// This function needs **not** to be called with consecutive term IDs,
        /// but the IDs must be in increasing order.
        void push(
            term_id_t term_id,
            offset_t document_size,
            offset_t frequency_size,
            std::vector<offset_t> score_sizes,
            std::vector<inverted_index_view::score_type> max_score_vec,
            std::vector<inverted_index_view::score_type> score_exp_vec,
            std::vector<inverted_index_view::score_type> score_var_vec,
            frequency_t frequency,
            frequency_t occurrences)
        {
            term_ids.push_back(term_id);
            document_offsets.push_back(cur_document_offset);
            frequency_offsets.push_back(cur_frequency_offset);
            cur_document_offset += document_size;
            cur_frequency_offset += frequency_size;
            for (auto&& [idx, size] : iter::enumerate(score_sizes)) {
                score_offsets[idx].push_back(cur_score_offsets[idx]);
                cur_score_offsets[idx] += size;
            }
            term_frequencies.push_back(frequency);
            term_occurrences.push_back(occurrences);
            for (auto&& [max, vec] : zip(max_score_vec, max_scores)) {
                vec.push_back(max);
            }
            total_occurrences += occurrences;
        }

    private:
        void write_terms(
            const boost::filesystem::path& input_dir,
            const boost::filesystem::path& output_dir,
            int keys_per_block)
        {
            io::filter_lines(
                terms_path(input_dir), terms_path(output_dir), term_ids);
            build_lexicon(terms_path(output_dir), keys_per_block)
                .serialize(term_map_path(output_dir));
            build_compact_table(term_frequencies)
                .serialize(term_doc_freq_path(output_dir));
        }
    };

    /// All streams for posting-like data.
    template<typename Stream>
    struct posting_streams {
        Stream documents;
        Stream frequencies;
        std::vector<Stream> scores;
        posting_vectors& vectors;

        posting_streams(
            const boost::filesystem::path& dir,
            const std::vector<std::string>& score_names,
            posting_vectors& vectors,
            std::ios_base::openmode mode = std::ios_base::binary)
            : documents(doc_ids_path(dir).string(), mode),
              frequencies(doc_counts_path(dir).string(), mode),
              vectors(vectors)
        {
            for (const std::string& score : score_names) {
                auto score_path = dir / fmt::format("{}.scores", score);
                auto score_offsets_path =
                    dir / fmt::format("{}.offsets", score);
                scores.emplace_back(score_path.string(), mode);
            }
        }

        /// Writes out the builders to files.
        template<
            typename DocBuilder,
            typename FreqBuilder,
            typename ScoreBuilder>
        void write(
            term_id_t term_id,
            DocBuilder& document_builder,
            FreqBuilder& frequency_builder,
            std::vector<ScoreBuilder>& score_builders)
        {
            using score_type = inverted_index_view::score_type;
            namespace a = boost::accumulators;
            using accumulator = a::accumulator_set<
                score_type,
                a::stats<a::tag::mean, a::tag::variance, a::tag::max>>;
            EXPECTS(score_builders.size() == scores.size());
            const auto& frequency_vector = frequency_builder.values();
            frequency_t occurrences = std::accumulate(
                frequency_vector.begin(),
                frequency_vector.end(),
                frequency_t(0),
                std::plus<frequency_t>());
            std::vector<score_type> max_scores, exps, vars;
            std::vector<offset_t> score_sizes;
            for (auto&& [builder, stream] : iter::zip(score_builders, scores)) {
                accumulator acc;
                std::for_each(
                    builder.values().begin(),
                    builder.values().end(),
                    [&acc](auto score) { acc(score); });
                max_scores.push_back(a::max(acc));
                exps.push_back(a::mean(acc));
                vars.push_back(a::variance(acc));
                score_sizes.push_back(builder.write(stream));
            }
            vectors.push(
                term_id,
                document_builder.write(documents),
                frequency_builder.write(frequencies),
                score_sizes,
                max_scores,
                exps,
                vars,
                document_builder.size(),
                occurrences);
        }
    };

}

namespace detail::partition {

    /// Resolves output paths to all shards.
    Vector<ShardId, path> resolve_paths(const path& output_dir, int shard_count)
    {
        Vector<ShardId, path> paths(shard_count);
        std::generate_n(
            paths.begin(), shard_count, [&output_dir, shard = 0]() mutable {
                return output_dir / fmt::format("{:03d}", shard++);
            });
        return paths;
    }

    /// Computes ID mapping from global to local document ID.
    static Vector<document_t>
    compute_document_mapping(const Vector<document_t, ShardId>& shard_mapping,
                             const int shard_count)
    {
        Vector<ShardId, document_t> next_id(shard_count, 0);
        Vector<document_t> document_mapping(shard_mapping.size());
        for (auto&& [document, shard] : zip(document_mapping, shard_mapping)) {
            document = next_id[shard]++;
        }
        return document_mapping;
    }

    /// Computes ID mapping from local to global document ID.
    static Vector<ShardId, Vector<document_t>>
    compute_reverse_mapping(const Vector<document_t, ShardId>& shard_mapping, const int shard_count)
    {
        Vector<ShardId, Vector<document_t>> reverse_mapping(shard_count);
        for (auto global_id : iter::range(shard_mapping.size())) {
            auto shard = shard_mapping[global_id];
            reverse_mapping[shard].push_back(global_id);
        }
        return reverse_mapping;
    }

    /// A convenient wrapper for a set of functions for index partitioning.
    class Partition {
    public:
        using score_type = inverted_index_view::score_type;
        using document_builder_type = ir::
            Standard_Block_List_Builder<document_t, stream_vbyte_codec<document_t>, true>;
        using frequency_builder_type = ir::
            Standard_Block_List_Builder<frequency_t, stream_vbyte_codec<frequency_t>, false>;
        using score_builder_type = ir::
            Standard_Block_List_Builder<score_type, stream_vbyte_codec<score_type>, false>;

        Partition(int32_t shard_count,
                  int32_t document_count,
                  const path& input_dir,
                  const Vector<ShardId, path>& shard_dirs,
                  const Vector<document_t, ShardId>& shard_mapping,
                  const Vector<document_t>& document_mapping,
                  const Vector<ShardId, Vector<document_t>>& reverse_mapping)
            : shard_count_(shard_count),
              document_count_(document_count),
              input_dir_(input_dir),
              shard_dirs_(shard_dirs),
              shard_mapping_(shard_mapping),
              document_mapping_(document_mapping),
              reverse_mapping_(reverse_mapping)
        {}

        /// Partitions document sizes.
        auto sizes()
        {
            using size_type = inverted_index_view::size_type;
            auto size_table = irk::load_compact_table<size_type>(
                index::doc_sizes_path(input_dir_));
            Vector<ShardId, std::vector<size_type>> shard_sizes(shard_count_);
            Vector<ShardId, size_t> avg_shard_sizes(shard_count_, 0);

            for (const auto& [shard_assignment, size] :
                 zip(shard_mapping_, size_table))
            {
                shard_sizes[shard_assignment].push_back(size);
                avg_shard_sizes[shard_assignment] += size;
            }

            Vector<ShardId, size_t> max_shard_sizes(shard_count_);
            std::transform(
                std::execution::par_unseq,
                shard_sizes.begin(),
                shard_sizes.end(),
                max_shard_sizes.begin(),
                [](const auto& size_vec) {
                    return *std::max_element(
                        std::execution::unseq,
                        size_vec.begin(),
                        size_vec.end());
                });

            for (auto&& [dir, sizes, avg_size] :
                 zip(shard_dirs_, shard_sizes, avg_shard_sizes))
            {
                if (not exists(dir)) {
                    create_directory(dir);
                }
                std::ofstream os(index::doc_sizes_path(dir).string());
                irk::build_compact_table(sizes).serialize(os);
                avg_size /= sizes.size();
            }

            return std::make_pair(
                std::move(avg_shard_sizes), std::move(max_shard_sizes));
        }

        /// Partitions document titles and title map.
        auto titles()
        {
            auto [buf, lex_view] =
                make_memory_view(index::title_map_path(input_dir_));
            (void)buf;
            auto titles = load_lexicon(lex_view);
            auto keys_per_block = titles.keys_per_block();
            Vector<ShardId, std::vector<std::string>> shard_titles(shard_count_);
            for (const auto& [shard, title] : zip(shard_mapping_, titles)) {
                shard_titles[shard].push_back(title);
            }
            for (const auto& [shard_dir, partitioned_titles] :
                 zip(shard_dirs_, shard_titles))
            {
                if (not exists(shard_dir)) {
                    create_directory(shard_dir);
                }
                std::ofstream los(index::title_map_path(shard_dir).string());
                std::ofstream tos(index::titles_path(shard_dir).string());
                irk::build_lexicon(partitioned_titles, keys_per_block)
                    .serialize(los);
                for (const auto& title : partitioned_titles) {
                    tos << title << '\n';
                }
            }
        }

        template<typename DocumentList>
        document_builder_type
        filter_document_lists(const DocumentList& documents, ShardId shard)
        {
            const auto& block_size = documents.block_size();
            document_builder_type builder(block_size);
            for (auto&& id : documents) {
                if (shard != shard_mapping_[id]) {
                    continue;
                }
                auto local_doc_id = document_mapping_[id];
                builder.add(local_doc_id);
            }
            return builder;
        }

        template<typename PostingList>
        frequency_builder_type
        filter_freq_lists(const PostingList& postings, ShardId shard)
        {
            const auto& block_size = postings.block_size();
            frequency_builder_type builder(block_size);
            for (auto&& posting : postings) {
                if (shard != shard_mapping_[posting.document()]) {
                    continue;
                }
                builder.add(posting.payload());
            }
            return builder;
        }

        template<typename Index>
        std::vector<score_builder_type> filter_score_lists(
            const Index& index,
            term_id_t term_id,
            const std::vector<std::string>& score_names,
            ShardId shard)
        {
            size_t block_size = index.documents(0).block_size();
            std::vector<score_builder_type> builders;
            for (const auto& _ : score_names) {
                (void)_;
                builders.emplace_back(block_size);
            }
            for (const auto& [idx, name] : iter::enumerate(score_names)) {
                auto postings = index.scored_postings(term_id, name);
                for (auto&& posting : postings) {
                    if (shard != shard_mapping_[posting.document()]) {
                        continue;
                    }
                    builders[idx].add(posting.payload());
                }
            }
            return builders;
        }

        template<typename DocumentList>
        Vector<ShardId, document_builder_type> build_document_lists(const DocumentList& documents)
        {
            const auto& block_size = documents.block_size();
            Vector<ShardId, document_builder_type> builders(shard_count_,
                                                            document_builder_type(block_size));
            for (auto&& id : documents) {
                auto shard = shard_mapping_[id];
                auto local_doc_id = document_mapping_[id];
                builders[shard].add(local_doc_id);
            }
            return builders;
        }

        template<typename PostingList>
        Vector<ShardId, frequency_builder_type> build_payload_lists(const PostingList& postings)
        {
            const auto& block_size = postings.block_size();
            Vector<ShardId, frequency_builder_type> builders(shard_count_,
                                                             frequency_builder_type(block_size));
            for (auto&& posting : postings) {
                auto shard = shard_mapping_[posting.document()];
                builders[shard].add(posting.payload());
            }
            return builders;
        }

        template<typename Index>
        Vector<ShardId, std::vector<score_builder_type>>
        build_score_lists(const Index& index,
                          term_id_t term_id,
                          const std::vector<std::string>& score_names)
        {
            size_t block_size = index.documents(0).block_size();
            Vector<ShardId, std::vector<score_builder_type>> builders(document_count_);
            for (auto& builder : builders) {
                for (const auto& _ : score_names) {
                    (void)_;
                    builder.emplace_back(block_size);
                }
            }
            for (const auto& [idx, name] : iter::enumerate(score_names)) {
                auto postings = index.scored_postings(term_id, name);
                for (auto&& posting : postings) {
                    auto id = posting.document();
                    auto shard = shard_mapping_[id];
                    builders[shard][idx].add(posting.payload());
                }
            }
            return builders;
        }

        template<typename DocumentList>
        std::vector<document_t> document_vector(const DocumentList& documents)
        {
            return std::vector<document_t>(documents.begin(), documents.end());
        }

        template<typename FreqList>
        std::vector<frequency_t> frequency_vector(const FreqList& frequencies)
        {
            return std::vector<frequency_t>(
                frequencies.begin(), frequencies.end());
        }

        template<typename Index>
        std::vector<std::vector<inverted_index_view::score_type>> score_vectors(
            const Index& index,
            term_id_t term_id,
            const std::vector<std::string>& score_names)
        {
            std::vector<std::vector<inverted_index_view::score_type>>
                score_vectors(score_names.size());
            for (const auto& [idx, name] : iter::enumerate(score_names)) {
                auto scores = index.scores(term_id, name);
                score_vectors[idx] =
                    std::vector<inverted_index_view::score_type>(
                        scores.begin(), scores.end());
            }
            return score_vectors;
        }

        /// Partitions all posting-like data.
        inline auto postings_once()
        {
            auto log = spdlog::get("partition");
            Vector<ShardId, frequency_t> total_occurrences;
            auto source = irtl::value(
                Inverted_Index_Mapped_Source::from(input_dir_, index::all_score_names(input_dir_)));
            inverted_index_view index(source);
            auto score_names = index.score_names();

            Vector<ShardId, index::posting_vectors> vectors(shard_count_,
                                                            index::posting_vectors(score_names));
            Vector<ShardId, index::posting_streams<std::ofstream>> outputs;
            for (ShardId shard : ShardId::range(shard_dirs_.size())) {
                outputs.emplace_back(
                    shard_dirs_[shard], score_names, vectors[shard]);
            }
            auto term_count = index.term_count();
            for (auto term_id : iter::range(term_count)) {
                if (log and term_id % 100000 == 0) {
                    log->info("Partitioning postings for term {}/{}", term_id, term_count);
                }
                auto documents = document_vector(index.documents(term_id));
                auto frequencies = frequency_vector(index.frequencies(term_id));
                auto scores = score_vectors(index, term_id, score_names);

                const auto& block_size = index.skip_block_size();
                Vector<ShardId, document_builder_type> document_builders(
                    shard_count_, document_builder_type(block_size));
                Vector<ShardId, frequency_builder_type> frequency_builders(
                    shard_count_, frequency_builder_type(block_size));
                Vector<ShardId, std::vector<score_builder_type>> score_builders(
                    shard_count_,
                    std::vector<score_builder_type>(score_names.size(),
                                                    score_builder_type(block_size)));
                for (auto idx : iter::range(documents.size())) {
                    auto id = documents[idx];
                    auto shard = shard_mapping_[id];
                    auto local_doc_id = document_mapping_[id];
                    document_builders[shard].add(local_doc_id);
                    frequency_builders[shard].add(frequencies[idx]);
                    for (auto i : iter::range(score_names.size())) {
                        score_builders[shard][i].add(scores[i][idx]);
                    }
                }
                for (ShardId shard : ShardId::range(shard_count_)) {
                    auto& document_builder = document_builders[shard];
                    if (document_builder.size() > 0) {
                        outputs[shard].write(
                            term_id,
                            document_builder,
                            frequency_builders[shard],
                            score_builders[shard]);
                    }
                }
            }
            if (log) {
                log->info("Writing vectors");
            }
            for (ShardId shard : ShardId::range(shard_count_)) {
                total_occurrences.push_back(vectors[shard].total_occurrences);
                vectors[shard].write(
                    input_dir_,
                    shard_dirs_[shard],
                    index.terms().keys_per_block(),
                    score_names);
            }
            return total_occurrences;
        }

        /// Partitions all posting-like data.
        inline auto postings(size_t terms_in_batch)
        {
            auto log = spdlog::get("partition");
            auto source = irtl::value(
                Inverted_Index_Mapped_Source::from(input_dir_, index::all_score_names(input_dir_)));
            inverted_index_view index(source);
            Vector<ShardId, frequency_t> total_occurrences;
            for (const auto& [shard, shard_dir] :
                 iter::zip(ShardId::range(shard_count_), shard_dirs_))
            {
                if (log) {
                    log->info(
                        "Partitioning postings for shard {}",
                        static_cast<size_t>(shard));
                }
                index::posting_vectors vectors(index.score_names());
                index::posting_streams<std::ofstream> out(
                    shard_dir,
                    index.score_names(),
                    vectors,
                    std::ios_base::binary);
                for (auto term_id : iter::range(index.term_count())) {
                    auto document_builder =
                        filter_document_lists(index.documents(term_id), shard);
                    if (document_builder.size() > 0) {
                        auto freq_builder = filter_freq_lists(index.postings(term_id), shard);
                        auto score_builders = filter_score_lists(
                            index, term_id, index.score_names(), shard);
                        out.write(term_id, document_builder, freq_builder, score_builders);
                    }
                }
                total_occurrences.push_back(vectors.total_occurrences);
                vectors.write(
                    input_dir_,
                    shard_dirs_[shard],
                    index.terms().keys_per_block(),
                    index.score_names());
            }
            return total_occurrences;
        }

        [[nodiscard]] std::vector<std::string> scores_with_stats() const
        {
            auto score_stats = index::find_score_stats_paths(input_dir_);
            std::vector<std::string> names;
            irk::transform_range_if(score_stats,
                                    std::back_inserter(names),
                                    [](auto const& entry) -> std::string { return entry.first; },
                                    [](auto const& entry) -> bool {
                                        auto const& stats = entry.second;
                                        return stats.max or stats.mean or stats.var;
                                    });
            return names;
        }

        /// Partitions the entire index.
        nonstd::expected<void, std::string> index()
        {
            try {
                auto log = spdlog::get("partition");
                if (log) {
                    for (auto const& score_name : scores_with_stats()) {
                        log->warn(
                            "Detected score statistics for {} that will NOT be computed for shards "
                            "at this point. Run `irk-scorestats` to do so.",
                            score_name);
                    }
                }
                for (const auto& path : shard_dirs_) {
                    boost::filesystem::create_directory(path);
                }
                titles();
                auto [avg_sizes, max_sizes] = sizes();
                auto total_occurrences = postings_once();
                Vector<ShardId, size_t> document_counts(shard_count_, 0);
                for (const auto& shard : shard_mapping_) {
                    document_counts[shard] += 1;
                }
                write_properties(
                    document_counts, avg_sizes, max_sizes, total_occurrences);
                write_reverse_mappings();
                copy_term_tables();
                return nonstd::expected<void, std::string>();
            } catch (boost::filesystem::filesystem_error& error) {
                return nonstd::make_unexpected(std::string(error.what()));
            }
        }

        inline void write_reverse_mappings() const
        {
            for (auto&& [idx, dir] : enumerate(shard_dirs_)) {
                std::ofstream os((dir / "reverse.map").string());
                io::write_vector(reverse_mapping_[ShardId(idx)].as_vector(),
                                 os);
            }
        }

        inline void copy_term_tables()
        {
            auto copy = [](auto from, auto to) {
                boost::filesystem::copy_file(
                    from, to, boost::filesystem::copy_option::overwrite_if_exists);
            };
            auto cluster_dir = shard_dirs_.begin()->parent_path();
            copy(index::term_doc_freq_path(input_dir_), index::term_doc_freq_path(cluster_dir));
            copy(index::term_occurrences_path(input_dir_),
                 index::term_occurrences_path(cluster_dir));
            copy(index::term_map_path(input_dir_), index::term_map_path(cluster_dir));
            for (auto const& [name, path] : index::find_score_stats_paths(input_dir_)) {
                if (path.max) {
                    copy(path.max.value(), cluster_dir / fmt::format("{}.max", name));
                }
                if (path.mean) {
                    copy(path.mean.value(), cluster_dir / fmt::format("{}.mean", name));
                }
                if (path.var) {
                    copy(path.var.value(), cluster_dir / fmt::format("{}.var", name));
                }
            }
        }

        inline void write_properties(const Vector<ShardId, size_t>& document_counts,
                                     const Vector<ShardId, size_t>& avg_document_sizes,
                                     const Vector<ShardId, size_t>& max_document_sizes,
                                     const Vector<ShardId, frequency_t>& total_occurrences)
        {
            auto input_props = index::Properties::read(input_dir_);

            for (auto&& [idx, dir] : enumerate(shard_dirs_)) {
                ShardId shard(idx);
                index::Properties shard_props{};
                shard_props.document_count = document_counts[shard];
                shard_props.occurrences_count = total_occurrences[shard];
                shard_props.skip_block_size = input_props.skip_block_size;
                shard_props.avg_document_size = avg_document_sizes[shard];
                shard_props.max_document_size = max_document_sizes[shard];
                index::Properties::write(shard_props, dir);
            }

            input_props.shard_count = shard_count_;
            index::Properties::write(
                input_props,
                shard_dirs_.begin()->parent_path() / "properties.json");
        }

        const int32_t shard_count_;
        const int32_t document_count_;
        const path& input_dir_;
        const Vector<ShardId, path>& shard_dirs_;
        const Vector<document_t, ShardId>& shard_mapping_;
        const Vector<document_t>& document_mapping_;
        const Vector<ShardId, Vector<document_t>>& reverse_mapping_;
    };

}  // namespace detail::partition

/// Partitions an inverted index in `input_path` into `shard_count` shards
/// described by `shard_mapping`, writing them to `output_dir`.
///
/// \param input_dir        an index directory
/// \param output_dir       a directory to write the resulting shards to
/// \param shard_mapping    `i`-th value is the shard assigned to document `i`
/// \param shard_count      total number of shards
nonstd::expected<void, std::string>
partition_index(const path& input_dir,
                const path& output_dir,
                const Vector<document_t, ShardId>& shard_mapping,
                int shard_count)
{
    int32_t document_count = shard_mapping.size();
    auto shard_dirs = detail::partition::resolve_paths(output_dir, shard_count);
    auto document_mapping = detail::partition::compute_document_mapping(shard_mapping, shard_count);
    auto reverse_mapping = detail::partition::compute_reverse_mapping(shard_mapping, shard_count);
    auto log = spdlog::get("partition");
    if (log) {
        log->info("Partitioning index {} into {} shards in {}",
                  input_dir.string(),
                  shard_count,
                  output_dir.string());
    }
    auto partition = detail::partition::Partition(shard_count,
                                                  document_count,
                                                  input_dir,
                                                  shard_dirs,
                                                  shard_mapping,
                                                  document_mapping,
                                                  reverse_mapping);
    return partition.index();
}

}  // namespace irk

max_stars_repo_name: elshize/irkit

max_issues_repo_name: elshize/irkit

max_forks_repo_name: elshize/irkit


text:
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>

#include "wml_parser.hpp"

#include <iostream>
#include <string>
#include <vector>

////////////////////////////////////////////////////////////////////////////
//  Main program
////////////////////////////////////////////////////////////////////////////
int main() {
	std::cout << "/////////////////////////////////////////////////////////\n\n";
	std::cout << "\t\tAn attribute parser for Spirit...\n\n";
	std::cout << "/////////////////////////////////////////////////////////\n\n";

	std::cout << "Give me an attribute.\n";
	std::cout << "Type [q or Q] to quit\n\n";

	std::string str;
	while (getline(std::cin, str)) {
		if (str.empty() || str[0] == 'q' || str[0] == 'Q')
			break;

		if (wml::parse_attr(str)) {
			std::cout << "-------------------------\n";
			std::cout << "Parsing succeeded\n";
			std::cout << str << " Parses OK: " << std::endl;
		} else {
			std::cout << "-------------------------\n";
			std::cout << "Parsing failed\n";
			std::cout << "-------------------------\n";
		}
	}

	std::cout << "Bye... :-) \n\n";
	return 0;
}


text: #include <boost/fiber/segmented_stack.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef qlex_multibootstrap_hpp
#define qlex_multibootstrap_hpp

#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>
#include <ql/termstructures/bootstraphelper.hpp>
#include <ql/math/optimization/costfunction.hpp>
#include <ql/math/optimization/constraint.hpp>
#include <ql/math/optimization/armijo.hpp>
#include <ql/math/optimization/levenbergmarquardt.hpp>
#include <ql/math/optimization/leastsquare.hpp>
#include <ql/math/optimization/problem.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <ql/termstructures/iterativebootstrap.hpp>
#include <ql/patterns/lazyobject.hpp>
#include <boost/shared_ptr.hpp>

using namespace QuantLib;

namespace QLExtension {
	// penalty function class for multiple curve
	template <class Curve>
	class MultiCurvePenaltyFunction : public CostFunction {
	public:
		typedef typename Curve::traits_type Traits;
		typedef typename Traits::helper helper;
		typedef
			typename std::vector< boost::shared_ptr<helper> >::const_iterator helper_iterator;

		MultiCurvePenaltyFunction(std::vector<Curve*> curves,
			std::vector<Size> initialIndexes,
			std::vector<helper_iterator> rateHelpersStarts,
			std::vector<helper_iterator> rateHelpersEnds)
			: curves_(curves), initialIndexes_(initialIndexes),
			rateHelpersStarts_(rateHelpersStarts), rateHelpersEnds_(rateHelpersEnds) {
		}

		Real value(const Array& x) const;
		Disposable<Array> values(const Array& x) const;

	private:
		std::vector<Curve*> curves_;
		std::vector<Size> initialIndexes_;
		std::vector<helper_iterator> rateHelpersStarts_;
		std::vector<helper_iterator> rateHelpersEnds_;
	};

	template <class Curve>
	class MultiCurveOptimizer : public LazyObject {
	public:
		MultiCurveOptimizer(bool forcePositive = true)
			: accuracy_(1.0e-12), forcePositive_(forcePositive){};
		void addTermStructure(Curve* c) {
			for (Size i = 0; i<c->instruments_.size(); ++i){
				this->registerWith(c->instruments_[i]);
			}
			ts_.push_back(c);
			accuracy_ = accuracy_ > c->accuracy_ ? c->accuracy_ : accuracy_;
		};
		void optimize() const { calculate(); };
		//! \name Observer interface
		//@{
		void update();
		//@}
	private:
		//! \name LazyObject interface
		//@{
		void performCalculations() const;
		//@}
		Real accuracy_;
		bool forcePositive_;
		std::vector<Curve*> ts_;
	};

	template <class Curve>
	void MultiCurveOptimizer<Curve>::update() {
		LazyObject::update();
	}

	template <class Curve>
	void MultiCurveOptimizer<Curve>::performCalculations() const {

		std::vector<Size> initialIndexes;
		std::vector< typename MultiCurvePenaltyFunction<Curve>::helper_iterator > rateHelpersStarts;
		std::vector< typename MultiCurvePenaltyFunction<Curve>::helper_iterator > rateHelpersEnds;

		Size nInsts = 0;
		for (Size i = 0; i < ts_.size(); i++) {
			ts_[i]->bootstrap_.initialize();
			nInsts += ts_[i]->instruments_.size();
			initialIndexes.push_back(1);
			rateHelpersStarts.push_back(ts_[i]->instruments_.begin());
			rateHelpersEnds.push_back(ts_[i]->instruments_.end());
		}

		LevenbergMarquardt solver(accuracy_,
			accuracy_,
			accuracy_);

		EndCriteria endCriteria(20 * nInsts, 10, 0.00, accuracy_, 0.00);
		PositiveConstraint posConstraint;
		NoConstraint noConstraint;
		Constraint& solverConstraint = forcePositive_ ?
			static_cast<Constraint&>(posConstraint) :
			static_cast<Constraint&>(noConstraint);

		Array startArray(nInsts);

		Size pos = 0;
		for (Size i = 0; i < ts_.size(); i++) {
			for (Size j = 0; j < ts_[i]->instruments_.size(); j++) {
				startArray[pos] = ts_[i]->data_[j + initialIndexes[i]];
				pos++;
			}
		}

		MultiCurvePenaltyFunction<Curve> currentCost(
			ts_,
			initialIndexes,
			rateHelpersStarts,
			rateHelpersEnds);

		Problem toSolve(currentCost, solverConstraint, startArray);

		EndCriteria::Type endType = solver.minimize(toSolve, endCriteria);

		// check the end criteria
		QL_REQUIRE(endType == EndCriteria::StationaryFunctionAccuracy ||
			endType == EndCriteria::StationaryFunctionValue,
			"Unable to strip yieldcurve to required accuracy ");

	}

	//! multiple bootstrapper for simultanaous bootstrap of multiple curves.
	/*!
	\TODO: template <class Curve> should be unique for all curves.
	*/
	template <class Curve>
	class MultiBootstrap {
		typedef typename Curve::traits_type Traits;
		typedef typename Curve::interpolator_type Interpolator;
	public:

		MultiBootstrap(boost::shared_ptr<MultiCurveOptimizer<Curve> > optimizer =
			boost::shared_ptr<MultiCurveOptimizer<Curve> >(new MultiCurveOptimizer<Curve>()));
		void setup(Curve* ts);
		void calculate() const;

	private:
		friend MultiCurveOptimizer<Curve>;
		void initialize() const;
		mutable bool validCurve_;
		Curve* ts_;
		boost::shared_ptr<MultiCurveOptimizer<Curve> > multiCurveOptimizer_;
	};

	// template definitions

	template <class Curve>
	MultiBootstrap<Curve>::MultiBootstrap(boost::shared_ptr<MultiCurveOptimizer<Curve> > optimizer)
		: ts_(0), validCurve_(false), multiCurveOptimizer_(optimizer)
	{}

	template <class Curve>
	void MultiBootstrap<Curve>::setup(Curve* ts) {

		ts_ = ts;

		Size n = ts_->instruments_.size();
		QL_REQUIRE(n >= Interpolator::requiredPoints,
			"not enough instruments: " << n << " provided, " <<
			Interpolator::requiredPoints << " required");

		for (Size i = 0; i<n; ++i){
			ts_->registerWith(ts_->instruments_[i]);
		}

		multiCurveOptimizer_->addTermStructure(ts_);

	}

	template <class Curve>
	void MultiBootstrap<Curve>::initialize() const {

		Size nInsts = ts_->instruments_.size();

		// ensure rate helpers are sorted
		std::sort(ts_->instruments_.begin(), ts_->instruments_.end(),
			detail::BootstrapHelperSorter());

		// check that there is no instruments with the same maturity
		for (Size i = 1; i<nInsts; ++i) {
			Date m1 = ts_->instruments_[i - 1]->latestDate(),
				m2 = ts_->instruments_[i]->latestDate();
			QL_REQUIRE(m1 != m2,
				"two instruments have the same maturity (" << m1 << ")");
		}

		// check that there is no instruments with invalid quote
		for (Size i = 0; i<nInsts; ++i)
			QL_REQUIRE(ts_->instruments_[i]->quote()->isValid(),
			io::ordinal(i + 1) << " instrument (maturity: " <<
			ts_->instruments_[i]->latestDate() <<
			") has an invalid quote");

		// setup instruments
		for (Size i = 0; i<nInsts; ++i) {
			// don't try this at home!
			// This call creates instruments, and removes "const".
			// There is a significant interaction with observability.
			ts_->instruments_[i]->setTermStructure(const_cast<Curve*>(ts_));
		}
		// set initial guess only if the current curve cannot be used as guess
		if (validCurve_)
			QL_ENSURE(ts_->data_.size() == nInsts + 1,
			"dimension mismatch: expected " << nInsts + 1 <<
			", actual " << ts_->data_.size());
		else {
			ts_->data_ = std::vector<Rate>(nInsts + 1);
			ts_->data_[0] = Traits::initialValue(ts_);
		}

		// calculate dates and times
		ts_->dates_ = std::vector<Date>(nInsts + 1);
		ts_->times_ = std::vector<Time>(nInsts + 1);
		ts_->dates_[0] = Traits::initialDate(ts_);
		ts_->times_[0] = ts_->timeFromReference(ts_->dates_[0]);
		for (Size i = 0; i<nInsts; ++i) {
			ts_->dates_[i + 1] = ts_->instruments_[i]->latestDate();
			ts_->times_[i + 1] = ts_->timeFromReference(ts_->dates_[i + 1]);
			if (!validCurve_)
				ts_->data_[i + 1] = ts_->data_[i];
		}

		ts_->interpolation_ =
			ts_->interpolator_.interpolate(ts_->times_.begin(),
			ts_->times_.end(),
			ts_->data_.begin());

	}

	template <class Curve>
	void MultiBootstrap<Curve>::calculate() const {
		validCurve_ = false;
		multiCurveOptimizer_->optimize();
		validCurve_ = true;

	}

	template <class Curve>
	Real MultiCurvePenaltyFunction<Curve>::value(const Array& x) const {
		Array::const_iterator guessIt = x.begin();
		for (Size n = 0; n < curves_.size(); n++) {
			Size nInsts = curves_[n]->instruments_.size();
			Size i = initialIndexes_[n];
			for (Size j = 0; j < nInsts; j++) {
				Traits::updateGuess(curves_[n]->data_, *guessIt, j + i);
				++guessIt;
			}
			curves_[n]->interpolation_.update();
		}

		Real penalty = 0.0;
		for (Size n = 0; n < curves_.size(); n++) {
			helper_iterator instIt = rateHelpersStarts_[n];
			while (instIt != rateHelpersEnds_[n]) {
				Real quoteError = (*instIt)->quoteError();
				penalty += std::fabs(quoteError);
				++instIt;
			}
		}
		return penalty;
	}

	template <class Curve>
	Disposable<Array> MultiCurvePenaltyFunction<Curve>::values(const Array& x) const {
		Array::const_iterator guessIt = x.begin();
		for (Size n = 0; n < curves_.size(); n++) {
			Size nInsts = curves_[n]->instruments_.size();
			Size i = initialIndexes_[n];
			for (Size j = 0; j < nInsts; j++) {
				Traits::updateGuess(curves_[n]->data_, *guessIt, j + i);
				++guessIt;
			}
			curves_[n]->interpolation_.update();
		}

		Array penalties(x.size());
		Array::iterator penIt = penalties.begin();
		for (Size n = 0; n < curves_.size(); n++) {
			helper_iterator instIt = rateHelpersStarts_[n];
			while (instIt != rateHelpersEnds_[n]) {
				Real quoteError = (*instIt)->quoteError();
				*penIt = std::fabs(quoteError);
				++instIt;
				++penIt;
			}
		}
		return penalties;
	}
}

#endif


text:
#pragma once
#include <boost/property_tree/ptree.hpp>
#include <boost/algorithm/string.hpp>
#include "network/traits/traits.hpp"
#include "network/meta/meta.hpp"
#include "network/util/cast.hpp"
#include "network/util/string.hpp"
#include "detail/parser.hpp"
#include "network/base/date_time.hpp"

namespace cytx
{
    namespace detail
    {
        using namespace boost::property_tree;

        enum class node_type { object, array, value, null };

        struct xml_node
        {
            node_type type;
            std::string key;
            ptree val;

            xml_node(xml_node&& node)
                : key(std::move(node.key))
                , val(std::move(node.val))
                , type(node.type) {}
            xml_node(node_type t) : type(t) {}
            xml_node(xml_node& node) : key(node.key), val(node.val), type(node.type) {}

            xml_node& operator=(xml_node&& node)
            {
                key = std::move(node.key);
                val = std::move(node.val);
                type = node.type;
                return *this;
            }

            void reset(node_type t)
            {
                type = t;
                key = "";
                val.clear();
            }
        };

        template<typename T>
        class base_serialize_adapter
        {
        public:
            enum { use_field_separator = 0, use_begin_map = 0 };

            base_serialize_adapter() {}

            void begin_serialize(const std::string& key = "")
            {
                nodes_.clear();
                nodes_.emplace_back(xml_node(node_type::object));
                cur_node_.reset(node_type::value);
                cur_node_.key = key.empty() ? "+" : key;
            }
            void end_serialize()
            {
                if (cur_node_.type != node_type::null && !(cur_node_.key.empty() && cur_node_.val.data().empty() && cur_node_.val.empty()))
                {
                    if (cur_node_.key.empty())
                        cur_node_.key = "+";
                    nodes_.emplace_back(cur_node_);
                }
                while (nodes_.size() > 1)
                {
                    auto& pt = nodes_[nodes_.size() - 2];
                    auto& node = nodes_.back();
                    pt.val.add_child(node.key.empty() ? "+" : node.key, node.val);
                    nodes_.pop_back();
                }

                auto node = nodes_.back();
                std::stringstream ss;
                T::write(ss, node.val);
                buf_ = ss.str();
            }
            void begin_object()
            {
                if (cur_node_.type == node_type::value)
                {
                    if (!cur_node_.val.data().empty())
                    {
                        nodes_.back().val.add_child(cur_node_.key.empty() ? "+" : cur_node_.key, cur_node_.val);
                        cur_node_.reset(node_type::object);
                    }
                    else
                    {
                        cur_node_.type = node_type::object;
                    }
                }
                else if (cur_node_.type == node_type::null)
                {
                    cur_node_.type = node_type::object;
                }
                nodes_.emplace_back(cur_node_);
                cur_node_.reset(node_type::value);
            }
            void end_object()
            {
                auto node = nodes_.back();
                nodes_.pop_back();
                if (cur_node_.type != node_type::null && (!cur_node_.key.empty() || !cur_node_.val.data().empty()))
                {
                    node.val.add_child(cur_node_.key, cur_node_.val);
                }
                nodes_.back().val.add_child(node.key.empty() ? "+" : node.key, node.val);
                cur_node_.reset(node_type::value);
            }
            void begin_array(size_t)
            {
                if (cur_node_.type == node_type::value)
                {
                    if (!cur_node_.val.data().empty())
                    {
                        nodes_.back().val.add_child(cur_node_.key.empty() ? "+" : cur_node_.key, cur_node_.val);
                        cur_node_.reset(node_type::object);
                    }
                    else
                    {
                        cur_node_.type = node_type::object;
                    }
                }
                nodes_.emplace_back(cur_node_);
                cur_node_.reset(node_type::array);
                nodes_.emplace_back(cur_node_);
                cur_node_.reset(node_type::value);
            }
            void end_array()
            {
                auto node = nodes_.back();
                nodes_.pop_back();
                if (cur_node_.type == node_type::value)
                {
                    if (!cur_node_.key.empty() || !cur_node_.val.data().empty())
                    {
                        if (node.val.empty() && node.type != node_type::array)
                            node.val = cur_node_.val;
                        else
                            node.val.add_child(cur_node_.key.empty() ? "+" : cur_node_.key, cur_node_.val);
                    }
                }
                else if(cur_node_.type != node_type::null)
                {
                    if (node.val.empty() && node.type != node_type::array)
                        node.val = cur_node_.val;
                    else
                        node.val.add_child(cur_node_.key.empty() ? "+" : cur_node_.key, cur_node_.val);
                }

                auto obj_node = nodes_.back();
                nodes_.pop_back();
                if (obj_node.val.empty() && obj_node.type != node_type::array)
                    obj_node.val = node.val;
                else
                    obj_node.val.add_child(node.key.empty() ? "+" : node.key, node.val);

                nodes_.back().val.add_child(obj_node.key.empty() ? "+" : obj_node.key, obj_node.val);
                cur_node_.reset(node_type::value);
            }
            void begin_fixed_array(size_t s) { begin_array(s); }
            void end_fixed_array() { end_array(); }

            void write_key_name(const std::string& str) { write_key(str); }

            template<typename T1>
            void write_key(T1&& t)
            {
                if (cur_node_.type == node_type::null)
                {
                    cur_node_.reset(node_type::value);
                }
                if (cur_node_.key.empty())
                {
                    auto str = fmt::format("{}", t);
                    if (string_util::contains_chars(str, "@,.<>\"'/&; \t\r\n"))
                    {
                        cur_node_.key = "@key";
                        cur_node_.val.add("<xmlattr>.name", str);
                    }
                    else
                        cur_node_.key = str;
                }
                else
                {
                    auto& node = nodes_.back();
                    node.val.add_child(cur_node_.key, cur_node_.val);
                    auto type = cur_node_.type;
                    cur_node_.reset(type);
                    cur_node_.key = fmt::format("{}", t);
                }
            }

            template<typename T1>
            void write(T1&& t)
            {
                if (cur_node_.type == node_type::array)
                {
                    ptree p;
                    p.put_value(t);
                    cur_node_.val.add_child(cur_node_.key.empty() ? "+" : cur_node_.key, p);
                }
                else if (cur_node_.type == node_type::value)
                {
                    if (cur_node_.val.data().empty())
                        cur_node_.val.put_value(t);
                    else
                    {
                        nodes_.back().val.add_child(cur_node_.key.empty() ? "+" : cur_node_.key, cur_node_.val);
                        cur_node_.val.put_value(t);
                    }
                }
                else if(cur_node_.type != node_type::null)
                {
                    cur_node_.val.put_value(t);
                }
            }

            void write(const date_time& t)
            {
                std::string str = t.to_string();
                write(str);
            }

            void write_is_null(bool is_null)
            {
                if (is_null)
                {
                    cur_node_.reset(node_type::null);
                }
            }

            std::string str() { return buf_; }
        private:
            xml_node cur_node_{ node_type::value };
            std::vector<xml_node> nodes_;
            std::string buf_;
        };
    }

    using xml_serialize_adapter = detail::base_serialize_adapter<xml_parser>;
    using ini_serialize_adapter = detail::base_serialize_adapter<ini_parser>;
    using info_serialize_adapter = detail::base_serialize_adapter<info_parser>;
}

namespace cytx
{
    namespace detail
    {
        using namespace boost::property_tree;
        using namespace std;

        template<typename T>
        class base_deserialize_adapter
        {
        public:
            using value_t = ptree;
            using array_iterator = ptree::iterator;
            using member_iterator = ptree::iterator;
            using properties_map = std::unordered_map<std::string, std::string>;

            base_deserialize_adapter(const properties_map* properties = nullptr)
                : default_properties_(properties)
            {}
            void parse(const char* str) { parse(string(str)); }
            void parse(const char* str, size_t len) { parse(string(str, len)); }
            void parse(const std::string& str)
            {
                stringstream ss;
                ss << str;
                T::read(ss, pt_);
                init();
            }

            void parse_file(const std::string& file, bool with_whitespace = false)
            {
                T::read_file(with_whitespace, file, pt_);
                init(with_whitespace);
            }

            value_t& get_root(const char* key, bool has_root = true)
            {
                if (!has_root || key == nullptr)
                {
                    if (pt_.size() > 1)
                        return pt_;
                    else
                        return pt_.get_child("+");
                }

                auto child = pt_.get_child_optional(key);
                if (!child)
                    throw std::invalid_argument(fmt::format("the key \"{}\" is not exist", key));

                return child.get();
            }

            size_t array_size(value_t& val) { return val.size(); }
            array_iterator array_begin(value_t& val) { return val.begin(); }
            array_iterator array_end(value_t& val) { return val.end(); }
            value_t& it_val(array_iterator& it) { return it->second; }
            array_iterator array_it(value_t& val, size_t index)
            {
                auto it = array_begin(val);
                while (index > 0)
                {
                    ++it;
                    --index;
                }
                return it;
            }

            bool is_valid(array_iterator& it) const
            {
                return it->first != "<xmlattr>";
            }

            size_t member_size(value_t& val) { return val.size(); }
            member_iterator member_begin(value_t& val) { return val.begin(); }
            member_iterator member_end(value_t& val) { return val.end(); }
            member_iterator member_it(value_t& val, size_t index)
            {
                auto it = member_begin(val);
                while (index > 0)
                {
                    ++it;
                    --index;
                }
                return it;
            }

            bool has_member(const char* key, value_t& val) { return val.find(key) != val.not_found(); }
            member_iterator get_member(const char* key, value_t& val)
            {
                auto it = val.find(key);
                if (it == val.not_found())
                {
                    auto attr = val.get_child_optional("<xmlattr>");
                    if (attr)
                    {
                        auto it_key = attr->find(key);
                        if (it_key != attr->not_found())
                        {
                            return attr->to_iterator(it_key);
                        }
                    }
                }
                return val.to_iterator(it);
            }

            template<typename T1>
            void read(T1& t, value_t& val)
            {
                auto str = val.data();

                auto extend_func = [this](const std::string& prop, std::string& val) -> bool {
                    auto it = properties_.find(prop);
                    if (it != properties_.end())
                    {
                        val = it->second;
                        return true;
                    }

                    if (default_properties_)
                    {
                        auto dit = default_properties_->find(prop);
                        if (dit != default_properties_->end())
                        {
                            val = dit->second;
                            return true;
                        }
                    }

                    return false;
                };

                bool is_extend = string_util::extend_all(str, "$(", ")", extend_func);
                t = is_extend ? util::cast<T1>(str) : val.get_value<T1>();
            }

            bool is_null(value_t& val)
            {
                return false;
            }

            std::string first(member_iterator& it)
            {
                if (it->first != "@key" && it->first != "+")
                {
                    return it->first;
                }
                if (it->first == "@key")
                {
                    auto name = (it->second).get_optional<std::string>("<xmlattr>.name");
                    if (name)
                        return name.value();
                }
                else
                {
                    auto name = (it->second).get_optional<std::string>("<xmlattr>.key");
                    if (name)
                        return name.value();
                }
                return it->first;
            }

            value_t& second(member_iterator& it)
            {
                return it->second;
            }

            void process_array(value_t& val)
            {
                if (val.data().empty())
                    return;

                std::string str_val = val.data();
                auto values = string_util::split(str_val, ",;");
                if (values.empty())
                    return;

                val.put_value("");
                for (auto& s : values)
                {
                    val.add("+", s);
                }
            }

        private:
            void init(bool with_whitespace = false)
            {
                if (pt_.empty())
                    return;

                parse_using(pt_);

                auto& tmp_pt = pt_.begin()->second;
                for (auto it = tmp_pt.begin(); it != tmp_pt.end();)
                {
                    auto& p = *it;
                    if (p.first == "property_group")
                    {
                        for (auto& prop : p.second)
                        {
                            read(properties_[prop.first], prop.second);
                        }
                    }
                    else if (p.first == "import")
                    {
                        auto& import_pt = p.second;
                        ptree other_pt;
                        auto mb_it = get_member("path", import_pt);
                        if (mb_it != member_end(import_pt))
                        {
                            std::string path;
                            read<std::string>(path, second(mb_it));
                            T::read_file(with_whitespace, path, other_pt);

                            for (auto& op : other_pt.begin()->second)
                            {
                                tmp_pt.push_back(op);
                            }
                            it = tmp_pt.erase(it);
                            continue;
                        }
                    }
                    ++it;
                }
            }

            void parse_using(ptree& pt)
            {
                if (pt.empty())
                    return;

                auto& tmp_pt = pt;
                for (auto it = tmp_pt.begin(); it != tmp_pt.end();)
                {
                    auto& p = *it;
                    if (p.first == "using")
                    {
                        auto& using_pt = p.second;
                        auto mb_it = get_member("node", using_pt);
                        if (mb_it != member_end(using_pt))
                        {
                            std::string node_path;
                            read<std::string>(node_path, second(mb_it));
                            auto other_pt = pt_.get_child_optional(node_path);
                            if (other_pt)
                            {
                                it = tmp_pt.erase(it);
                                for (auto& op : other_pt.get())
                                {
                                    tmp_pt.add_child(fmt::format("<xmlattr>.{}", op.first), op.second);
                                }
                                continue;
                            }
                        }
                        ++it;
                    }
                    else if (p.first == "<xmlattr>")
                    {
                        auto node_path_optional = p.second.get_optional<std::string>("using");
                        if (node_path_optional)
                        {
                            auto other_pt = pt_.get_child_optional(node_path_optional.get());
                            if (other_pt)
                            {
                                p.second.erase("using");
                                for (auto& op : other_pt.get())
                                {
                                    p.second.push_back(op);
                                }
                            }
                        }
                        ++it;
                    }
                    else
                    {
                        parse_using(p.second);
                        ++it;
                    }
                }
            }

            void debug(const ptree& pt, bool debug_pt = true)
            {
                std::stringstream ss;
                T::write(ss, pt);
                std::string str = ss.str();

                if (debug_pt)
                    debug(pt_, false);
            }

            void debug()
            {
                debug(pt_, false);
            }
        protected:
            ptree pt_;
            properties_map properties_;
            const properties_map* default_properties_;
        };
    }

    using xml_deserialize_adapter = detail::base_deserialize_adapter<xml_parser>;
    using ini_deserialize_adapter = detail::base_deserialize_adapter<ini_parser>;
    using info_deserialize_adapter = detail::base_deserialize_adapter<info_parser>;
}

max_stars_repo_name: hbccdf/network-core

max_issues_repo_name: hbccdf/network-core

max_forks_repo_name: hbccdf/network-core


text:
#include<process.h>
#include<functional>
#include "daemon.h"
#include "utilities.h"
#include "globalVariables.h"
#include "fileManager.h"
#define BOOST_USE_WINDOWS_H
#include <boost/interprocess/managed_windows_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>

using std::wstring;
using std::string;
namespace bi = boost::interprocess;

#define common_shared_memory_name "Local\\GCSDokan_mount_point_list"

//GCSDokan running instance in the shared memory
// map: mount point -> remote link
typedef bi::allocator<WCHAR, bi::managed_windows_shared_memory::segment_manager> CharAllocator;
typedef bi::basic_string<WCHAR, std::char_traits<WCHAR>, CharAllocator> ShmString;
typedef std::pair<const ShmString, ShmString> ValueType;
typedef bi::allocator<ValueType, bi::managed_windows_shared_memory::segment_manager> ShmemAllocator;
typedef bi::map<ShmString, ShmString, std::less<ShmString>, ShmemAllocator> shared_map;

//This shared memory object stores all the running gcs instance.
static bi::managed_windows_shared_memory* segment = nullptr;
static shared_map* gcs_instance_list = nullptr;
static bi::managed_windows_shared_memory* existance_indicator = nullptr;
bi::named_mutex mutex(bi::open_or_create, "GCSDokan_mount_point_list");

static std::hash<wstring> hash_object;

/*
========================================================================================
Functions to get keys and utilities
========================================================================================
*/
wstring add_white_space(wstring str, size_t maxLength) {
	size_t i, length;
	length = str.length();
	for (i = length; i < maxLength; i++)
		str = str + L" ";
	return str;
};

static wstring get_key(wstring key) {
	return L"GCSDokan_" + std::to_wstring(hash_object(key));
}

static wstring get_pip_name(wstring key) {
	return L"\\\\.\\pipe\\" + get_key(key);
}

static wstring get_shared_memory_name(wstring key) {
	return L"Local\\" + get_key(key);
}

/*
========================================================================================
Functions to store all running GCSDokan instance in shared memory
========================================================================================
*/
static bool has_shared_memory(string key)
{
	try
	{
		bi::managed_windows_shared_memory segment(bi::open_only, key.c_str());
		return true;
	}
	catch (const std::exception)
	{
		return false;
	}
}

static bool exist_instance(ShmString mount_point) {
	string key = wstringToString(get_shared_memory_name(mount_point.c_str()));
	return has_shared_memory(key.c_str());
}

static void remove_unexist_instance_from_list() {
	auto itr = gcs_instance_list->begin();
	while (itr != gcs_instance_list->end()) {
		if (!exist_instance(itr->first)) {
			itr = gcs_instance_list->erase(itr);
		}
		else {
			++itr;
		}
	}
}

static bool initial_gcs_instance_list()
{
	if (gcs_instance_list != nullptr)
		return true;
	try
	{
		if (segment != nullptr) {
			delete segment;
		}
		//Initialize the instance list
		if (!has_shared_memory(common_shared_memory_name)) {
			boost::interprocess::permissions perm;
			perm.set_unrestricted();
			segment = new bi::managed_windows_shared_memory(bi::create_only, common_shared_memory_name, 1024 * 1024, 0, perm);
			//allocate the instance list
			ShmemAllocator alloc_inst(segment->get_segment_manager());
			gcs_instance_list = segment->construct<shared_map>("instance_list")(std::less<ShmString>(), alloc_inst);
		}
		else {
			segment = new bi::managed_windows_shared_memory(bi::open_only, common_shared_memory_name);
			//allocate or open the instance list
			ShmemAllocator alloc_inst(segment->get_segment_manager());
			gcs_instance_list = segment->find<shared_map>("instance_list").first;
		}
	}
	catch (const std::exception& ex)
	{
		error_print("Unable to initiate shared memory space: %s\n", ex.what());
		return false;
	}
	if (gcs_instance_list == nullptr) {
		error_print("Unable to create instance list\n");
		return false;
	}
	//Remove the unexist instance
	remove_unexist_instance_from_list();
	return true;
}

static bool create_existance_indicator() {
	//Create a placeholder in the shared memory which will be destroyed when the instance is closed.
	try
	{
		string key = wstringToString(get_shared_memory_name(get_mount_point()));
		boost::interprocess::permissions perm;
		perm.set_unrestricted();
		//We do this memory leaking on purpose
		existance_indicator = new bi::managed_windows_shared_memory(bi::create_only, key.c_str(), 512, 0, perm);
	}
	catch (const std::exception& ex)
	{
		error_print("Unable to create existance indicator: %s\n", ex.what());
		return false;
	}
	//Insert key and value to the instance list
	ShmString map_key(get_mount_point().c_str(), segment->get_allocator<ShmString>());
	ShmString map_value(get_remote_link().c_str(), segment->get_allocator<ShmString>());
	gcs_instance_list->insert(ValueType(map_key, map_value));

	return true;
}

/*
========================================================================================
Functions to kill a GCSDokan instance when receive a signal
========================================================================================
*/

static unsigned __stdcall thread_monitor_function(void*)
{
	wstring pip_name = get_pip_name(get_mount_point());
	HANDLE pipe = CreateNamedPipe(
		pip_name.c_str(), // name of the pipe
		PIPE_ACCESS_INBOUND, // 1-way pipe -- receive only
		PIPE_TYPE_BYTE, // get data as a byte stream
		1, // only allow 1 instance of this pipe
		0, // no outbound buffer
		0, // no inbound buffer
		0, // use default wait time
		NULL // use default security attributes
	);
	if (pipe == NULL || pipe == INVALID_HANDLE_VALUE) {
		ExitProcess(ERROR_BAD_PIPE);
	}
	// The thread will be blocked by this function
	// until a process wants to connect to this pip
	BOOL result = ConnectNamedPipe(pipe, NULL);
	if (!result) {
		ExitProcess(ERROR_PIPE_NOT_CONNECTED);
	}
	else {
		CloseHandle(pipe);
		ExitProcess(0);
	}
	return 0;
}

/*
========================================================================================
Exported function
========================================================================================
*/
bool start_deamon()
{
	mutex.lock();
	bool success = initial_gcs_instance_list();
	if (!success) {
		mutex.unlock();
		return false;
	}
	success = create_existance_indicator();
	if (!success) {
		mutex.unlock();
		return false;
	}
	HANDLE handle;
	handle = (HANDLE)_beginthreadex(NULL, 0, thread_monitor_function,
		0, 0, 0);
	if (handle == NULL) {
		error_print("Unable to start the daemon!\n");
		mutex.unlock();
		return false;
	}
	mutex.unlock();
	return true;
}

void kill_process()
{
	wstring pip_name = get_pip_name(get_mount_point());
	HANDLE pipe = CreateFile(
		pip_name.c_str(),
		GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL
	);
	CloseHandle(pipe);
}

bool list_instances()
{
	mutex.lock();
	bool success = initial_gcs_instance_list();
	if (!success) {
		error_print("Unable to initiate shared memory space!\n");
		mutex.unlock();
		return false;
	}
	// Add padding space
	size_t mount_point_size = 11;
	for (auto i : *gcs_instance_list) {
		mount_point_size = max(i.first.length(), mount_point_size);
	}
	std::vector<wstring> mount_points;
	std::vector<wstring> remote_links;
	mount_points.push_back(L"Mount Point");
	remote_links.push_back(L"Remote Link");

	for (auto i : *gcs_instance_list) {
		wstring mp = add_white_space(i.first.c_str(), mount_point_size);
		mount_points.push_back(mp);
		remote_links.push_back(i.second.c_str());
	}
	for (int i = 0; i < mount_points.size(); i++) {
		wprintf(L"%s\t\t%s\n", mount_points[i].c_str(), remote_links[i].c_str());
	}
	mutex.unlock();
	return true;
}

max_stars_repo_name: Jiefei-Wang/GCSDokan

max_issues_repo_name: Jiefei-Wang/GCSDokan

max_forks_repo_name: Jiefei-Wang/GCSDokan


text:
// Copyright 2018 Peter Dimov.
// Distributed under the Boost Software License, Version 1.0.

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

using namespace boost::system;

namespace lib1
{

error_code get_system_code();
error_code get_generic_code();

} // namespace lib1

namespace lib2
{

error_code get_system_code();
error_code get_generic_code();

} // namespace lib2

int main()
{
    BOOST_TEST_EQ( lib1::get_system_code(), lib2::get_system_code() );
    BOOST_TEST_EQ( lib1::get_generic_code(), lib2::get_generic_code() );

    return boost::report_errors();
}

max_forks_repo_name: ZeroInfinite/turicreate


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

#ifndef BOOST_URL_BNF_HPP
#define BOOST_URL_BNF_HPP

#include <boost/url/detail/config.hpp>

#include <boost/url/bnf/ascii.hpp>
#include <boost/url/bnf/charset.hpp>
#include <boost/url/bnf/parse.hpp>
#include <boost/url/bnf/range.hpp>
#include <boost/url/bnf/repeat.hpp>
#include <boost/url/bnf/token.hpp>

#endif

max_stars_repo_name: sandmanhome/liuguang

max_issues_repo_name: sandmanhome/liuguang

max_forks_repo_name: sandmanhome/liuguang


text:
/* Frame.cpp
 * -*- coding: utf-8 -*-
 *
 */

#include <boost/test/unit_test.hpp>

// system includes =============================================================

#include <vector>

// local includes ==============================================================

#include "../src/Frame.hpp"

#include "utils/log.hpp"

BOOST_AUTO_TEST_SUITE(Frame_test)

BOOST_AUTO_TEST_CASE(frame_successful_creation) {
    TEST_MESSAGE("frame_successful_creation");

    std::vector<double> x = {0, 1};
    std::vector<double> y = {2, 3};
    std::vector<double> z = {3, 4};
    Frame frame(x, y, z);

    BOOST_CHECK_EQUAL(frame.get_atom_positions().get_x()[0], x[0]);
    BOOST_CHECK_EQUAL(frame.get_atom_positions().get_y()[0], y[0]);
    BOOST_CHECK_EQUAL(frame.get_atom_positions().get_z()[0], z[0]);
    BOOST_CHECK_EQUAL(frame.get_atom_positions().get_x()[1], x[1]);
    BOOST_CHECK_EQUAL(frame.get_atom_positions().get_y()[1], y[1]);
    BOOST_CHECK_EQUAL(frame.get_atom_positions().get_z()[1], z[1]);
}

BOOST_AUTO_TEST_CASE(frame_failed_creation) {
    TEST_MESSAGE("frame_failed_creation");

    std::vector<double> x = {0};
    std::vector<double> y = {0, 1};
    std::vector<double> z = {0, 1, 2};
    BOOST_REQUIRE_THROW(Frame frame(x, y, z), std::runtime_error);
}

BOOST_AUTO_TEST_SUITE_END()

// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 fenc=utf-8

max_stars_repo_name: AFriemann/LowCarb

max_issues_repo_name: AFriemann/LowCarb

max_forks_repo_name: AFriemann/LowCarb


text:
// Copyright (C) 2006-2009, 2012 Alexander Nasonov
// Copyright (C) 2012 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0
// (see accompanying file LICENSE_1_0.txt or a copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Home at http://www.boost.org/libs/scope_exit

#include <boost/scope_exit.hpp>
#include <boost/rational.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/typeof/std/vector.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <vector>

template<class type>
void tpl_long(
      type tval
    , type & t
    , type const& tc
    , type volatile& tv
    , type const volatile& tcv
) {
    int i = 0; // non-dependent name
    type const remember(tval);

    {
        BOOST_SCOPE_EXIT_TPL( (&tval) (&t) (&tc) (&tv) (&tcv) (&i) ) {
            tval = 1;
            ++t;
            ++tv;
        } BOOST_SCOPE_EXIT_END

        BOOST_TEST(t == remember);
        BOOST_TEST(tval == remember);
    }

    BOOST_TEST(tval == 1);
    BOOST_TEST(t == remember + 2);
}

template<class Vector, int Value>
void tpl_vector(
      Vector vval
    , Vector & v
    , Vector const& vc
) {
    Vector const remember(vval);

    {
        BOOST_SCOPE_EXIT_TPL( (&vval) (&v) (&vc) ) {
            v.push_back(-Value);
            vval.push_back(Value);
        } BOOST_SCOPE_EXIT_END

        BOOST_TEST(v.size() == remember.size());
        BOOST_TEST(vval.size() == remember.size());
    }

    BOOST_TEST(v.size() == 1 + remember.size());
    BOOST_TEST(vval.size() == 1 + remember.size());
}

int main(void) {
    long l = 137;
    tpl_long(l, l, l, l, l);

    std::vector<int> v(10, 137);
    tpl_vector<std::vector<int>, 13>(v, v, v);

    return boost::report_errors();
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema