text:
#pragma once

#include "ArithmeticProgression.hpp"
#include "Misc.hpp"
#include "Sequences.hpp"
#include "VectorHelpers.hpp"
#include <boost/iterator/iterator_facade.hpp>

namespace discreture
{

////////////////////////////////////////////////////////////////////////////////////
/// \brief Class for iterating through all dyck (dyck) paths.
/// \param IntType must be a SIGNED integer type.
///
/// Dyck paths, also called Catalan Paths, are paths that go from \f$(0,0)\f$ to
/// \f$(0,2n)\f$, which never go below the \f$ y=0\f$ line, in which each step
/// is from \f$(x,y)\f$ to either \f$(x+1,y+1)\f$ or \f$(x+1,y-1)\f$ #Example
/// Usage:
///
///     dyck_paths X(3)
///     for (auto&& x : X)
///         cout << x << endl;
/// Prints out:
///     [ 1 1 1 -1 -1 -1 ]
///     [ 1 1 -1 1 -1 -1 ]
///     [ 1 -1 1 1 -1 -1 ]
///     [ 1 1 -1 -1 1 -1 ]
///     [ 1 -1 1 -1 1 -1 ]
///
/// # Example: Parenthesis
///
///     dyck_paths X(3)
///     for (auto&& x : X)
///         cout << dyck_paths::to_string(x, "()") << endl;
///
/// Prints out:
///     ((()))
///     (()())
///     ()(())
///     (())()
///     ()()()
///
/////////////////////////////////////////////////////////////////////////////////////
template <class IntType = int, class RAContainerInt = std::vector<IntType>>
class DyckPaths
{
public:
    static_assert(std::is_integral<IntType>::value,
                  "Template parameter IntType must be integral");
    static_assert(std::is_signed<IntType>::value,
                  "Template parameter IntType must be signed");
    using value_type = RAContainerInt;
    using dyck_path = value_type;
    using difference_type = std::ptrdiff_t;
    using size_type = difference_type;
    class iterator;
    using const_iterator = iterator;

    // **************** Begin static functions
    static void next_dyck_path(dyck_path& data)
    {
        size_t n_ = data.size()/2;

        if (n_ == 0)
            return;

        if (data[1] != -1)
        {
            size_t loc = 2;

            while (data[loc] != -1)
                ++loc;

            data[loc] = 1;
            data[loc - 1] = -1;

            return;
        }

        size_t verif = 0;
        size_t i = 1;

        while (i < n_ && verif == 0)
        {
            if (data[(2*i) + 1] == 1)
                verif = ((2*i) + 1);

            ++i;
        }

        //          for(nuint i=1; i<t; ++t)
        //          {
        //              if(data[(2*i)+1]==0)
        //                  verif=((2*i)+1);
        //          }

        if (verif == 0)
        {
            return;
        }

        size_t cont = 0;
        auto encontrar = verif + 1;

        for (size_t i = 0; i < verif; ++i)
        {
            if (data[i] == -1)
            {
                data[i] = 1;
                ++cont;
            }
        }

        while (data[encontrar] != -1)
            ++encontrar;

        data[encontrar] = 1;
        data[encontrar - 1] = -1;

        while (cont != 0)
        {
            data[encontrar - 1 - cont] = -1;
            --cont;
        }
    }

    static std::string to_string(const dyck_path& data,
                                 const std::string& delim = "()")
    {
        std::string toReturn;

        for (auto i : data)
        {
            auto j = 1 - (i + 1)/2;
            toReturn.push_back(delim[j]);
        }

        return toReturn;
    }

    // **************** End static functions

public:
    ////////////////////////////////////////////////////////////
    /// \brief Constructor
    ///
    /// \param n is an integer >= 0
    ///
    ////////////////////////////////////////////////////////////
    explicit DyckPaths(IntType n) : n_(n) {}

    ////////////////////////////////////////////////////////////
    /// \brief The total number of dyck_paths
    ///
    /// \return binomial(2n,n)/(n+1)
    ///
    ////////////////////////////////////////////////////////////
    size_type size() const { return catalan(n_); }

    IntType get_n() const { return n_; }

    ////////////////////////////////////////////////////////////
    /// \brief Forward iterator class.
    ////////////////////////////////////////////////////////////
    class iterator
        : public boost::iterator_facade<iterator, const dyck_path&, boost::forward_traversal_tag>
    {
    public:
        iterator() = default; // empty initializer
        explicit iterator(IntType n) : ID_(0), data_(2*n, 1)
        {
            for (size_t i = n; i < data_.size(); ++i)
                data_[i] = -1;
        }

        size_type ID() const { return ID_; }

        bool is_at_end(IntType n) const { return ID_ == catalan(n); }

        void reset(IntType n)
        {
            ID_ = 0;
            data_.resize(2*n);
            auto r = static_cast<size_t>(n);
            for (size_t i = 0; i < r; ++i)
                data_[i] = 1;

            for (size_t i = r; i < data_.size(); ++i)
                data_[i] = -1;
        }

        static const iterator make_invalid_with_id(size_type id)
        {
            iterator it;
            it.ID_ = id;
            return it;
        }

    private:
        void increment()
        {
            ++ID_;

            next_dyck_path(data_);
        }

        const dyck_path& dereference() const { return data_; }

        bool equal(const iterator& it) const { return it.ID() == ID(); }

    private:
        size_type ID_{0};
        dyck_path data_{};

        friend class boost::iterator_core_access;
    }; // end class iterator

    iterator begin() const { return iterator(n_); }

    const iterator end() const
    {
        return iterator::make_invalid_with_id(size());
    }

private:
    IntType n_;

}; // end class DyckPaths

using boost::container::static_vector;

using dyck_paths = DyckPaths<int>;
using dyck_paths_stack = DyckPaths<int, static_vector<int, 48>>;

} // namespace discreture

max_forks_repo_name: greati/logicantsy


text:
/**
 *
 *  \file
 *  \brief      Main entry point for the serial node.
 *  \author     Mike Purvis <mpurvis@clearpathrobotics.com>
 *  \copyright  Copyright (c) 2013, Clearpath Robotics, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Clearpath Robotics, Inc. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL CLEARPATH ROBOTICS, INC. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Please send comments, questions, or patches to code@clearpathrobotics.com
 *
 */

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

#include <ros/ros.h>

#include "rosserial_server/serial_session.h"

int main(int argc, char* argv[])
{
  // Initialize ROS.
  ros::init(argc, argv, "rosserial_server_serial_node");
  std::string port;
  ros::param::param<std::string>("~port", port, "/dev/ttyACM0");
  int baud;
  ros::param::param<int>("~baud", baud, 57600);

  // Run boost::asio io service in a background thread.
  boost::asio::io_service io_service;
  new rosserial_server::SerialSession(io_service, port, baud);
  boost::thread(boost::bind(&boost::asio::io_service::run, &io_service));

  ros::spin();
  return 0;
}

ext: cpp


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "crypto/crypto_store/key_type.hpp"

#include <unordered_set>

#include <boost/endian/arithmetic.hpp>

namespace kagome::crypto {

  bool isSupportedKeyType(KeyTypeId k) {
    static const std::unordered_set<KeyTypeId> supported_types = {
        KEY_TYPE_GRAN,
        KEY_TYPE_ACCO,
        KEY_TYPE_AUDI,
        KEY_TYPE_BABE,
        KEY_TYPE_IMON,
        KEY_TYPE_LP2P};

    return supported_types.count(k) > 0;
  }

  std::string decodeKeyTypeId(KeyTypeId param) {
    constexpr unsigned size = sizeof(KeyTypeId);
    constexpr unsigned bits = size * 8u;
    std::array<char, size> key_type{};

    boost::endian::endian_buffer<boost::endian::order::big, KeyTypeId, bits>
        buf(param);
    for (size_t i = 0; i < size; ++i) {
      // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
      key_type.at(i) = buf.data()[i];
    }

    return std::string(key_type.begin(), key_type.end());
  }
}  // namespace kagome::crypto

OUTCOME_CPP_DEFINE_CATEGORY(kagome::crypto, KeyTypeError, e) {
  using Error = kagome::crypto::KeyTypeError;
  switch (e) {
    case Error::UNSUPPORTED_KEY_TYPE:
      return "key type is not supported";
    case Error::UNSUPPORTED_KEY_TYPE_ID:
      return "key type id is not supported";
  }

  return "Unknown KeyTypeError";
}

max_stars_repo_name: igor-egorov/kagome

max_issues_repo_name: igor-egorov/kagome

max_forks_repo_name: igor-egorov/kagome


text:
/*
 * Distributed under the MIT License (See accompanying file /LICENSE)
 * Copyright (c) 2018 Kaze Organization
 * Authors: Michał Wiatr
 */

#ifndef KAZESL_SERVER
#define KAZESL_SERVER

#include <boost/beast.hpp>

#include <core/Stoppable.hpp>
#include <common/Logger.hpp>
#include <server/ServerInterface.hpp>

namespace kazesl
{

using namespace boost::asio;

class Server
    : public ServerInterface,
      Stoppable
{
  public:
    Server(io_service &io_service_, kazeCommon::journal j_);

    virtual ~Server();

    Endpoints
    endpoints(std::vector<unsigned int> const &v) override;

    void
    close() override;

  private:
    void onStart() override;

  private:
    kazeCommon::journal log_;
    io_service &io_service_;
    std::optional<io_service::work> work_;
};

std::unique_ptr<Server>
create_Server(boost::asio::io_service &io_service, kazeCommon::journal journal);
}
#endif

ext: hpp

max_stars_repo_name: wiatrM/kazesl

max_issues_repo_name: wiatrM/kazesl

max_forks_repo_name: wiatrM/kazesl


text:
/* Copyright (c) 2017, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 *
 * All rights reserved.
 *
 * The Astrobee platform is licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
#include <ff_common/init.h>
#include <ff_common/utils.h>

#include <gflags/gflags.h>

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

// ROS
#include <rosbag/bag.h>
#include <rosbag/view.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>

#include <string>
#include <vector>
#include <fstream>

// Merge bags
// Usage: merge_bags -output_bag output.bag input1.bag input2.bag ...

DEFINE_string(output_bag, "",
              "The output bag.");

// Read the list of topics in a bag while avoiding repetitions
void readTopicsInBag(std::string const& bag_file, std::vector<std::string> & topics) {
  topics.clear();

  rosbag::Bag bag(bag_file.c_str());
  rosbag::View view(bag);
  std::vector<const rosbag::ConnectionInfo *> connection_infos = view.getConnections();

  // Read first in a set to deal with any repetitions
  std::set<std::string> topics_set;
  BOOST_FOREACH(const rosbag::ConnectionInfo *info, connection_infos) {
    topics_set.insert(info->topic);
  }

  // Copy the unique names to a vector
  for (auto it = topics_set.begin(); it != topics_set.end() ; it++) {
    topics.push_back(*it);
  }
}

int main(int argc, char ** argv) {
  ff_common::InitFreeFlyerApplication(&argc, &argv);

  if (FLAGS_output_bag == "") {
    std::cout << "The output bag was not specified.\n";
    return 1;
  }

  // Make the directory where the output will go
  std::string out_dir = boost::filesystem::path(FLAGS_output_bag).parent_path().string();
  if (out_dir == "")
    out_dir = ".";
  if (!boost::filesystem::exists(out_dir)) {
    int status = mkdir(out_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
    if (status && errno != EEXIST) {
      std::cout << "Failed to create directory: " << out_dir << ".";
      return 1;
    }
  }

  // Open the output bag
  std::cout << "Opening the output bag file: " << FLAGS_output_bag << "\n";
  rosbag::Bag output_bag;
  output_bag.open(FLAGS_output_bag, rosbag::bagmode::Write);

  // Append the input bags
  for (int it = 1; it < argc; it++) {
    std::string input_bag_file = argv[it];

    std::cout << "Opening the input bag file: " << input_bag_file << "\n";

    // Get the topics from the input bag
    std::vector<std::string> topics;
    readTopicsInBag(input_bag_file, topics);

    rosbag::Bag input_bag;
    input_bag.open(input_bag_file, rosbag::bagmode::Read);

    rosbag::View view(input_bag, rosbag::TopicQuery(topics));
    for (rosbag::MessageInstance const m : view) {
      output_bag.write(m.getTopic(), m.getTime(), m);
    }

    input_bag.close();
  }

  output_bag.close();

  return 0;
}

ext: cc

max_stars_repo_name: jdekarske/astrobee

max_issues_repo_name: jdekarske/astrobee

max_forks_repo_name: jdekarske/astrobee


text:
//==================================================================================================
/*!
  @file

  @copyright 2015 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_SIMD_ALIGNED_LOAD_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_SIMD_ALIGNED_LOAD_HPP_INCLUDED

#include <boost/simd/function/scalar/aligned_load.hpp>
#include <boost/simd/arch/common/simd/function/aligned_load.hpp>

#if defined(BOOST_HW_SIMD_X86)

#if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_SSE_VERSION
#include <boost/simd/arch/x86/sse1/simd/function/aligned_load.hpp>
#endif

#if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_SSE2_VERSION
#include <boost/simd/arch/x86/sse2/simd/function/aligned_load.hpp>
#endif

#if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_AVX_VERSION
#include <boost/simd/arch/x86/avx/simd/function/aligned_load.hpp>
#endif

#if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_AVX2_VERSION
#include <boost/simd/arch/x86/avx2/simd/function/aligned_load.hpp>
#endif

#endif

#endif


text:
/*
Copyright 2016 BitTorrent Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#ifndef BITTORRENT_DHT_SESSION_HPP
#define BITTORRENT_DHT_SESSION_HPP

#include <thread>
#include <future>
#include <boost/asio/io_service.hpp>
#include <boost/asio/steady_timer.hpp>
#include <dht.h>
#include <ExternalIPCounter.h>
#include <libminiupnpc/igd_desc_parse.h>
#include "udp_socket.hpp"
#include "scout.hpp"

namespace scout
{

struct upnp_mapping
{
	upnp_mapping(char* ctrlURL, char st[MINIUPNPC_URL_MAXSIZE])
		: controlURL(ctrlURL)
	{
		memcpy(servicetype, st, sizeof(servicetype));
	}

	std::string controlURL;
	char servicetype[MINIUPNPC_URL_MAXSIZE];
};

class dht_session
{
	friend struct ip_change_observer_session;

public:
	enum run_state
	{
		INITIAL,
		RUNNING,
		QUITTING,
	};

	dht_session();
	~dht_session();

	// start the dht client
	// the client will start listening on a random port and bootstrap its routing table
	// if this function returns zero the session is ready to handle requests
	// otherwise an error occurred
	int start();

	// stop the client
	// this will terminate all network activity and any outstanding requests will be aborted
	void stop();

	// Note: See the corresponding functions in scout.hpp for more details on
	// each type of request.

	// synchronize a list of entries with the DHT
	// this will first update the given vector with any new or updated entries from the DHT
	// then store the updated list in the DHT
	void synchronize(secret_key_span shared_key, std::vector<entry> entries
		, entry_updated entry_cb, finalize_entries finalize_cb, sync_finished finished_cb);

	// store an immutable item in the DHT
	void put(list_token const& token, gsl::span<gsl::byte const> contents
		, put_finished finished_cb);

	// retrieve an immutable item from the DHT
	void get(hash_span address, item_received received_cb);

private:
	bool is_quitting() const { return m_state == QUITTING; }
	void resolve_bootstrap_servers();
	void update_mappings();
	void network_thread_fun(std::promise<int>& promise);
	void on_dht_timer(error_code const& ec);
	void on_natpmp_timer(error_code const& ec);
	void on_ip_changed(udp::endpoint const& new_ip);
	void incoming_packet(char* buf, size_t len, udp::endpoint const& ep);

	boost::asio::io_service m_ios;
	std::uint16_t m_dht_external_port;
	run_state m_state;
	ExternalIPCounter m_external_ip;
	std::shared_ptr<udp_socket> m_socket;
	std::thread m_thread;
	smart_ptr<IDht> m_dht;
	boost::asio::steady_timer m_dht_timer;
	// io service for handling various async tasks (such as nat-pmp):
	io_service m_ios_worker;
	// worker thread used by the worker io service:
	std::thread m_worker_thread;
	boost::asio::steady_timer m_natpmp_timer;
	std::vector<upnp_mapping> m_upnp_mappings;
	bool m_is_natpmp_mapped;
	std::vector<std::pair<std::string, int>> m_bootstrap_nodes;
	int m_dht_rate_limit;
};

} // namespace scout

#endif

max_stars_repo_name: bittorrent/scout

max_issues_repo_name: bittorrent/scout

max_forks_repo_name: bittorrent/scout


text:
//
//   Project Name:        KratosContactMechanicsApplication $
//   Created by:          $Author:              JMCarbonell $
//   Last modified by:    $Co-Author:                       $
//   Date:                $Date:                August 2016 $
//   Revision:            $Revision:                    0.0 $
//
//

#if !defined(KRATOS_BUILD_CONTACT_MODEL_PART_PROCESS_H_INCLUDED )
#define  KRATOS_BUILD_CONTACT_MODEL_PART_PROCESS_H_INCLUDED

// System includes
#include <string>
#include <iostream>

// External includes
#include <boost/timer.hpp>

// Project includes
#include "includes/model_part.h"
#include "custom_utilities/mesher_utilities.hpp"

///VARIABLES used:
//Data:
//StepData:
//Flags:    (checked)
//          (set)
//          (modified)
//          (reset)
// (set):=(set in this process)

namespace Kratos
{

  ///@name Kratos Globals
  ///@{

  ///@}
  ///@name Type Definitions
  ///@{

  ///@}
  ///@name  Enum's
  ///@{

  ///@}
  ///@name  Functions
  ///@{

  ///@}
  ///@name Kratos Classes
  ///@{

  /// Short class definition.
  /** Detail class definition.
   */
  class BuildContactModelPartProcess
    : public Process
  {
  public:
    ///@name Type Definitions
    ///@{

    /// Pointer definition of BuildContactModelPartProcess
    KRATOS_CLASS_POINTER_DEFINITION( BuildContactModelPartProcess );

    typedef ModelPart::ConditionType         ConditionType;
    typedef ModelPart::PropertiesType       PropertiesType;
    typedef ConditionType::GeometryType       GeometryType;

    ///@}
    ///@name Life Cycle
    ///@{

    /// Default constructor.
    BuildContactModelPartProcess(ModelPart& rModelPart,
				     MesherUtilities::MeshingParameters& rRemeshingParameters,
				     std::vector<std::string>& rContactModelParts,
				     int EchoLevel)
        : mrModelPart(rModelPart)
        ,mrRemesh(rRemeshingParameters)
        ,mrContactModelParts(rContactModelParts)
    {
      mEchoLevel = EchoLevel;
      mMasterConditionsInitialized = false;
    }

    /// Copy constructor.
    BuildContactModelPartProcess(BuildContactModelPartProcess const& rOther)
        :mrModelPart(rOther.mrModelPart)
        ,mrRemesh(rOther.mrRemesh)
        ,mrContactModelParts(rOther.mrContactModelParts)
        ,mEchoLevel(rOther.mEchoLevel)
        ,mMasterConditionsInitialized(rOther.mMasterConditionsInitialized)
    {
    }

    /// Destructor.
    virtual ~BuildContactModelPartProcess()
    {
    }

    ///@}
    ///@name Operators
    ///@{

    void operator()()
    {
      Execute();
    }

    ///@}
    ///@name Operations
    ///@{

    void Execute() override
    {
      KRATOS_TRY

      if( mEchoLevel > 0 )
	std::cout<<" [ CONSTRUCT CONTACT MODEL_PART: "<<std::endl;

      ModelPart& rModelPart = mrModelPart.GetSubModelPart(mrRemesh.SubModelPartName);

      //set CONTACT label
      rModelPart.Set(CONTACT);

      this->Execute(rModelPart);

      //this->Transfer(rModelPart);

      this->SetHoles();

      if( mEchoLevel > 0 )
	std::cout<<"   CONSTRUCT CONTACT MODEL_PART ]; "<<std::endl;

      KRATOS_CATCH(" ")
    }

    ///@}
    ///@name Access
    ///@{

    ///@}
    ///@name Inquiry
    ///@{

    ///@}
    ///@name Input and output
    ///@{

    /// Turn back information as a string.
    std::string Info() const override
    {
      return "BuildContactModelPartProcess";
    }

    /// Print information about this object.
    void PrintInfo(std::ostream& rOStream) const override
    {
      rOStream << "BuildContactModelPartProcess";
    }

    /// Print object's data.
    void PrintData(std::ostream& rOStream) const override
    {
    }

    ///@}
    ///@name Friends
    ///@{

    ///@}

  protected:
    ///@name Protected static Member Variables
    ///@{

    ///@}
    ///@name Protected member Variables
    ///@{

    ///@}
    ///@name Protected Operators
    ///@{

    ///@}
    ///@name Protected Operations
    ///@{

    ///@}
    ///@name Protected  Access
    ///@{

    ///@}
    ///@name Protected Inquiry
    ///@{

    ///@}
    ///@name Protected LifeCycle
    ///@{

    ///@}

  private:
    ///@name Static Member Variables
    ///@{

    ///@}
    ///@name Member Variables
    ///@{
    ModelPart& mrModelPart;

    MesherUtilities::MeshingParameters& mrRemesh;

    std::vector<std::string> mrContactModelParts;

    int mEchoLevel;

    bool mMasterConditionsInitialized;

    ///@}
    ///@name Private Operators
    ///@{

    //**************************************************************************
    //**************************************************************************
    void Execute(ModelPart& rModelPart)
    {

      KRATOS_TRY

      //check if the construction is needed
      unsigned int count_nodes = 0;
      unsigned int count_conditions = 0;

      for(std::vector<std::string>::const_iterator n_mp = mrContactModelParts.begin(); n_mp!=mrContactModelParts.end(); ++n_mp)
	{
          //std::cout<<" ModelParts "<<*n_mp<<std::endl;
 	  ModelPart& i_mp = mrModelPart.GetSubModelPart(*n_mp);

	  for(ModelPart::NodesContainerType::iterator i_node = i_mp.NodesBegin() ; i_node != i_mp.NodesEnd() ; i_node++)
	    {
	      if( i_node->Is(BOUNDARY) )
		++count_nodes;
	    }

	  for(ModelPart::ConditionsContainerType::iterator i_cond = i_mp.ConditionsBegin() ; i_cond != i_mp.ConditionsEnd() ; i_cond++)
	    {
	      if( i_cond->Is(BOUNDARY) && i_cond->IsNot(CONTACT) )
		++count_conditions;
	    }
	}

      bool build_is_needed = false;
      if( count_nodes != rModelPart.Nodes().size() || count_conditions != rModelPart.Conditions().size() )
	build_is_needed = true;

      const ProcessInfo& rProcessInfo = rModelPart.GetProcessInfo();
      if( rProcessInfo[MESHING_STEP_TIME] == rProcessInfo[TIME] )
	build_is_needed = true;

      if( build_is_needed ){

	//*******************************************************************
	//set boundary conditions and nodes:

	rModelPart.Nodes().clear();
	rModelPart.Elements().clear();

	ModelPart::ConditionsContainerType PreservedConditions;
	PreservedConditions.swap(rModelPart.Conditions());

	for(std::vector<std::string>::const_iterator n_mp = mrContactModelParts.begin(); n_mp!=mrContactModelParts.end(); ++n_mp)
	  {
            //std::cout<<" ModelParts "<<*n_mp<<std::endl;
	    ModelPart&  i_mp = mrModelPart.GetSubModelPart(*n_mp);

	    for(ModelPart::NodesContainerType::iterator i_node = i_mp.NodesBegin() ; i_node != i_mp.NodesEnd() ; i_node++)
	      {
		if( i_node->Is(BOUNDARY) )
		  rModelPart.AddNode(*(i_node.base()));
	      }

	    for(ModelPart::ConditionsContainerType::iterator i_cond = i_mp.ConditionsBegin() ; i_cond != i_mp.ConditionsEnd() ; i_cond++)
	      {
		if( i_cond->Is(BOUNDARY) && i_cond->IsNot(CONTACT) )
		  rModelPart.AddCondition(*(i_cond.base()));
	      }
	  }

	//add previous contact conditions
	for(ModelPart::ConditionsContainerType::iterator i_cond = PreservedConditions.begin(); i_cond!= PreservedConditions.end(); i_cond++)
	  {
	    if(i_cond->Is(CONTACT)){
	      rModelPart.Conditions().push_back(*(i_cond.base()));
	    }
	  }

	//Sort
	//rModelPart.Nodes().Sort();
	//rModelPart.Conditions().Sort();

	//Unique
	//rModelPart.Nodes().Unique();
	//rModelPart.Conditions().Unique();

      }

      if( mEchoLevel > 0 )
	std::cout<<"   CONTACT MODEL_PART: (NODES:"<<rModelPart.NumberOfNodes()<<" CONDITIONS:"<<rModelPart.NumberOfConditions()<<") ]; "<<std::endl;

      KRATOS_CATCH(" ")

    }

    //**************************************************************************
    //**************************************************************************
    void Transfer(ModelPart& rModelPart)
    {

      KRATOS_TRY

      //*******************************************************************
      //set transfer parameters
      MeshDataTransferUtilities DataTransferUtilities;

      MeshDataTransferUtilities::TransferParameters::Pointer rParameters = mrRemesh.GetTransferParameters();

      //be careful: it must be done once only after the step solution:
      if(!mMasterConditionsInitialized){
	rParameters->Options.Set(MeshDataTransferUtilities::INITIALIZE_MASTER_CONDITION, true);
	DataTransferUtilities.TransferBoundaryData(*rParameters, rModelPart);
	mMasterConditionsInitialized = true;
      }
      else{
	rParameters->Options.Set(MeshDataTransferUtilities::MASTER_ELEMENT_TO_MASTER_CONDITION, true);
	DataTransferUtilities.TransferBoundaryData(*rParameters, mrModelPart);
      }

      KRATOS_CATCH( "" )
    }

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

    void SetHoles()
    {

      KRATOS_TRY

      //*******************************************************************
      //set holes (inside point of the contact domains):
      std::vector<BoundedVector<double, 3> > Holes;
      BoundedVector<double, 3> Point;

      for(std::vector<std::string>::const_iterator n_mp = mrContactModelParts.begin(); n_mp!=mrContactModelParts.end(); ++n_mp)
	{
	  //std::cout<<" ModelParts "<<*n_mp<<std::endl;
	  ModelPart&  i_mp = mrModelPart.GetSubModelPart(*n_mp);

	  //Get inside point of the subdomains
	  unsigned int dimension = i_mp.GetProcessInfo()[SPACE_DIMENSION];
	  if(i_mp.NumberOfConditions()){
	    ModelPart::ConditionsContainerType::iterator element_begin = i_mp.ConditionsBegin();
	    dimension = element_begin->GetGeometry().WorkingSpaceDimension();
	  }

	  bool hole_found = false;
	  for(ModelPart::NodesContainerType::iterator i_node = i_mp.NodesBegin() ; i_node != i_mp.NodesEnd() ; i_node++)
	    {
	      if( i_node->IsNot(BOUNDARY) ){
		Point[0] = i_node->X();
		Point[1] = i_node->Y();

		if(dimension>2)
		  Point[2] = i_node->Z();

		//std::cout<<" SetPoint "<<Point<<std::endl;
		Holes.push_back(Point);
		hole_found = true;
		break;
	      }
	    }

	  if( !hole_found ){
	    for(ModelPart::NodesContainerType::iterator i_node = i_mp.NodesBegin() ; i_node != i_mp.NodesEnd() ; i_node++)
	    {
	      if( i_node->Is(BOUNDARY) ){

		array_1d<double, 3>& Normal = i_node->FastGetSolutionStepValue(NORMAL);
		double Nodal_H = i_node->FastGetSolutionStepValue(NODAL_H);
		double tolerance = 0.5 * Nodal_H;

		//std::cout<<" Normal "<<Normal<<" Nodal_h "<<Nodal_H<<std::endl;

		Point[0] = i_node->X() - Normal[0] * tolerance;
		Point[1] = i_node->Y() - Normal[1] * tolerance;
		if(dimension>2)
		  Point[2] = i_node->Z() - Normal[2] * tolerance;

		Holes.push_back(Point);
		hole_found = true;
		break;
	      }
	    }
	  }
	}

      mrRemesh.SetHoles(Holes);

      KRATOS_CATCH(" ")

    }

    ///@}
    ///@name Private Operations
    ///@{

    ///@}
    ///@name Private  Access
    ///@{

    ///@}
    ///@name Private Inquiry
    ///@{

    ///@}
    ///@name Un accessible methods
    ///@{

    /// Assignment operator.
    BuildContactModelPartProcess& operator=(BuildContactModelPartProcess const& rOther);

    /// Copy constructor.
    //BuildContactModelPartProcess(BuildContactModelPartProcess const& rOther);

    ///@}

  }; // Class BuildContactModelPartProcess

  ///@}

  ///@name Type Definitions
  ///@{

  ///@}
  ///@name Input and output
  ///@{

  /// input stream function
  inline std::istream& operator >> (std::istream& rIStream,
				    BuildContactModelPartProcess& rThis);

  /// output stream function
  inline std::ostream& operator << (std::ostream& rOStream,
				    const BuildContactModelPartProcess& rThis)
  {
    rThis.PrintInfo(rOStream);
    rOStream << std::endl;
    rThis.PrintData(rOStream);

    return rOStream;
  }
  ///@}

}  // namespace Kratos.

#endif // KRATOS_BUILD_CONTACT_MODEL_PART_PROCESS_H_INCLUDED  defined

max_stars_repo_name: lkusch/Kratos

max_issues_repo_name: lkusch/Kratos

max_forks_repo_name: lkusch/Kratos


text:
/* $Id: common.hpp 48153 2011-01-01 15:57:50Z mordante $ */

/**
* @file
* @brief Main definitions for project ana.
*
* ana: Asynchronous Network API.
* Copyright (C) 2010 - 2011 Guillermo Biset.
*
* This file is part of the ana project.
*
* System:         ana
* Language:       C++
*
* Author:         Guillermo Biset
* E-Mail:         billybiset AT gmail DOT com
*
* ana is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* ana is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ana.  If not, see <http://www.gnu.org/licenses/>.
*
*/

#ifndef ANA_COMMON_HPP
#define ANA_COMMON_HPP

#include <boost/asio/detail/socket_ops.hpp>
#include <boost/cstdint.hpp>
#include <boost/system/error_code.hpp>

namespace ana
{
    /** @name Type and constant definitions
     *
     * Definitions of main types and relevant constants.
     */
    //@{
        /** Standard unsigned int, with fixed size to 32 bits.  */
        typedef boost::uint32_t ana_uint32 ;

        /** Standard int, with fixed size to 32 bits.           */
        typedef boost::int32_t  ana_int32  ;

        /** Standard unsigned int, with fixed size to 16 bits.  */
        typedef boost::uint16_t ana_uint16 ;

        /** Standard int, with fixed size to 16 bits.           */
        typedef boost::int16_t  ana_int16  ;

        /** Message size type.                                  */
        typedef ana_uint32  message_size   ;

        /** IDs of connected components, unique, non zero.      */
        typedef size_t      net_id         ;

        /** IDs of network operations, unique, zero = no-op.    */
        typedef size_t      operation_id   ;

        /** Port type, a std::string (instead of a short.)      */
        typedef std::string port           ;

        /** Address type, a string. Either IP of hostname.      */
        typedef std::string address        ;

        /** Send operation type, true to copy the buffer.       */
        typedef bool        send_type      ;

        /** Standard error code, can evaluate to bool.          */
        typedef boost::system::error_code error_code ;

        /** The default timeout error. */
        const ana::error_code operation_aborted =
                    boost::asio::error::make_error_code( boost::asio::error::operation_aborted );

        /** The default timeout error. */
        const ana::error_code timeout_error =
                    boost::asio::error::make_error_code( boost::asio::error::timed_out );

        /** A generic error. Used to describe an undefined error. */
        const ana::error_code generic_error =
                    boost::asio::error::make_error_code( boost::asio::error::fault );

        /** A network operation that didn't do anything.        */
        const operation_id no_operation = 0;

        /** An invalid net_id. Useful for error checking.       */
        const operation_id invalid_net_id = 0;

        /** Don't copy the buffer. */
        const send_type ZERO_COPY   = false;

        /** Copy the buffer.       */
        const send_type COPY_BUFFER = true ;

        /** Length of message header, 4 bytes.    */
        const message_size HEADER_LENGTH = sizeof(ana_uint32);

        /** Initial length of raw message buffer. */
        const message_size INITIAL_RAW_MODE_BUFFER_SIZE = 256 ;
    //@}
}

#endif

max_stars_repo_name: blackberry/Wesnoth

max_issues_repo_name: blackberry/Wesnoth

max_forks_repo_name: blackberry/Wesnoth


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

#include <iostream>
#include <sstream>
#include <string>

#include <SDL2/SDL.h>
#include <boost/scope_exit.hpp>

std::string GetRenderFlagsName(Uint32 flags);

int main(int argc, char* argv[]) {
  if (-1 == SDL_Init(SDL_INIT_VIDEO)) {
    std::cout << "Could not initialize SDL: " << SDL_GetError() << '\n';
    return EXIT_FAILURE;
  }
  BOOST_SCOPE_EXIT_ALL(&) { SDL_Quit(); };

  int num = SDL_GetNumRenderDrivers();
  std::cout << "Number of render drivers: " << num << '\n';

  for (int i = 0; i < num; ++i) {
    SDL_RendererInfo info = {};
    if (0 == SDL_GetRenderDriverInfo(i, &info)) {
      std::cout << "\n[" << i << "] " << info.name
                << "\n\tflags: " << GetRenderFlagsName(info.flags)
                << "\n\tnum_texture_formats: " << info.num_texture_formats;
      for (Uint32 j = 0; j < info.num_texture_formats; ++j) {
        std::cout << "\n\t\t(" << j << ") "
                  << SDL_GetPixelFormatName(info.texture_formats[j]);
      }

      std::cout << "\n\tmax_texture_width: " << info.max_texture_width
                << "\n\tmax_texture_height: " << info.max_texture_height;
    } else {
      std::cout << "\nSDL_GetRenderDriverInfo(" << i
                << ") failed: " << SDL_GetError();
    }
  }

  return EXIT_SUCCESS;
}

void PadOrString(std::string& name, const std::string& pad) {
  if (!name.empty()) {
    name.append(" | ");
  }
  name.append(pad);
}

std::string GetRenderFlagsName(Uint32 flags) {
  std::string name;

#define PAD_OR_STRING(x)   \
  if (flags & x) {         \
    flags &= ~x;           \
    PadOrString(name, #x); \
  }

  PAD_OR_STRING(SDL_RENDERER_SOFTWARE);
  PAD_OR_STRING(SDL_RENDERER_ACCELERATED);
  PAD_OR_STRING(SDL_RENDERER_PRESENTVSYNC);
  PAD_OR_STRING(SDL_RENDERER_TARGETTEXTURE);

  if (flags) {
    std::stringstream ss;
    ss << flags;
    PadOrString(name, ss.str());
  }
  return name;
}


text:
#include <appbase/application.hpp>

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

#include <iostream>
#include <fstream>

#include <boost/dll/import.hpp>
#include <boost/exception/diagnostic_information.hpp>

namespace appbase {

namespace bpo = boost::program_options;
using bpo::options_description;
using bpo::variables_map;
using std::cout;

class application_impl {
   public:
      application_impl():_app_options("Application Options"){
      }
      const variables_map*    _options = nullptr;
      options_description     _app_options;
      options_description     _cfg_options;
      variables_map           _args;

      bfs::path               _data_dir;
};

application::application()
:my(new application_impl()){
   io_serv = std::make_shared<boost::asio::io_service>();
}

application::~application() { }

void application::startup() {
   for (const auto& plugin : initialized_plugins)
      plugin->startup();
}

application& application::instance( bool reset ) {
   static application* _app = new application();
   if( reset )
   {
      delete _app;
      _app = new application();
   }
   return *_app;
}
application& app() { return application::instance(); }
application& reset() { return application::instance( true ); }

void application::set_program_options()
{
   options_description app_cfg_opts( "Application Config Options" );
   options_description app_cli_opts( "Application Command Line Options" );
   app_cfg_opts.add_options()
         ("plugin", bpo::value< vector<string> >()->composing(), "Plugin(s) to enable, may be specified multiple times");
   app_cfg_opts.add_options()
         ("backtrace", bpo::value< string >()->default_value( "yes" ), "Whether to print backtrace on SIGSEGV" );
   app_cfg_opts.add_options()
         ("log-level", bpo::value< string >()->default_value( "info" ), "Log level. Possible values: debug, info, notice, warning, error, critical, alert, emergency. For monitoring to work, min. level is notice !" );

   app_cfg_opts.add_options()
         ("external-plugins-dir", bpo::value<bfs::path>()->default_value( "external-plugins" ), "Directory containing external/runtime-loadable plugins binaries (absolute path or relative to the program option data-dir/)");
   app_cfg_opts.add_options()
         ("external-plugin", bpo::value< vector<string> >()->composing(), "External plugin(s) to enable, may be specified multiple times");

   app_cli_opts.add_options()
         ("help,h", "Print this help message and exit.")
         ("version,v", "Print version information.")
         ("data-dir,d", bpo::value<bfs::path>()->default_value( "sophia_app_data" ), "Directory containing configuration files, blockchain data and external plugins")
         ("config,c", bpo::value<bfs::path>()->default_value( "config.ini" ), "Main configuration file path (absolute path or relative to the data-dir/configs/)");

   my->_cfg_options.add(app_cfg_opts);
   my->_app_options.add(app_cfg_opts);
   my->_app_options.add(app_cli_opts);

   for(auto& plug : plugins) {
      const plugin_program_options& plugin_options = get_plugin_program_options(plug.second);

      const options_description& plugin_cfg_options = plugin_options.get_cfg_options();
      if (plugin_cfg_options.options().size()) {
         my->_app_options.add(plugin_cfg_options);
         my->_cfg_options.add(plugin_cfg_options);
      }

      const options_description& plugin_cli_options = plugin_options.get_cli_options();
      if (plugin_cli_options.options().size()) {
         my->_app_options.add(plugin_cli_options);
      }
   }
}

plugin_program_options application::get_plugin_program_options(const std::shared_ptr< abstract_plugin >& plugin) {
   options_description plugin_cli_opts("Command Line Options for " + plugin->get_name());
   options_description plugin_cfg_opts("Config Options for " + plugin->get_name());
   plugin->set_program_options(plugin_cli_opts, plugin_cfg_opts);

   return plugin_program_options(plugin_cli_opts, plugin_cfg_opts);
}

bool application::load_external_plugins() {
   // plugins-dir par (even if it is default) must be always present
   assert(my->_args.count( "external-plugins-dir" ));

   boost::program_options::variable_value cfg_plugins_dir = my->_args["external-plugins-dir"];
   bfs::path plugins_dir = cfg_plugins_dir.as<bfs::path>();
   if (plugins_dir.is_relative() == true) {
      plugins_dir = my->_data_dir / plugins_dir;

      if (bfs::exists(plugins_dir) == false) {
         bfs::create_directory(plugins_dir);
      }
   }

   if(my->_args.count("external-plugin") > 0)
   {
      auto plugins = my->_args.at("external-plugin").as<std::vector<std::string>>();
      for(auto& arg : plugins)
      {
         vector<string> plugins_names;
         boost::split(plugins_names, arg, boost::is_any_of(" \t,"));

         for(const std::string& plugin_name : plugins_names) {
            bfs::path plugin_binary_path = plugins_dir / std::string("lib" + plugin_name + "_plugin.so");
            if (bfs::exists(plugin_binary_path) == false) {
               std::cerr << "Missing binary: " << plugin_binary_path << " for plugin: \"" << plugin_name << "\"" << std::endl;
               return false;
            }

            std::shared_ptr<abstract_plugin> loaded_plugin;
            try {
               auto plugin_creator = boost::dll::import<std::shared_ptr<abstract_plugin>()>(plugin_binary_path, "get_plugin", boost::dll::load_mode::append_decorations);
               loaded_plugin = plugin_creator();
            }
            catch ( const boost::exception& e )
            {
               std::cerr << "Failed to load plugin. Error: " << boost::diagnostic_information(e) << std::endl;
               return false;
            }

            // Registers loaded plugin for application
            register_external_plugin(loaded_plugin);

            // Loads plugins config parameters
            load_external_plugin_config(loaded_plugin, plugin_name);

            // Initializes plugin
            loaded_plugin->initialize(my->_args);
         }
      }
   }

   return true;
}

void application::register_external_plugin(const std::shared_ptr<abstract_plugin>& plugin) {
   plugins[plugin->get_name()] = plugin;
   plugin->register_dependencies();
}

void application::load_external_plugin_config(const std::shared_ptr<abstract_plugin>& plugin, const std::string& cfg_plugin_name) {
   const plugin_program_options& plugin_options = get_plugin_program_options(plugin);

   // Writes config if it does not already exists
   bfs::path config_file_path = write_default_config(plugin_options.get_cfg_options(),  bfs::path(cfg_plugin_name + "_plugin_config.ini"));

   // Copies parameters from config_file into my->_args
   bpo::store(bpo::parse_config_file< char >( config_file_path.make_preferred().string().c_str(),
                                              plugin_options.get_cfg_options(), true ), my->_args );
}

// TODO: delete after HF2
/**
 * @brief Fix which renames default data directory and also moves config into subdirectory configs, so users do not need to do it themselves
 *        Applies fixes only when users did not specify some custom paths to data-dir and config file
 *
 * @param actual_data_dir
 * @param cfg_data_dir
 * @param cfg_config
 */
void fix_deprecated_data_folder_structure(const bfs::path& actual_data_dir,
                                          const boost::program_options::variable_value& cfg_data_dir,
                                          const boost::program_options::variable_value& cfg_config) {
   // If data_dir has default(new) name and there is existing directory with old name -> rename it
   if (cfg_data_dir.defaulted() == true) {
      bfs::path deprecated_default_data_dir = bfs::current_path() / "witness_node_data_dir";
      if (bfs::exists(deprecated_default_data_dir) == true) {
         bfs::rename(deprecated_default_data_dir, actual_data_dir);
      }
   }

   // If config with default name exists and is not in subdirectory configs -> move it there
   if (cfg_config.defaulted() == true) {
      bfs::path deprecated_default_config_path = actual_data_dir / "config.ini";
      if (bfs::exists(deprecated_default_config_path) == true) {
         if (bfs::exists(actual_data_dir) == false) {
            bfs::create_directory(actual_data_dir);
         }

         bfs::path configs_dir = actual_data_dir / "configs/";
         if (bfs::exists(configs_dir) == false) {
            bfs::create_directory(configs_dir);
         }

         bfs::rename(deprecated_default_config_path, configs_dir / cfg_config.as<bfs::path>());
      }
   }
}

bool application::load_config( int argc, char** argv ) {
   try
   {
      set_program_options();
      bpo::store( bpo::parse_command_line( argc, argv, my->_app_options ), my->_args );

      if( my->_args.count( "help" ) ) {
         cout << my->_app_options << "\n";
         return false;
      }

      if( my->_args.count( "version" ) )
      {
         cout << version_info << "\n";
         return false;
      }

      // data-dir par (even if it is default) must be always present
      assert(my->_args.count( "data-dir" ));

      my->_data_dir = my->_args["data-dir"].as<bfs::path>();
      if( my->_data_dir.is_relative() )
         my->_data_dir = bfs::current_path() / my->_data_dir;

      // config par (even if it is default) must be always present
      assert(my->_args.count( "config" ));

      // TODO: delete after HF2
      // Fix which renames default data directory and also moves config into subdirectory configs, so users do not need to do it themselves
      fix_deprecated_data_folder_structure(my->_data_dir, my->_args["data-dir"], my->_args["config"]);

      // Writes config if it does not already exists
      bfs::path config_file_path = write_default_config(my->_cfg_options, my->_args["config"].as<bfs::path>());

      // Copies parameters from config_file into my->_args
      bpo::store(bpo::parse_config_file< char >( config_file_path.make_preferred().string().c_str(),
                                                 my->_cfg_options, true ), my->_args );

      return true;
   }
   catch (const boost::program_options::error& e)
   {
      std::cerr << "Error parsing command line: " << e.what() << "\n";
      return false;
   }
}

bool application::initialize_impl(int argc, char** argv, vector<abstract_plugin*> autostart_plugins)
{
   try
   {
      if(my->_args.count("plugin") > 0)
      {
         auto plugins = my->_args.at("plugin").as<std::vector<std::string>>();
         for(auto& arg : plugins)
         {
            vector<string> names;
            boost::split(names, arg, boost::is_any_of(" \t,"));
            for(const std::string& name : names) {
               get_plugin(name).initialize(my->_args);
            }
         }
      }

      // Loads external plugins specified in config
      if (load_external_plugins() == false) {
         return false;
      }

      for (const auto& plugin : autostart_plugins) {
         if (plugin != nullptr && plugin->get_state() == abstract_plugin::registered)
            plugin->initialize(my->_args);
      }

      bpo::notify(my->_args);

      return true;
   }
   catch (const boost::program_options::error& e)
   {
      std::cerr << "Error parsing command line: " << e.what() << "\n";
      return false;
   }
}

void application::shutdown() {
   for(auto ritr = running_plugins.rbegin();
       ritr != running_plugins.rend(); ++ritr) {
      (*ritr)->shutdown();
   }
   for(auto ritr = running_plugins.rbegin();
       ritr != running_plugins.rend(); ++ritr) {
      plugins.erase((*ritr)->get_name());
   }
   running_plugins.clear();
   initialized_plugins.clear();
   plugins.clear();
}

void application::quit() {
   io_serv->stop();
}

void application::exec() {
   std::shared_ptr<boost::asio::signal_set> sigint_set(new boost::asio::signal_set(*io_serv, SIGINT));
   sigint_set->async_wait([sigint_set,this](const boost::system::error_code& err, int num) {
     quit();
     sigint_set->cancel();
   });

   std::shared_ptr<boost::asio::signal_set> sigterm_set(new boost::asio::signal_set(*io_serv, SIGTERM));
   sigterm_set->async_wait([sigterm_set,this](const boost::system::error_code& err, int num) {
     quit();
     sigterm_set->cancel();
   });

   io_serv->run();

   shutdown(); /// perform synchronous shutdown
}

bfs::path application::write_default_config( const options_description& options_desc, const bfs::path& cfg_file ) {
   bfs::path config_file_name = my->_data_dir / "configs" / cfg_file;
   if( cfg_file.is_absolute() == true ) {
      config_file_name = cfg_file;
   }

   if(bfs::exists(config_file_name) == true) {
      return config_file_name;
   }

   if(bfs::exists(config_file_name.parent_path()) == false) {
      bfs::create_directories(config_file_name.parent_path());
   }

   std::ofstream out_cfg( bfs::path(config_file_name).make_preferred().string());
   for(const boost::shared_ptr<bpo::option_description> od : options_desc.options())
   {
      if(!od->description().empty())
         out_cfg << "# " << od->description() << "\n";
      boost::any store;
      if(!od->semantic()->apply_default(store))
         out_cfg << "# " << od->long_name() << " = \n";
      else {
         auto example = od->format_parameter();
         if(example.empty())
            // This is a boolean switch
            out_cfg << od->long_name() << " = " << "false\n";
         else {
            // The string is formatted "arg (=<interesting part>)"
            example.erase(0, 6);
            example.erase(example.length()-1);
            out_cfg << od->long_name() << " = " << example << "\n";
         }
      }
      out_cfg << "\n";
   }
   out_cfg.close();

   return config_file_name;
}

abstract_plugin* application::find_plugin( const string& name )const
{
   auto itr = plugins.find( name );

   if( itr == plugins.end() )
   {
      return nullptr;
   }

   return itr->second.get();
}

abstract_plugin& application::get_plugin(const string& name)const {
   auto ptr = find_plugin(name);
   if(!ptr)
      BOOST_THROW_EXCEPTION(std::runtime_error("unable to find plugin: " + name));
   return *ptr;
}

bfs::path application::data_dir()const
{
   return my->_data_dir;
}

void application::add_program_options( const options_description& cli, const options_description& cfg )
{
   my->_app_options.add( cli );
   my->_app_options.add( cfg );
   my->_cfg_options.add( cfg );
}

const variables_map& application::get_args() const
{
   return my->_args;
}

} /// namespace appbase

max_stars_repo_name: SophiaTX/SophiaTx-Blockchain

max_issues_repo_name: SophiaTX/SophiaTx-Blockchain

max_forks_repo_name: SophiaTX/SophiaTx-Blockchain