text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

/*! \file orea/app/oreapp.hpp
  \brief Open Risk Engine App
  \ingroup app
 */

#pragma once

#include <boost/make_shared.hpp>
#include <iostream>
#include <orea/aggregation/collateralaccount.hpp>
#include <orea/aggregation/collatexposurehelper.hpp>
#include <orea/aggregation/postprocess.hpp>
#include <orea/app/parameters.hpp>
#include <orea/app/reportwriter.hpp>
#include <orea/app/sensitivityrunner.hpp>
#include <orea/engine/parametricvar.hpp>
#include <orea/scenario/scenariogenerator.hpp>
#include <orea/scenario/scenariogeneratorbuilder.hpp>
#include <orea/scenario/scenariosimmarket.hpp>
#include <orea/scenario/scenariosimmarketparameters.hpp>
#include <ored/ored.hpp>
#include <ored/portfolio/referencedata.hpp>
#include <ored/portfolio/tradefactory.hpp>

namespace ore {
namespace analytics {
using namespace ore::data;

class SensitivityScenarioData;
class SensitivityAnalysis;

//! Orchestrates the processes covered by ORE, data loading, analytics and reporting
/*! \ingroup app
 */
class OREApp {
public:
    //! Constructor
    OREApp(boost::shared_ptr<Parameters> params, std::ostream& out = std::cout);
    //! Destructor
    virtual ~OREApp();
    //! generates XVA reports for a given portfolio and market
    virtual int run();

    //! Load curve configurations from xml file, build t0 market using market data provided.
    //! If any of the passed vectors are empty fall back on OREApp::buildMarket() and use market/fixing data files
    void buildMarket(const std::string& todaysMarketXML = "", const std::string& curveConfigXML = "",
                     const std::string& conventionsXML = "",
                     const std::vector<std::string>& marketData = std::vector<std::string>(),
                     const std::vector<std::string>& fixingData = std::vector<std::string>());

    //! Get the t0 market
    // TODO: This should return a market, not market impl
    boost::shared_ptr<ore::data::MarketImpl> getMarket() const;

    //! build engine factory for a given market from an XML String
    boost::shared_ptr<ore::data::EngineFactory>
    buildEngineFactoryFromXMLString(const boost::shared_ptr<ore::data::Market>& market,
                                    const std::string& pricingEngineXML);

protected:
    //! read setup from params_
    virtual void readSetup();
    //! set up logging
    void setupLog();
    //! remove logs
    void closeLog();
    //! load market conventions
    void getConventions();
    //! load market parameters
    void getMarketParameters();
    //! load reference data
    void getReferenceData();
    //! build engine factory for a given market
    virtual boost::shared_ptr<EngineFactory> buildEngineFactory(const boost::shared_ptr<Market>& market,
                                                                const string& groupName = "setup") const;
    //! build trade factory
    boost::shared_ptr<TradeFactory> buildTradeFactory() const;
    //! build portfolio for a given market
    boost::shared_ptr<Portfolio> buildPortfolio(const boost::shared_ptr<EngineFactory>& factory);
    //! load portfolio from file(s)
    boost::shared_ptr<Portfolio> loadPortfolio();

    //! generate NPV cube
    virtual void generateNPVCube();
    //! get an instance of an aggregationScenarioData class
    virtual void initAggregationScenarioData();
    //! get an instance of a cube class
    virtual void initCube(boost::shared_ptr<NPVCube>& cube, const std::vector<std::string>& ids);
    //! build an NPV cube
    virtual void buildNPVCube();
    //! initialise NPV cube generation
    void initialiseNPVCubeGeneration(boost::shared_ptr<Portfolio> portfolio);
    //! load simMarketData
    boost::shared_ptr<ScenarioSimMarketParameters> getSimMarketData();
    //! load scenarioGeneratorData
    boost::shared_ptr<ScenarioGeneratorData> getScenarioGeneratorData();
    //! build CAM
    boost::shared_ptr<QuantExt::CrossAssetModel> buildCam(boost::shared_ptr<Market> market,
                                                          const bool continueOnCalibrationError);
    //! build scenarioGenerator
    virtual boost::shared_ptr<ScenarioGenerator>
    buildScenarioGenerator(boost::shared_ptr<Market> market,
                           boost::shared_ptr<ScenarioSimMarketParameters> simMarketData,
                           boost::shared_ptr<ScenarioGeneratorData> sgd, const bool continueOnCalibrationError);

    //! load in scenarioData
    virtual void loadScenarioData();
    //! load in cube
    virtual void loadCube();
    //! run postProcessor to generate reports from cube
    void runPostProcessor();

    //! run stress tests and write out report
    virtual void runStressTest();
    //! run parametric var and write out report
    void runParametricVar();

    //! write out initial (pre-cube) reports
    void writeInitialReports();
    //! write out XVA reports
    void writeXVAReports();
    //! write out DIM reports
    void writeDIMReport();
    //! write out cube
    void writeCube(boost::shared_ptr<NPVCube> cube);
    //! write out scenarioData
    void writeScenarioData();
    //! write out base scenario
    void writeBaseScenario();
    //! load in nettingSet data
    boost::shared_ptr<NettingSetManager> initNettingSetManager();

    //! Get report writer
    /*! This calls the private method getReportWriterImpl() which returns the
        actual ReportWriter implementation. The private method is virtual and
        can be overridden in derived classes to provide a dervied ReportWriter
        instance. This method is not virtual and can be hidden in derived
        classes by a method with the same name. This method can then return a
        shared pointer to the derived ReportWriter class.

        For example, we can have the following in a derived class:
        \code{.cpp}
        class MyApp : public OREApp {
            // stuff
        protected:
            boost::shared_ptr<MyReportWriter> getReportWriter() {
                return boost::shared_ptr<MyReportWriter>(getReportWriterImpl());
            }
        private:
            virtual MyReportWriter* getReportWriterImpl() const {
                return new MyReportWriter();
            }
        };
        \endcode
        where we have our own special report writer class MyReportWriter that
        derives from ReportWriter or any class in its hierarchy.
    */
    boost::shared_ptr<ReportWriter> getReportWriter() const;
    //! Get sensitivity runner
    virtual boost::shared_ptr<SensitivityRunner> getSensitivityRunner();
    //! Add extra engine builders
    virtual std::vector<boost::shared_ptr<EngineBuilder>> getExtraEngineBuilders() const { return {}; };
    //! Add extra leg builders
    virtual std::vector<boost::shared_ptr<LegBuilder>> getExtraLegBuilders() const { return {}; };
    //! Add extra trade builders
    virtual std::map<std::string, boost::shared_ptr<AbstractTradeBuilder>>
    getExtraTradeBuilders(const boost::shared_ptr<TradeFactory>& = {}) const {
        return {};
    };
    //! Get fixing manager
    virtual boost::shared_ptr<FixingManager> getFixingManager() { return boost::make_shared<FixingManager>(asof_); }
    //! Get parametric var calculator
    virtual boost::shared_ptr<ParametricVarCalculator>
    buildParametricVarCalculator(const std::map<std::string, std::set<std::string>>& tradePortfolio,
                                 const std::string& portfolioFilter,
                                 const boost::shared_ptr<SensitivityStream>& sensitivities,
                                 const std::map<std::pair<RiskFactorKey, RiskFactorKey>, Real> covariance,
                                 const std::vector<Real>& p, const std::string& method, const Size mcSamples,
                                 const Size mcSeed, const bool breakdown, const bool salvageCovarianceMatrix);

    Size tab_, progressBarWidth_;
    //! ORE Input parameters
    boost::shared_ptr<Parameters> params_;
    Date asof_;
    std::ostream& out_;
    bool writeInitialReports_;
    bool simulate_;
    bool buildSimMarket_;
    bool xva_;
    bool writeDIMReport_;
    bool sensitivity_;
    bool stress_;
    bool parametricVar_;
    bool writeBaseScenario_;
    bool continueOnError_;
    std::string inputPath_;
    std::string outputPath_;

    boost::shared_ptr<Market> market_;               // T0 market
    boost::shared_ptr<EngineFactory> engineFactory_; // engine factory linked to T0 market
    boost::shared_ptr<Portfolio> portfolio_;         // portfolio linked to T0 market
    Conventions conventions_;
    TodaysMarketParameters marketParameters_;
    boost::shared_ptr<ReferenceDataManager> referenceData_;

    boost::shared_ptr<ScenarioSimMarket> simMarket_; // sim market
    boost::shared_ptr<Portfolio> simPortfolio_;      // portfolio linked to sim market

    boost::shared_ptr<DateGrid> grid_;
    Size samples_;

    Size cubeDepth_;
    boost::shared_ptr<NPVCube> cube_;
    boost::shared_ptr<AggregationScenarioData> scenarioData_;
    boost::shared_ptr<PostProcess> postProcess_;

    ore::data::CurveConfigurations curveConfigs_;

private:
    virtual ReportWriter* getReportWriterImpl() const { return new ReportWriter(); }
};
} // namespace analytics
} // namespace ore

max_stars_repo_name: nvolfango/Engine

max_issues_repo_name: zhangjiayin/Engine

max_forks_repo_name: zhangjiayin/Engine


text:
//  Copyright (c) 2007-2013 Hartmut Kaiser
//  Copyright (c)      2011 Bryce Lelbach
//  Copyright (c)      2013 Adrian Serio
//
//  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)

// Make HPX inspect tool happy: hpxinspect:nounnamed

#if !defined(HPX_VERSION_AUG_18_2011_0854PM)
#define HPX_VERSION_AUG_18_2011_0854PM

#include <string>

#include <boost/version.hpp>
#include <boost/config.hpp>
#include <boost/cstdint.hpp>
#include <boost/preprocessor/cat.hpp>

#include <hpx/config/export_definitions.hpp>

///////////////////////////////////////////////////////////////////////////////
//  The version of HPX
//
//  HPX_VERSION_FULL & 0x0000FF is the sub-minor version
//  HPX_VERSION_FULL & 0x00FF00 is the minor version
//  HPX_VERSION_FULL & 0xFF0000 is the major version
//
//  HPX_VERSION_DATE   YYYYMMDD is the date of the release
//                               (estimated release date for master branch)
//
#define HPX_VERSION_FULL         0x000911

#define HPX_VERSION_MAJOR        0
#define HPX_VERSION_MINOR        9
#define HPX_VERSION_SUBMINOR     11

#define HPX_VERSION_DATE         20151113

#if !defined(HPX_AGAS_VERSION)
    #define HPX_AGAS_VERSION 0x30
#endif

#define HPX_VERSION_TAG          "-trunk"

#if !defined(HPX_HAVE_GIT_COMMIT)
    #define HPX_HAVE_GIT_COMMIT  "unknown"
#endif

///////////////////////////////////////////////////////////////////////////////
// The version check enforces the major and minor version numbers to match for
// every compilation unit to be compiled.
#define HPX_CHECK_VERSION                                                     \
    BOOST_PP_CAT(hpx_check_version_,                                          \
        BOOST_PP_CAT(HPX_VERSION_MAJOR,                                       \
            BOOST_PP_CAT(_, HPX_VERSION_MINOR)))                              \
    /**/

// The version check enforces the major and minor version numbers to match for
// every compilation unit to be compiled.
#define HPX_CHECK_BOOST_VERSION                                               \
    BOOST_PP_CAT(hpx_check_boost_version_, BOOST_VERSION)                     \
    /**/

///////////////////////////////////////////////////////////////////////////////
namespace hpx
{
    // Returns the major HPX version.
    HPX_EXPORT boost::uint8_t major_version();

    // Returns the minor HPX version.
    HPX_EXPORT boost::uint8_t minor_version();

    // Returns the sub-minor/patch-level HPX version.
    HPX_EXPORT boost::uint8_t subminor_version();

    // Returns the full HPX version.
    HPX_EXPORT boost::uint32_t full_version();

    // Returns the AGAS subsystem version.
    HPX_EXPORT boost::uint8_t agas_version();

    // Returns the tag.
    HPX_EXPORT std::string tag();

    // Returns the HPX full build information string.
    HPX_EXPORT std::string full_build_string();

    // Returns the HPX version string.
    HPX_EXPORT std::string build_string();

    // Returns the Boost version string.
    HPX_EXPORT std::string boost_version();

    // Returns the Boost platform string.
    HPX_EXPORT std::string boost_platform();

    // Returns the Boost compiler string.
    HPX_EXPORT std::string boost_compiler();

    // Returns the Boost standard library string.
    HPX_EXPORT std::string boost_stdlib();

    // Returns the copyright string.
    HPX_EXPORT std::string copyright();

    // Returns the full version string.
    HPX_EXPORT std::string complete_version();

    // Returns the HPX build type ('Debug', 'Release', etc.)
    HPX_EXPORT std::string build_type();

    // Returns the HPX build date and time
    HPX_EXPORT std::string build_date_time();

    // Return the HPX configuration information
    HPX_EXPORT std::string configuration_string();

    // Return the HPX runtime configuration information
    namespace util
    {
        struct command_line_handling;
    }

    HPX_EXPORT std::string runtime_configuration_string(
        util::command_line_handling const& cfg);

    // Helper data structures allowing to automatically detect version problems
    // between applications and the core libraries.
    HPX_EXPORT extern char const HPX_CHECK_VERSION[];
    HPX_EXPORT extern char const HPX_CHECK_BOOST_VERSION[];
}

///////////////////////////////////////////////////////////////////////////////
#if !defined(HPX_EXPORTS) && !defined(HPX_NO_VERSION_CHECK)
    // This is instantiated for each translation unit outside of the HPX core
    // library, forcing to resolve the variable HPX_CHECK_VERSION.
    namespace
    {

#if defined(__clang__)
#  pragma clang diagnostic push
#  pragma clang diagnostic ignored "-Wunused-function"
#endif

#if defined(__GNUG__) && !defined(__INTEL_COMPILER)
#  if defined(HPX_GCC_DIAGNOSTIC_PRAGMA_CONTEXTS)
#    pragma GCC diagnostic push
#  endif
#  pragma GCC diagnostic ignored "-Wunused-function"
#endif

        // Note: this function is never executed.
        char const* check_hpx_version()
        {
            char const* versions[] = {
                hpx::HPX_CHECK_VERSION, hpx::HPX_CHECK_BOOST_VERSION
            };
            return versions[0];
        }

#if defined(__GNUG__) && !defined(__INTEL_COMPILER)
#if defined(HPX_GCC_DIAGNOSTIC_PRAGMA_CONTEXTS)
#pragma GCC diagnostic pop
#endif
#endif

#if defined(__clang__)
#  pragma clang diagnostic pop
#endif

    }
#endif

#endif

ext: hpp

max_stars_repo_name: akemp/hpx

max_issues_repo_name: akemp/hpx

max_forks_repo_name: akemp/hpx


text:
//  (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
//  Permission to copy, use, modify, sell and
//  distribute this software is granted provided this copyright notice appears
//  in all copies. This software is provided "as is" without express or implied
//  warranty, and with no claim as to its suitability for any purpose.
//
//  See http://www.boost.org for most recent version including documentation.
//
//  defines traits classes for arithmetic types:
//  is_void, is_integral, is_float, is_arithmetic, is_fundamental.
//

//  Revision History:
// Feb 19 2001 Added #include <climits> (David Abrahams)

#ifndef BOOST_ARITHMETIC_TYPE_TRAITS_HPP
#define BOOST_ARITHMETIC_TYPE_TRAITS_HPP

#ifndef BOOST_ICE_TYPE_TRAITS_HPP
#include <boost/type_traits/ice.hpp>
#endif
#ifndef BOOST_FWD_TYPE_TRAITS_HPP
#include <boost/type_traits/fwd.hpp>
#endif

#include <limits.h> // for ULLONG_MAX/ULONG_LONG_MAX

namespace boost{

//* is a type T void - is_void<T>
template <typename T> struct is_void{ BOOST_STATIC_CONSTANT(bool, value = false); };
template <> struct is_void<void>{ BOOST_STATIC_CONSTANT(bool, value = true); };

//* is a type T an [cv-qualified-] integral type described in the standard (3.9.1p3)
// as an extention we include long long, as this is likely to be added to the
// standard at a later date
template <typename T> struct is_integral
{ BOOST_STATIC_CONSTANT(bool, value = false); };
template <> struct is_integral<unsigned char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<unsigned short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<unsigned int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<unsigned long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<signed char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<signed short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<signed int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<signed long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
template <> struct is_integral<wchar_t>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif
template <> struct is_integral<bool>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

# if defined(BOOST_HAS_LONG_LONG)
template <> struct is_integral<unsigned long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#elif defined(BOOST_HAS_MS_INT64)
template <> struct is_integral<unsigned __int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<__int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif

//* is a type T a floating-point type described in the standard (3.9.1p8)
template <typename T> struct is_float
{ BOOST_STATIC_CONSTANT(bool, value = false); };
template <> struct is_float<float>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<long double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

//
// declare cv-qualified specialisations of these templates only
// if BOOST_NO_CV_SPECIALIZATIONS is not defined:
#ifndef BOOST_NO_CV_VOID_SPECIALIZATIONS
template <> struct is_void<const void>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_void<volatile void>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_void<const volatile void>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif
#ifndef BOOST_NO_CV_SPECIALIZATIONS
// const-variations:
template <> struct is_integral<const unsigned char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const unsigned short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const unsigned int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const unsigned long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const signed char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const signed short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const signed int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const signed long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
template <> struct is_integral<const wchar_t>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif
template <> struct is_integral<const bool>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

# if defined(BOOST_HAS_LONG_LONG)
template <> struct is_integral<const unsigned long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#elif defined(BOOST_HAS_MS_INT64)
template <> struct is_integral<const unsigned __int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const __int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif //__int64

template <> struct is_float<const float>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<const double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<const long double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

// volatile-variations:
template <> struct is_integral<volatile  unsigned char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  unsigned short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  unsigned int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  unsigned long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  signed char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  signed short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  signed int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  signed long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
template <> struct is_integral<volatile  wchar_t>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif
template <> struct is_integral<volatile  bool>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

# if defined(BOOST_HAS_LONG_LONG)
template <> struct is_integral<volatile  unsigned long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#elif defined(BOOST_HAS_MS_INT64)
template <> struct is_integral<volatile  unsigned __int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<volatile  __int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif //__int64

template <> struct is_float<volatile  float>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<volatile  double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<volatile  long double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

// const-volatile-variations:
template <> struct is_integral<const volatile unsigned char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile unsigned short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile unsigned int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile unsigned long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile signed char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile signed short>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile signed int>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile signed long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile char>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
template <> struct is_integral<const volatile wchar_t>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif
template <> struct is_integral<const volatile bool>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

# if defined(BOOST_HAS_LONG_LONG)
template <> struct is_integral<const volatile unsigned long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile long long>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#elif defined(BOOST_HAS_MS_INT64)
template <> struct is_integral<const volatile unsigned __int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_integral<const volatile __int64>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
#endif //__int64

template <> struct is_float<const volatile float>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<const volatile double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };
template <> struct is_float<const volatile long double>
{ BOOST_STATIC_CONSTANT(bool, value = true); };

#endif // BOOST_NO_CV_SPECIALIZATIONS

//* is a type T an arithmetic type described in the standard (3.9.1p8)
template <typename T>
struct is_arithmetic
{
   BOOST_STATIC_CONSTANT(bool, value =
      (::boost::type_traits::ice_or<
         ::boost::is_integral<T>::value,
         ::boost::is_float<T>::value
      >::value));
};

//* is a type T a fundamental type described in the standard (3.9.1)
template <typename T>
struct is_fundamental
{
   BOOST_STATIC_CONSTANT(bool, value =
      (::boost::type_traits::ice_or<
         ::boost::is_arithmetic<T>::value,
         ::boost::is_void<T>::value
      >::value));
};

} // namespace boost

#endif


text:
#pragma once
#ifndef IBOTPP_LOADER_HPP
#define IBOTPP_LOADER_HPP

#include <string>
#include <boost/container/vector.hpp>
#include <clang/CodeGen/CodeGenAction.h>
#include <clang/Driver/Compilation.h>
#include <clang/Driver/Driver.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/Interpreter.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/Program.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <ibotpp/module.hpp>

namespace ibotpp {
	class loader {
	private:
		std::unique_ptr<llvm::LLVMContext> llvm_context;
		llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diag_ids;
		llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diag_options;
		clang::DiagnosticsEngine diag_engine;
		std::unique_ptr<clang::driver::Driver> driver;
		llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> invocation;
		clang::CompilerInstance compiler;
		llvm::llvm_shutdown_obj llvm_destructor;

	public:
		loader(void)
				: llvm_context(new llvm::LLVMContext()),
				  diag_ids(new clang::DiagnosticIDs()),
				  diag_options(new clang::DiagnosticOptions()),
				  diag_engine(diag_ids, diag_options.get(),
					new clang::TextDiagnosticPrinter(llvm::errs(),
					                                 diag_options.get())),
				  invocation(new clang::CompilerInvocation()) {
			llvm::InitializeNativeTarget();
			llvm::InitializeNativeTargetAsmPrinter();
			llvm::InitializeNativeTargetAsmParser();
			auto error_or_clang_path = llvm::sys::findProgramByName("clang++");
			if(!error_or_clang_path) {
				throw std::runtime_error("failed to find path of clang executable");
			}
			driver = std::unique_ptr<clang::driver::Driver>(
				new clang::driver::Driver(error_or_clang_path.get(),
			                              llvm::sys::getDefaultTargetTriple(),
			                              diag_engine));
			driver->setCheckInputsExist(false);
			compiler.createDiagnostics();
			if(!compiler.hasDiagnostics()) {
				throw std::runtime_error("failed to create compiler instance with diagnostics");
			}
		}

		std::unique_ptr<module> load(const std::string &path) {
			return get_module_value(load_llvm_module("modules/" + path + ".cpp"));
		}

		std::unique_ptr<llvm::Module> load_llvm_module(const std::string &path) {
			auto compilation = driver->BuildCompilation({"-c++", "-std=c++11",
			                                             "-DIBOTPP_IS_MODULE",
			                                             "-Imodules",
			                                             "-include", "ibotpp/module.hpp",
			                                             path.c_str()});
			if(!compilation) {
				throw std::runtime_error("failed to build driver compilation");
			}
			auto &jobs = compilation->getJobs();
			auto &cmd = llvm::cast<clang::driver::Command>(*jobs.begin());
			auto &args = cmd.getArguments();
			clang::CompilerInvocation::CreateFromArgs(*invocation, args.data(),
			                                          args.data() + args.size(),
			                                          diag_engine);
			//llvm::errs() << "clang invocation: ";
			//jobs.Print(llvm::errs(), " ", true);
			//llvm::errs() << "\n";
			compiler.setInvocation(invocation.get());
			clang::EmitLLVMOnlyAction action(llvm_context.get());
			if(!compiler.ExecuteAction(action)) {
				throw std::runtime_error("failed to execute action");
			}
			return action.takeModule();
		}

		std::unique_ptr<module> get_module_value(std::unique_ptr<llvm::Module> m) {
			auto fn = m->getFunction("module");
			if(!fn) {
				throw std::runtime_error("failed to find module function");
			}
			std::string err;
			auto exec_engine = llvm::EngineBuilder(std::move(m))
				.setEngineKind(llvm::EngineKind::Either)
				.setErrorStr(&err)
				.create();
			if(!exec_engine) {
				throw std::runtime_error("failed to create execution engine: " + err);
			}
			exec_engine->finalizeObject();
			auto value = exec_engine->runFunction(fn, {});
			auto ptr = reinterpret_cast<module *>(value.PointerVal);
			return std::unique_ptr<module>(ptr);
		}
	};
}

#endif

max_stars_repo_name: shockkolate/ibot-

max_issues_repo_name: shockkolate/ibot-

max_forks_repo_name: shockkolate/ibot-


text:
<<<<<<< HEAD
/*    Copyright (c) 2010-2018, Delft University of Technology
=======
/*    Copyright (c) 2010-2019, Delft University of Technology
>>>>>>> origin/master
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 *    References
 *      Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge
 *          University Press, February 2002.
 *
 */

#include <boost/multi_array.hpp>

#include "Tudat/Mathematics/Interpolators/linearInterpolator.h"

namespace tudat
{
namespace interpolators
{

//! Compute linear interpolation.
double computeLinearInterpolation( const Eigen::VectorXd& sortedIndependentVariables,
                                   const Eigen::VectorXd& associatedDependentVariables,
                                   const double targetIndependentVariableValue )
{
    // Declare local variables.
    // Declare nearest neighbor.
    int nearestNeighbor;
    double locationTargetIndependentVariableValueInInterval;

    // Compute nearest neighbor in sorted vector of independent variables.
    // Result is always to the left of the target independent variable value.
    nearestNeighbor = basic_mathematics::computeNearestLeftNeighborUsingBinarySearch(
            sortedIndependentVariables, targetIndependentVariableValue );

    // Compute location of target independent variable value in interval
    // between nearest neighbors.
    locationTargetIndependentVariableValueInInterval
            = ( targetIndependentVariableValue
              - sortedIndependentVariables[ nearestNeighbor ] )
             / ( sortedIndependentVariables[ nearestNeighbor + 1 ]
                 - sortedIndependentVariables[ nearestNeighbor ] );

    // Return the computed value of the dependent variable.
    return ( associatedDependentVariables[ nearestNeighbor ]
             * ( 1 - locationTargetIndependentVariableValueInInterval )
             + associatedDependentVariables[ nearestNeighbor + 1 ]
             * locationTargetIndependentVariableValueInInterval );
}

//! Compute linear interpolation.
Eigen::VectorXd computeLinearInterpolation(
        const std::map < double, Eigen::VectorXd >& sortedIndepedentAndDependentVariables,
        const double targetIndependentVariableValue )
{
    // Declare local variables.
    // Declare nearest neighbor.
    int nearestLeftNeighbor;

    // Declare location of target independent variable value in interval.
    double locationTargetIndependentVariableValueInInterval;

    // Declare map iterators
    std::map< double, Eigen::VectorXd >::const_iterator mapIteratorIntervalLeft;
    std::map< double, Eigen::VectorXd >::const_iterator mapIteratorIntervalRight;

    // Compute nearest neighbor in map of data.
    // Result is always to the left of the target independent variable value.
    nearestLeftNeighbor = basic_mathematics::computeNearestLeftNeighborUsingBinarySearch(
                sortedIndepedentAndDependentVariables, targetIndependentVariableValue );

    // Compute location of target independent variable value in interval
    // between nearest neighbors.
    mapIteratorIntervalLeft = sortedIndepedentAndDependentVariables.begin( );
    advance( mapIteratorIntervalLeft, nearestLeftNeighbor );
    mapIteratorIntervalRight = sortedIndepedentAndDependentVariables.begin( );
    advance( mapIteratorIntervalRight, nearestLeftNeighbor + 1 );
    locationTargetIndependentVariableValueInInterval
            = ( targetIndependentVariableValue
              - mapIteratorIntervalLeft->first )
             / ( mapIteratorIntervalRight->first
                 - mapIteratorIntervalLeft->first );

    // Return the computed value of the dependent variable.
    return ( mapIteratorIntervalLeft->second
             * ( 1 - locationTargetIndependentVariableValueInInterval )
             + mapIteratorIntervalRight->second
             * locationTargetIndependentVariableValueInInterval );
}

template class LinearInterpolator< double, Eigen::VectorXd >;
template class LinearInterpolator< double, Eigen::Vector6d >;
template class LinearInterpolator< double, Eigen::MatrixXd >;

template class LinearInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic, 1 > >;
template class LinearInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic, 6 > >;
template class LinearInterpolator< double, Eigen::Matrix< long double, Eigen::Dynamic,  Eigen::Dynamic > >;

} // namespace interpolators
} // mamespace tudat

ext: cpp

max_stars_repo_name: ViktorJordanov/tudat

max_issues_repo_name: ViktorJordanov/tudat

max_forks_repo_name: ViktorJordanov/tudat


text:
#include <iostream>

#include <boost/multiprecision/cpp_dec_float.hpp>

typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<50>> Precise_Decimal;

/*
    Solves two conic sections equations simultaneously.

    It is used to find the intersection points of two conic sections.

    An arbitrary conic section (equation) is of the following form:

    Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0

    where A, B, C, D, and E are arbitrary coefficients, and F is an arbitrary constant.

    - by Melwyn Francis Carlo <carlo.melwyn@outlook.com>

    - Written for LibreCAD software.
*/
RS_VectorSolutions RS_Math::simultaneousQuadraticSolverFull(const std::vector<std::vector<double>>& input_conicSections)
{
    RS_VectorSolutions intersectionPoints;

    if (input_conicSections.size() != 2) return intersectionPoints;

    if ((input_conicSections[0].size() == 3) || (input_conicSections[1].size() == 3))
    {
        return simultaneousQuadraticSolverMixed(input_conicSections);
    }

    if ((input_conicSections[0].size() != 6) || (input_conicSections[1].size() != 6))
    {
        return intersectionPoints;
    }

    std::vector<std::vector<double>> conicSections = input_conicSections;

    for (int i = 0; i < 2; i++)
    {
        unsigned int max_orderOfMagnitudeFactor = 0;

        for (int j = 0; j < 6; j++)
        {
            if (std::fabs(conicSections[i][j]) < RS_TOLERANCE15)
            {
                conicSections[i][j] = 0.0;
            }

            if (conicSections[i][j] < 1.0)
            {
                const unsigned int orderOfMagnitudeFactor = (unsigned int) std::trunc(std::fabs(std::log10(conicSections[i][j]))) + 1;

                if (orderOfMagnitudeFactor > max_orderOfMagnitudeFactor)
                {
                    max_orderOfMagnitudeFactor = orderOfMagnitudeFactor;
                }
            }
        }

        for (int j = 0; j < 6; j++)
        {
            const double orderOfMagnitude = std::pow(10, max_orderOfMagnitudeFactor);

            conicSections[i][j] = std::trunc(conicSections[i][j] * orderOfMagnitude * 1.0E+10) * 1.0E-10;
        }
    }

    const Precise_Decimal a1 = conicSections[0][0];
    const Precise_Decimal b1 = conicSections[0][1];
    const Precise_Decimal c1 = conicSections[0][2];
    const Precise_Decimal d1 = conicSections[0][3];
    const Precise_Decimal e1 = conicSections[0][4];
    const Precise_Decimal f1 = conicSections[0][5];

    const Precise_Decimal a2 = conicSections[1][0];
    const Precise_Decimal b2 = conicSections[1][1];
    const Precise_Decimal c2 = conicSections[1][2];
    const Precise_Decimal d2 = conicSections[1][3];
    const Precise_Decimal e2 = conicSections[1][4];
    const Precise_Decimal f2 = conicSections[1][5];

    if ((a1 == 0.0) || (a2 == 0.0) || (c1 == 0.0) || (c2 == 0.0)) return intersectionPoints;

    const Precise_Decimal a1_sq = a1 * a1;
    const Precise_Decimal b1_sq = b1 * b1;
    const Precise_Decimal c1_sq = c1 * c1;
    const Precise_Decimal d1_sq = d1 * d1;
    const Precise_Decimal e1_sq = e1 * e1;
    const Precise_Decimal f1_sq = f1 * f1;

    const Precise_Decimal a2_sq = a2 * a2;
    const Precise_Decimal b2_sq = b2 * b2;
    const Precise_Decimal c2_sq = c2 * c2;
    const Precise_Decimal d2_sq = d2 * d2;
    const Precise_Decimal e2_sq = e2 * e2;
    const Precise_Decimal f2_sq = f2 * f2;

    const Precise_Decimal c1_cu = c1_sq * c1;

    std::vector<double> x_n_terms(5, 0.0);

    /* The x^4 term. */
    x_n_terms[4] = ((a1_sq * c1 * c2_sq)  + (a2_sq * c1_cu)  - (2.0 * a1 * a2 * c1_sq * c2)
                 + (a2 * b1_sq * c1 * c2) - (a2 * b1 * b2 * c1_sq)
                 + (a1 * b2_sq * c1_sq)  - (a1 * b1 * b2 * c1 * c2)).convert_to<double>();

    /* The x^3 term. */
    x_n_terms[3] = ((2.0 * a1 * c1 * c2_sq * d1) + (2.0 * a2 * c1_cu * d2) - (2.0 * a1 * c1_sq * c2 * d2) - (2.0 * a2 * c1_sq * c2 * d1)
                 + (2.0 * a2 * b1 * c1 * c2 * e1) + (b1_sq * c1 * c2 * d2) - (a2 * b1 * c1_sq * e2) - (a2 * b2 * c1_sq * e1) - (b1 * b2 * c1_sq * d2)
                 + (2.0 * a1 * b2 * c1_sq * e2) + (b2_sq * c1_sq * d1) - (a1 * b1 * c1 * c2 * e2) - (a1 * b2 * c1 * c2 * e1) - (b1 * b2 * c1 * c2 * d1)).convert_to<double>();

    /* The x^2 term. */
    x_n_terms[2] = ((2.0 * a1 * c1 * c2_sq * f1) + (2.0 * a2 * c1_cu * f2) + (c1_cu * d2_sq)  + (c1 * c2_sq * d1_sq)  - (2.0 * a1 * c1_sq * c2 * f2) - (2.0 * a2 * c1_sq * c2 * f1) - (2.0 * c1_sq * c2 * d1 * d2)
                 + (a2 * c1 * c2 * e1_sq)  + (2.0 * b1 * c1 * c2 * d2 * e1) + (b1_sq * c1 * c2 * f2) - (a2 * c1_sq * e1 * e2) - (b1 * b2 * c1_sq * f2) - (b1 * c1_sq * d2 * e2) - (b2 * c1_sq * d2 * e1)
                 + (a1 * c1_sq * e2_sq)  + (b2_sq * c1_sq * f1) + (2.0 * b2 * c1_sq * d1 * e2) - (a1 * c1 * c2 * e1 * e2) - (b1 * b2 * c1 * c2 * f1) - (b1 * c1 * c2 * d1 * e2) - (b2 * c1 * c2 * d1 * e1)).convert_to<double>();

    /* The x term. */
    x_n_terms[1] = ((2.0 * c1_cu * d2 * f2) + (2.0 * c1 * c2_sq * d1 * f1) - (2.0 * c1_sq * c2 * d1 * f2) - (2.0 * c1_sq * c2 * d2 * f1)
                 + (2.0 * b1 * c1 * c2 * e1 * f2) + (c1 * c2 * d2 * e1_sq)  - (b1 * c1_sq * e2 * f2) - (b2 * c1_sq * e1 * f2) - (c1_sq * d2 * e1 * e2)
                 + (c1_sq * d1 * e2_sq)  + (2.0 * b2 * c1_sq * e2 * f1) - (b1 * c1 * c2 * e2 * f1) - (b2 * c1 * c2 * e1 * f1) - (c1 * c2 * d1 * e1 * e2)).convert_to<double>();

    /* The constant term. */
    x_n_terms[0] = ((c1_cu * f2_sq)  + (c1 * c2_sq * f1_sq)  - (2.0 * c1_sq * c2 * f1 * f2)
                 + (c1 * c2 * e1_sq * f2) - (c1_sq * e1 * e2 * f2)
                 + (c1_sq * e2_sq * f1) - (c1 * c2 * e1 * e2 * f1)).convert_to<double>();

    if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)
    {
        DEBUG_HEADER
        std::cout << std::endl << std::endl
                  << " (" << x_n_terms[4] << ")x^4 + "
                  <<  "(" << x_n_terms[3] << ")x^3 + "
                  <<  "(" << x_n_terms[2] << ")x^2 + "
                  <<  "(" << x_n_terms[1] << ")x + "
                  <<  "(" << x_n_terms[0] << ") = 0"
                  << std::endl << std::endl;

        const double a = x_n_terms[4];
        const double b = x_n_terms[3];
        const double c = x_n_terms[2];
        const double d = x_n_terms[1];
        const double e = x_n_terms[0];

        const double a_sq = a * a;
        const double b_sq = b * b;
        const double c_sq = c * c;
        const double d_sq = d * d;
        const double e_sq = e * e;

        const double a_cu = a * a * a;
        const double b_cu = b * b * b;
        const double c_cu = c * c * c;
        const double d_cu = d * d * d;
        const double e_cu = e * e * e;

        std::cout << " Discriminant (Delta) = "
                  << (256.0 * a_cu * e_cu) - (192.0 * a_sq * b * d * e_sq) - (128.0 * a_sq * c_sq * e_sq)
                   + (144.0 * a_sq * c * d_sq * e) - (27.0 * a_sq * d_cu * d) + (144.0 * a * b_sq * c * e_sq)
                   - (6.0 * a * b_sq * d_sq * e) - (80.0 * a * b * c_sq * d * e) + (18.0 * a * b * c * d_cu)
                   + (16.0 * a * c_cu * c * e) - (4.0 * a * c_cu * d_sq) - (27.0 * b_cu * b * e_sq)
                   + (18.0 * b_cu * c * d * e) - (4.0 * b_cu * d_cu) - (4.0 * b_sq * c_cu * e) + (b_sq * c_sq * d_sq)
                  << std::endl << std::endl;

        std::cout << " P Factor = "
                  << (8.0 * a * c) - (3.0 * b_sq)
                  << std::endl << std::endl;

        std::cout << " D Factor = "
                  << (64.0 * a_cu * e) - (16.0 * a_sq * c_sq) + (16.0 * a * b_sq * c) - (16.0 * a_sq * b * d) - (3 * b_cu * b)
                  << std::endl << std::endl;
    }

	std::vector<double> rootsAbscissae = quarticSolverFull(x_n_terms);

    if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)
    {
        std::cout << " Number of quartic roots = " << rootsAbscissae.size()
                  << std::endl << std::endl;
    }

    for (double& rootX : rootsAbscissae)
    {
        const Precise_Decimal rootXPrecise = rootX;

        const Precise_Decimal sqrtTerm1 = boost::multiprecision::trunc(((((b1 * rootXPrecise) + e1) * ((b1 * rootXPrecise) + e1))
                                        - (4.0 * c1 * ((a1 * rootXPrecise * rootXPrecise) + (d1 * rootXPrecise) + f1))) * 1.0E+4) * 1.0E-4;

        const Precise_Decimal sqrtTerm2 = boost::multiprecision::trunc(((((b2 * rootXPrecise) + e2) * ((b2 * rootXPrecise) + e2))
                                        - (4.0 * c2 * ((a2 * rootXPrecise * rootXPrecise) + (d2 * rootXPrecise) + f2))) * 1.0E+4) * 1.0E-4;

        if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)
        {
            std::cout << " RootX square root terms : "
                      << sqrtTerm1 << ", " << sqrtTerm2
                      << std::endl << std::endl;
        }

        if ((sqrtTerm1 < 0.0) || (sqrtTerm2 < 0.0)) continue;

        const Precise_Decimal numeratorTerm1 = (-b1 * rootXPrecise) - e1;
        const Precise_Decimal numeratorTerm2 = (-b2 * rootXPrecise) - e2;

        const Precise_Decimal denominatorTerm1 = 2.0 * c1;
        const Precise_Decimal denominatorTerm2 = 2.0 * c2;

        const RS_Vector conic_1_points[2] =
        {
            RS_Vector(rootX, ((numeratorTerm1 + boost::multiprecision::sqrt(sqrtTerm1)) / denominatorTerm1).convert_to<double>()),
            RS_Vector(rootX, ((numeratorTerm1 - boost::multiprecision::sqrt(sqrtTerm1)) / denominatorTerm1).convert_to<double>())
        };

        const RS_Vector conic_2_points[2] =
        {
            RS_Vector(rootX, ((numeratorTerm2 + boost::multiprecision::sqrt(sqrtTerm2)) / denominatorTerm2).convert_to<double>()),
            RS_Vector(rootX, ((numeratorTerm2 - boost::multiprecision::sqrt(sqrtTerm2)) / denominatorTerm2).convert_to<double>())
        };

        if (((fabs(conic_1_points[0].x - conic_2_points[0].x) < 1.0E-4)
        &&   (fabs(conic_1_points[0].y - conic_2_points[0].y) < 1.0E-4))
        ||  ((fabs(conic_1_points[0].x - conic_2_points[1].x) < 1.0E-4)
        &&   (fabs(conic_1_points[0].y - conic_2_points[1].y) < 1.0E-4)))
        {
            intersectionPoints.push_back(conic_1_points[0]);
        }

        if (((fabs(conic_1_points[1].x - conic_2_points[0].x) < 1.0E-4)
        &&   (fabs(conic_1_points[1].y - conic_2_points[0].y) < 1.0E-4))
        ||  ((fabs(conic_1_points[1].x - conic_2_points[1].x) < 1.0E-4)
        &&   (fabs(conic_1_points[1].y - conic_2_points[1].y) < 1.0E-4)))
        {
            intersectionPoints.push_back(conic_1_points[1]);
        }

        if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)
        {
            std::cout << " Available roots : " << std::endl
                      << " 1.1. " << conic_1_points[0] << std::endl
                      << " 1.2. " << conic_1_points[1] << std::endl
                      << " 2.1. " << conic_2_points[0] << std::endl
                      << " 2.2. " << conic_2_points[1] << std::endl << std::endl;

            std::cout << " Chosen root : " << intersectionPoints [intersectionPoints.size() - 1]
                      << std::endl << std::endl;
        }
    }

    if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)
    {
        std::cout << " Number of intersection points = " << intersectionPoints.size()
                  << std::endl << std::endl;
    }

    return intersectionPoints;
}


text:
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

#include <Magick++/Drawable.h>
#include <Magick++.h>

using namespace boost::python;

namespace  {

struct Magick_DrawableTextUnderColor_Wrapper: Magick::DrawableTextUnderColor
{
    Magick_DrawableTextUnderColor_Wrapper(PyObject* py_self_, const Magick::Color& p0):
        Magick::DrawableTextUnderColor(p0), py_self(py_self_) {}

    Magick_DrawableTextUnderColor_Wrapper(PyObject* py_self_, const Magick::DrawableTextUnderColor& p0):
        Magick::DrawableTextUnderColor(p0), py_self(py_self_) {}

    PyObject* py_self;
};

}

void __DrawableTextUnderColor()
{
    class_< Magick::DrawableTextUnderColor, bases<Magick::DrawableBase>, Magick_DrawableTextUnderColor_Wrapper >("DrawableTextUnderColor", init< const Magick::Color& >())
        .def(init< const Magick::DrawableTextUnderColor& >())
        .def("color", (void (Magick::DrawableTextUnderColor::*)(const Magick::Color&) )&Magick::DrawableTextUnderColor::color)
        .def("color", (Magick::Color (Magick::DrawableTextUnderColor::*)() const)&Magick::DrawableTextUnderColor::color)
    ;
}

max_stars_repo_name: veryhappythings/pgmagick

max_issues_repo_name: veryhappythings/pgmagick

max_forks_repo_name: veryhappythings/pgmagick


text:
#include <iostream>

#include <boost/log/trivial.hpp>

#include "transport.h"

class TCPTest:  public Receiver, public enable_shared_from_this<TCPTest> {
public:

    std::unique_ptr<AsyncTCPServer> udp_server;

    void start(unsigned short port) {
        BOOST_LOG_TRIVIAL(debug) << "TCPTest::start: Allocating udp_server";
        udp_server.reset(new AsyncTCPServer(static_pointer_cast<Receiver>(this->shared_from_this()), port));
        this->udp_server->run();
    }

    virtual void receive(const std::string& ip, unsigned short port, const std::string& data) override {
        BOOST_LOG_TRIVIAL(info) << "TCPTest::receive: Packet of length " + std::to_string(data.length()) + " received from " + ip + ':' + std::to_string(port) + '\n' + data;

        unsigned short remote_port = 63304;

        BOOST_LOG_TRIVIAL(info) << "TCPTest::receive: Responding to " + ip + ':' + std::to_string(remote_port) + '\n';
        std::string msg = "Packet of length " + std::to_string(data.length()) + " received from " + ip + ':' + std::to_string(remote_port);

        this->udp_server->send(ip, remote_port, msg);
    }

};

int main(int argc, char* argv[]) {
    BOOST_LOG_TRIVIAL(debug) << "main: Starting with " << argc << " arguments";
    unsigned short port = std::stoi(argv[1]);
    BOOST_LOG_TRIVIAL(debug) << "main: Port number " << port;
    std::shared_ptr<TCPTest> udp_test(new TCPTest());
    udp_test->start(port);
    udp_test->udp_server->stop();
    return 0;
}


text:
#define BOOST_TEST_MODULE module_test

#include <blockchain_plugin.hpp>
#include <blockbuilder_plugin.hpp>
#include "script_module.hpp"
#include "script_global_module.hpp"
#include <boost/test/included/unit_test.hpp>
#include "pro/utils/singleton.hpp"

using namespace xmaxapp;
using namespace xmax;
using namespace boost::unit_test;

#define Test_Script

#ifdef Test_Script
BOOST_AUTO_TEST_SUITE(vm_plugin_test)

BOOST_AUTO_TEST_CASE(bpt_1)
{
 	xmax::scriptv8::ScriptGlobalMoudle::GetInstance().SetupV8Env();

	v8::Isolate::Scope isolate_scope(xmax::scriptv8::ScriptGlobalMoudle::GetInstance().GetIsolate());
	v8::HandleScope handle_scope(xmax::scriptv8::ScriptGlobalMoudle::GetInstance().GetIsolate());

	v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(xmax::scriptv8::ScriptGlobalMoudle::GetInstance().GetIsolate());
	xmax::scriptv8::ScriptGlobalMoudle::GetInstance().V8SetupGlobalObjTemplate(&global);

	xmax::scriptv8::ScriptMoudle module;
	xmax::scriptv8::ScriptGlobalMoudle::GetInstance().SetCurrentModule(&module);
	module.CleanInstrunction();
	module.LoadScript("function LoopCheckTest() { int i = 10; while ( i > 0 ) { i--; }");
	module.RunFoo("LoopCheckTest");
 	xmax::scriptv8::ScriptGlobalMoudle::GetInstance().DiscardV8Env();
}

BOOST_AUTO_TEST_SUITE_END()
#endif

max_stars_repo_name: xleakOfficial/xmax-mainchain

max_issues_repo_name: xleakOfficial/xmax-mainchain

max_forks_repo_name: xleakOfficial/xmax-mainchain


text:
#ifndef DATASET_HPP
#define DATASET_HPP

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

#include "Eigen/Core"
#include <Eigen/Geometry>

class DataSet
{
public:
  DataSet(const std::string& folder);
  ~DataSet();

  bool get_next_point_cloud(Eigen::MatrixXd& P, Eigen::MatrixXd &colors, Eigen::Matrix4d& t_camera);
  Eigen::Affine3f findPlaneRotation(Eigen::MatrixXd& points);
private:
  bool operational;
  int next_file_idx;
  std::string folder_path;
  std::vector<std::string> depth_files;
  std::string rgb_ref_file_name;
  std::fstream camera_ref_file;
  Eigen::Matrix4d rOffset;

  bool get_next_camera(Eigen::Matrix4d& cam, const double timestamp);
  std::string get_next_rgb(const double timestamp);
};

#endif // DATASET_HPP

max_stars_repo_name: asterycs/rtsr

max_issues_repo_name: haohanxingkong/rtsr

max_forks_repo_name: haohanxingkong/rtsr


text:
#ifndef BOOST_LEAF_COMMON_HPP_INCLUDED
#define BOOST_LEAF_COMMON_HPP_INCLUDED

// Copyright (c) 2018-2020 Emil Dotchevski and Reverge Studios, Inc.

// 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)

#if defined(__clang__)
#	pragma clang system_header
#elif (__GNUC__*100+__GNUC_MINOR__>301) && !defined(BOOST_LEAF_ENABLE_WARNINGS)
#	pragma GCC system_header
#elif defined(_MSC_VER) && !defined(BOOST_LEAF_ENABLE_WARNINGS)
#	pragma warning(push,1)
#endif

#include <boost/leaf/detail/print.hpp>
#include <string>
#include <cerrno>
#ifdef _WIN32
#	include <Windows.h>
#	include <cstring>
#ifdef min
#	undef min
#endif
#ifdef max
#	undef max
#endif
#endif

namespace boost { namespace leaf {

	struct e_api_function { char const * value; };

	struct e_file_name { std::string value; };

	struct e_errno
	{
		int value;

		friend std::ostream & operator<<( std::ostream & os, e_errno const & err )
		{
			return os << type<e_errno>() << ": " << err.value << ", \"" << std::strerror(err.value) << '"';
		}
	};

	struct e_type_info_name { char const * value; };

	struct e_at_line { int value; };

	namespace windows
	{
		struct e_LastError
		{
			unsigned value;
		};
	}

} }

#endif


text:
#pragma once

#include <cstddef>
#include <string>

#include <boost/optional.hpp>

inline
std::size_t
operator "" _B(unsigned long long size)
{
  return size;
}

inline
std::size_t
operator "" _kB(unsigned long long size)
{
  return size * 1000;
}

inline
std::size_t
operator "" _MB(unsigned long long size)
{
  return size * 1'000'000;
}

inline
std::size_t
operator "" _GB(unsigned long long size)
{
  return size * 1000'000'000;
}

inline
std::size_t
operator "" _KiB(unsigned long long size)
{
  return size * 1024;
}

inline
std::size_t
operator "" _MiB(unsigned long long size)
{
  return size * 1024 * 1024;
}

inline
std::size_t
operator "" _GiB(unsigned long long size)
{
  return size * 1024 * 1024 * 1024;
}

namespace elle
{
  /// Pretty-print a number of bytes.
  ///
  /// @param bytes  The number of bytes.
  /// @param si     Whether to use scientific notation (KB vs KiB, etc.).
  std::string
  human_data_size(double bytes, bool si = true);

  /// Convert an optional capacity in string into an optional capacity.
  boost::optional<int64_t>
  convert_capacity(boost::optional<std::string> capacity);

  /// Parse a capacity with embeded unit.
  ///
  /// For instance "10KB" => 10000, "10KiB" => 10240.
  int64_t convert_capacity(std::string value);

  /// Parse a capacity, with its unit on the side.
  long double
  convert_capacity(long double value, std::string unit);
}

ext: hh

max_issues_repo_name: mefyl/elle

max_forks_repo_name: mefyl/elle


text:
/*
Copyright (c) 2015, Tianwei Shen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of libvot nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

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

/** \file euclidean_matrix.cpp
 *	\brief euclidean matrix completion (exe)
 */
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <stdio.h>
#include <cmath>
#include <vector>

#include <Eigen/Dense>
#include <Eigen/SVD>

using namespace std;

/**
 * @brief An ad-hoc simple 2d point struct
 */
namespace {
struct point2d
{
	float x,y;
};
}	// end of namespace vot

float EuclideanDistance(point2d x1, point2d x2)
{
	return (x1.x - x2.x) * (x1.x - x2.x) + (x1.y - x2.y) * (x1.y - x2.y);
}

int main(int argc, char **argv)
{
	int input_size;
	cout << "the size of the matrix: \n";
	cin >> input_size;
	const int MATRIX_SIZE = input_size;
	string matrix_filename = "euclidean_matrix";
	stringstream ss;
	ss << matrix_filename << "_" << MATRIX_SIZE;
	ss >> matrix_filename;
	FILE *matrix_file = fopen(matrix_filename.c_str(), "w");

	std::vector<point2d> points(MATRIX_SIZE);
	for (int i = 0; i < MATRIX_SIZE; i++) {
		points[i].x = rand() % 1000;
		points[i].x /= 1000;
		points[i].y = rand() % 1000;
		points[i].y /= 1000;
	}

	Eigen::MatrixXf distance_matrix(MATRIX_SIZE, MATRIX_SIZE);
	for (int i = 0; i < MATRIX_SIZE; i++) {
		distance_matrix(i, i) = 0.0;
		for (int j = i+1; j < MATRIX_SIZE; j++) {
			distance_matrix(i, j) = EuclideanDistance(points[i], points[j]);
			distance_matrix(j, i) = distance_matrix(i, j);
		}
	}

	// output to the file
	for (int i = 0; i < MATRIX_SIZE; i++) {
		for (int j = 0; j < MATRIX_SIZE; j++) {
			cout << distance_matrix(i, j) << " ";
			fprintf(matrix_file, "%f ", distance_matrix(i, j));
		}
		cout << endl;
		fprintf(matrix_file, "\n");
	}

	Eigen::FullPivLU<Eigen::MatrixXf> lu_decomp(distance_matrix);
	//lu_decomp.setThreshold(1e-5);
	cout << "rank of distance matrix: " << lu_decomp.rank() << endl;

	//Eigen::JacobiSVD<Eigen::MatrixXf> svd(distance_matrix, Eigen::ComputeThinU | Eigen::ComputeThinV);
	//cout << svd.singularValues() << endl;

	fclose(matrix_file);
	return 0;
}

max_stars_repo_name: zyxrrr/GraphSfM

max_issues_repo_name: zyxrrr/GraphSfM

max_forks_repo_name: zyxrrr/GraphSfM


text:
#include <mtpio/chain/platform_timer_accuracy.hpp>
#include <mtpio/chain/platform_timer.hpp>

#include <fc/time.hpp>
#include <fc/log/logger.hpp>

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>

#include <chrono>
#include <mutex>

namespace mtpio { namespace chain {

namespace bacc = boost::accumulators;

void compute_and_print_timer_accuracy(platform_timer& timer) {
   static std::mutex m;
   static bool once_is_enough;

   std::lock_guard guard(m);

   if(once_is_enough)
      return;

   bacc::accumulator_set<int, bacc::stats<bacc::tag::mean, bacc::tag::min, bacc::tag::max, bacc::tag::variance>, float> samples;

   //keep longest first in list. You're effectively going to take test_intervals[0]*sizeof(test_intervals[0])
   //time to do the the test
   int test_intervals[] = {50000, 10000, 5000, 1000, 500, 100, 50, 10};

   for(int& interval : test_intervals) {
      unsigned int loops = test_intervals[0]/interval;

      for(unsigned int i = 0; i < loops; ++i) {
         auto start = std::chrono::high_resolution_clock::now();
         timer.start(fc::time_point(fc::time_point::now().time_since_epoch() + fc::microseconds(interval)));
         while(!timer.expired) {}
         auto end = std::chrono::high_resolution_clock::now();
         int timer_slop = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count() - interval;

         //since more samples are run for the shorter expirations, weigh the longer expirations accordingly. This
         //helps to make a few results more fair. Two such examples: AWS c4&i5 xen instances being rather stable
         //down to 100us but then struggling with 50us and 10us. MacOS having performance that seems to correlate
         //with expiry length; that is, long expirations have high error, short expirations have low error.
         //That said, for these platforms, a tighter tolerance may possibly be achieved by taking performance
         //metrics in mulitple bins and appliying the slop based on which bin a deadline resides in. Not clear
         //if that's worth the extra complexity at this point.
         samples(timer_slop, bacc::weight = interval/(float)test_intervals[0]);
      }
   }

   #define TIMER_STATS_FORMAT "min:${min}us max:${max}us mean:${mean}us stddev:${stddev}us"
   #define TIMER_STATS \
      ("min", bacc::min(samples))("max", bacc::max(samples)) \
      ("mean", (int)bacc::mean(samples))("stddev", (int)sqrt(bacc::variance(samples)))

   ilog("Checktime timer accuracy: " TIMER_STATS_FORMAT, TIMER_STATS);
   if(bacc::mean(samples) + sqrt(bacc::variance(samples))*2 > 250)
      wlog("Checktime timer accuracy on this platform and hardware combination is poor; accuracy of subjective transaction deadline enforcement will suffer");

   once_is_enough = true;
}

}}

max_stars_repo_name: mtpbuilder/mtp

max_issues_repo_name: zhllljm/mtp

max_forks_repo_name: zhllljm/mtp


text:
#include <iostream>6
#include<conio.h>
#include <armadillo>
#include"linearRegression .h"
using namespace std;
using namespace arma;

// Armadillo documentation is available at:
// http://arma.sourceforge.net/docs.html

int
main(int argc, char** argv)
  {
	mat ketquasoxo;
	ketquasoxo.load("w.txt", arma_ascii);
	mat thamSo1 = ketquasoxo.col(1);
	mat thamSo2 = ketquasoxo.cols(1,2);
	mat thamSo3 = ketquasoxo.cols(1, 3);
	mat thamSo4 = ketquasoxo.cols(1, 4);
	mat thamSo5 = ketquasoxo.cols(1, 5);
	//cout << thamSo5;
	//cout << ketquasoxo<<endl;
	//cout << X1;
	mat Y = ketquasoxo.col(2);
	mat heSo1 = LinearRegreeOne(thamSo1, Y);
	mat heSo2 = LinearRegreeOne(thamSo2, ketquasoxo.col(3));
	mat heSo3 = LinearRegreeOne(thamSo3, ketquasoxo.col(4));
	mat heSo4 = LinearRegreeOne(thamSo4, ketquasoxo.col(5));
	mat heso5 = LinearRegreeOne(thamSo5, ketquasoxo.col(6));
	mat conSoMayMan = ones(2,1) ;
	double x;
	ketquasoxo(0, 0);
	cout << "nhap vao con so may man" << endl;
	cin >> x;
	conSoMayMan(1, 0) = x;
	//cout << heSo2;
	mat ketqua =  KetQuaTraVe(heSo1, conSoMayMan);
	conSoMayMan = join_cols(conSoMayMan, ketqua);
	ketqua = KetQuaTraVe(heSo2, conSoMayMan);
	conSoMayMan = join_cols(conSoMayMan, ketqua);
	ketqua = KetQuaTraVe(heSo3, conSoMayMan);
	conSoMayMan = join_cols(conSoMayMan, ketqua);
	ketqua = KetQuaTraVe(heSo4, conSoMayMan);
	conSoMayMan = join_cols(conSoMayMan, ketqua);
	ketqua = KetQuaTraVe(heso5, conSoMayMan);
	conSoMayMan = join_cols(conSoMayMan, ketqua);
	//cout << conSoMayMan;
	cout << "Day so ban nen danh ngay hom nay la:"<<endl;
	cout << (int)conSoMayMan(1, 0)<<" "<<(int) conSoMayMan(2,0)<< " " << (int)conSoMayMan(3, 0)<< " " << (int)conSoMayMan(4, 0)<< " " << (int)conSoMayMan(5, 0)<< " " << (int)conSoMayMan(6, 0)<<endl;
	getch();
	return 0;

  }

max_stars_repo_name: batuan/CodeDoAn-LinearRegressionfull

max_issues_repo_name: batuan/CodeDoAn-LinearRegressionfull

max_forks_repo_name: batuan/CodeDoAn-LinearRegressionfull


text:
$NetBSD: patch-src_pingus_config__manager.hpp,v 1.1 2019/05/12 06:17:30 triaxx Exp $

* Port to Boost.Signals2.

--- src/pingus/config_manager.hpp.orig	2011-12-24 21:46:47.000000000 +0000
+++ src/pingus/config_manager.hpp
@@ -17,7 +17,7 @@
 #ifndef HEADER_PINGUS_PINGUS_CONFIG_MANAGER_HPP
 #define HEADER_PINGUS_PINGUS_CONFIG_MANAGER_HPP

-#include <boost/signal.hpp>
+#include <boost/signals2.hpp>

 #include "math/size.hpp"
 #include "pingus/options.hpp"
@@ -39,55 +39,55 @@ public:

   void set_master_volume(int);
   int  get_master_volume() const;
-  boost::signal<void(int)> on_master_volume_change;
+  boost::signals2::signal<void(int)> on_master_volume_change;

   void set_sound_volume(int);
   int  get_sound_volume() const;
-  boost::signal<void(int)> on_sound_volume_change;
+  boost::signals2::signal<void(int)> on_sound_volume_change;

   void set_music_volume(int);
   int  get_music_volume() const;
-  boost::signal<void(int)> on_music_volume_change;
+  boost::signals2::signal<void(int)> on_music_volume_change;

   void set_fullscreen_resolution(const Size& size);
   Size get_fullscreen_resolution() const;
-  boost::signal<void(Size)> on_fullscreen_resolution_change;
+  boost::signals2::signal<void(Size)> on_fullscreen_resolution_change;

   void set_fullscreen(bool);
   bool get_fullscreen() const;
-  boost::signal<void(bool)> on_fullscreen_change;
+  boost::signals2::signal<void(bool)> on_fullscreen_change;

   void set_renderer(FramebufferType type);
   FramebufferType get_renderer() const;
-  boost::signal<void(FramebufferType)> on_renderer_change;
+  boost::signals2::signal<void(FramebufferType)> on_renderer_change;

   void set_resizable(bool);
   bool get_resizable() const;
-  boost::signal<void(bool)> on_resizable_change;
+  boost::signals2::signal<void(bool)> on_resizable_change;

   void set_mouse_grab(bool);
   bool get_mouse_grab() const;
-  boost::signal<void(bool)> on_mouse_grab_change;
+  boost::signals2::signal<void(bool)> on_mouse_grab_change;

   void set_print_fps(bool);
   bool get_print_fps() const;
-  boost::signal<void(bool)> on_print_fps_change;
+  boost::signals2::signal<void(bool)> on_print_fps_change;

   void set_language(const tinygettext::Language&);
   tinygettext::Language get_language() const;
-  boost::signal<void(const tinygettext::Language&)> on_language_change;
+  boost::signals2::signal<void(const tinygettext::Language&)> on_language_change;

   void set_software_cursor(bool);
   bool get_software_cursor() const;
-  boost::signal<void(bool)> on_software_cursor_change;
+  boost::signals2::signal<void(bool)> on_software_cursor_change;

   void set_auto_scrolling(bool);
   bool get_auto_scrolling() const;
-  boost::signal<void(bool)> on_auto_scrolling_change;
+  boost::signals2::signal<void(bool)> on_auto_scrolling_change;

   void set_drag_drop_scrolling(bool);
   bool get_drag_drop_scrolling() const;
-  boost::signal<void(bool)> on_drag_drop_scrolling_change;
+  boost::signals2::signal<void(bool)> on_drag_drop_scrolling_change;

 private:
   ConfigManager (const ConfigManager&);


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

#include "revgen.hpp"

#include <iostream>

#include <boost/dynamic_bitset.hpp>
#include <boost/program_options.hpp>

#include <cli/reversible_stores.hpp>
#include <core/utils/bitset_utils.hpp>
#include <classical/utils/truth_table_utils.hpp>
#include <reversible/truth_table.hpp>

namespace cirkit
{

using boost::program_options::value;

revgen_command::revgen_command( const environment::ptr& env )
  : cirkit_command( env, "Generate reversible structures" )
{
  opts.add_options()
    ( "hwb",   value( &hwb ),   "generate reversible HWB function" )
    ( "prime", value( &prime ), "generate reversible nth-prime function" )
    ;
}

bool revgen_command::execute()
{
  if ( is_set( "hwb" ) )
  {
    binary_truth_table spec;

    boost::dynamic_bitset<> b( hwb );

    spec.add_entry( number_to_truth_table_cube( 0u, hwb ), number_to_truth_table_cube( 0u, hwb ) );

    do {
      if ( b.any() )
      {
        const auto shift = b.count();
        const auto out = ( b << shift ) | ( b >> ( hwb - shift ) );

        const auto c_in = number_to_truth_table_cube( b.to_ulong(), hwb );
        const auto c_out = number_to_truth_table_cube( out.to_ulong(), hwb );

        spec.add_entry( c_in, c_out );
      }

      inc( b );
    } while ( b.any() );

    auto& specs = env->store<binary_truth_table>();

    if ( specs.empty() )
    {
      specs.extend();
    }
    specs.current() = spec;
  }
  else if ( is_set( "prime" ) )
  {
    binary_truth_table spec;

    spec.add_entry( number_to_truth_table_cube( 0u, prime ),
                    number_to_truth_table_cube( 0u, prime ) );

    auto index = 1u;
    auto pt = primes;

    while ( *pt < ( 1u << prime ) )
    {
      spec.add_entry( number_to_truth_table_cube( index++, prime ),
                      number_to_truth_table_cube( *pt++, prime ) );
    }

    pt = primes;
    auto non_prime = 1u;

    while ( index < ( 1u << prime ) )
    {
      while ( non_prime < *pt )
      {
        spec.add_entry( number_to_truth_table_cube( index++, prime ),
                        number_to_truth_table_cube( non_prime++, prime ) );
      }
      ++non_prime;
      ++pt;
    }

    auto& specs = env->store<binary_truth_table>();

    if ( specs.empty() )
    {
      specs.extend();
    }
    specs.current() = spec;
  }

  return true;
}

}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
#include <sys/epoll.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <system_error>
#include <iostream>
#include <boost/intrusive_ptr.hpp>
#include "proxifier.hh"
#include "../core/poller.hh"
#include "../proxifier/readabledeferreactor.hh"
#include "sessionsupplicationagent.hh"
#include "tfocookiesupplicationagent.hh"
#include "proxifierupstreamer.hh"

using namespace std;
using boost::intrusive_ptr;

Proxifier::Proxifier(Poller *poller, const S6U::SocketAddress &proxyAddr, const S6U::SocketAddress &bindAddr, bool defer, const pair<string_view, string_view> &credentials, TLSContext *clientCtx)
	: ListenReactor(poller, bindAddr), proxyAddr(proxyAddr), defer(defer),
	  username(credentials.first), password(credentials.second),
	  clientCtx(clientCtx)
{
	// tolerable error
	S6U::Socket::saveSYN(listenFD);
}

void Proxifier::start()
{
	bool supplicateTFO = true;

	supplicationLock.lock();
	try
	{
		auto sessionSupplicant = make_shared<SessionSupplicant>(this);
		poller->assign(new SessionSupplicationAgent(this, sessionSupplicant, clientCtx));

		if (clientCtx) /* TLS uses TFO */
			supplicateTFO = false;
	}
	catch (exception &ex)
	{
		cerr << "Error supplicating token window: " << ex.what() << endl;
	}

	if (supplicateTFO)
	{
		try
		{
			poller->assign(new TFOCookieSupplicationAgent(this));
		}
		catch (exception &ex)
		{
			cerr << "Error supplicating TFO cookie: " << ex.what() << endl;
		}
	}

	ListenReactor::start();
}

void Proxifier::handleNewConnection(int fd)
{
	UniqFD ufd(fd);
	std::shared_ptr<SessionSupplicant> supplicant;

	if (supplicationLock.try_lock())
	{
		if (!session)
			supplicant = make_shared<SessionSupplicant>(this);
		else
			supplicationLock.unlock();
	}

	try
	{

		intrusive_ptr<ProxifierUpstreamer> upstreamer = new ProxifierUpstreamer(this, move(ufd), supplicant);
		if (defer)
			poller->assign(new ReadableDeferReactor(poller, fd, upstreamer));
		else
			poller->assign(upstreamer);
	}
	catch (exception &ex)
	{
		cerr << "Error handling new connection: " << ex.what() << endl;
	}
}

ext: cc

max_stars_repo_name: vlolteanu/sixtysocks

max_issues_repo_name: vlolteanu/sixtysocks

max_forks_repo_name: vlolteanu/sixtysocks


text:
#include <boost/asio/io_service.hpp>
#include <boost/asio/steady_timer.hpp>
#include <chrono>
#include <thread>
#include <iostream>

using namespace std;
using namespace boost::asio;

int main()
{
  io_service ioservice;

  steady_timer timer1{ioservice, std::chrono::seconds{3}};
  timer1.async_wait([](const boost::system::error_code& __unused ec)
    { cout << "timer1: 3 seconds." << endl; });

  steady_timer timer2{ioservice, std::chrono::seconds{3}};
  timer2.async_wait([](const boost::system::error_code& __unused ec)
    { cout << "timer2: 3 seconds." << endl; });

  thread thread1{[&ioservice](){ ioservice.run(); }};
  thread thread2{[&ioservice](){ ioservice.run(); }};
  thread1.join();
  thread2.join();
}


text:
//
// detail/impl/task_io_service.ipp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef ASIO_DETAIL_IMPL_TASK_IO_SERVICE_IPP
#define ASIO_DETAIL_IMPL_TASK_IO_SERVICE_IPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include "asio/detail/config.hpp"

#if !defined(ASIO_HAS_IOCP)

#include <boost/limits.hpp>
#include "asio/detail/call_stack.hpp"
#include "asio/detail/event.hpp"
#include "asio/detail/reactor.hpp"
#include "asio/detail/task_io_service.hpp"

#include "asio/detail/push_options.hpp"

namespace asio {
namespace detail {

struct task_io_service::task_cleanup
{
  ~task_cleanup()
  {
    // Enqueue the completed operations and reinsert the task at the end of
    // the operation queue.
    lock_->lock();
    task_io_service_->task_interrupted_ = true;
    task_io_service_->op_queue_.push(*ops_);
    task_io_service_->op_queue_.push(&task_io_service_->task_operation_);
  }

  task_io_service* task_io_service_;
  mutex::scoped_lock* lock_;
  op_queue<operation>* ops_;
};

struct task_io_service::work_finished_on_block_exit
{
  ~work_finished_on_block_exit()
  {
    task_io_service_->work_finished();
  }

  task_io_service* task_io_service_;
};

struct task_io_service::idle_thread_info
{
  event wakeup_event;
  idle_thread_info* next;
};

task_io_service::task_io_service(asio::io_service& io_service)
  : asio::detail::service_base<task_io_service>(io_service),
    mutex_(),
    task_(0),
    task_interrupted_(true),
    outstanding_work_(0),
    stopped_(false),
    shutdown_(false),
    first_idle_thread_(0)
{
  ASIO_HANDLER_TRACKING_INIT;
}

void task_io_service::init(std::size_t /*concurrency_hint*/)
{
}

void task_io_service::shutdown_service()
{
  mutex::scoped_lock lock(mutex_);
  shutdown_ = true;
  lock.unlock();

  // Destroy handler objects.
  while (!op_queue_.empty())
  {
    operation* o = op_queue_.front();
    op_queue_.pop();
    if (o != &task_operation_)
      o->destroy();
  }

  // Reset to initial state.
  task_ = 0;
}

void task_io_service::init_task()
{
  mutex::scoped_lock lock(mutex_);
  if (!shutdown_ && !task_)
  {
    task_ = &use_service<reactor>(this->get_io_service());
    op_queue_.push(&task_operation_);
    wake_one_thread_and_unlock(lock);
  }
}

std::size_t task_io_service::run(asio::error_code& ec)
{
  ec = asio::error_code();
  if (outstanding_work_ == 0)
  {
    stop();
    return 0;
  }

  call_stack<task_io_service>::context ctx(this);

  idle_thread_info this_idle_thread;
  this_idle_thread.next = 0;

  mutex::scoped_lock lock(mutex_);

  std::size_t n = 0;
  for (; do_one(lock, &this_idle_thread); lock.lock())
    if (n != (std::numeric_limits<std::size_t>::max)())
      ++n;
  return n;
}

std::size_t task_io_service::run_one(asio::error_code& ec)
{
  ec = asio::error_code();
  if (outstanding_work_ == 0)
  {
    stop();
    return 0;
  }

  call_stack<task_io_service>::context ctx(this);

  idle_thread_info this_idle_thread;
  this_idle_thread.next = 0;

  mutex::scoped_lock lock(mutex_);

  return do_one(lock, &this_idle_thread);
}

std::size_t task_io_service::poll(asio::error_code& ec)
{
  if (outstanding_work_ == 0)
  {
    stop();
    ec = asio::error_code();
    return 0;
  }

  call_stack<task_io_service>::context ctx(this);

  mutex::scoped_lock lock(mutex_);

  std::size_t n = 0;
  for (; do_one(lock, 0); lock.lock())
    if (n != (std::numeric_limits<std::size_t>::max)())
      ++n;
  return n;
}

std::size_t task_io_service::poll_one(asio::error_code& ec)
{
  ec = asio::error_code();
  if (outstanding_work_ == 0)
  {
    stop();
    return 0;
  }

  call_stack<task_io_service>::context ctx(this);

  mutex::scoped_lock lock(mutex_);

  return do_one(lock, 0);
}

void task_io_service::stop()
{
  mutex::scoped_lock lock(mutex_);
  stop_all_threads(lock);
}

bool task_io_service::stopped() const
{
  mutex::scoped_lock lock(mutex_);
  return stopped_;
}

void task_io_service::reset()
{
  mutex::scoped_lock lock(mutex_);
  stopped_ = false;
}

void task_io_service::post_immediate_completion(task_io_service::operation* op)
{
  work_started();
  post_deferred_completion(op);
}

void task_io_service::post_deferred_completion(task_io_service::operation* op)
{
  mutex::scoped_lock lock(mutex_);
  op_queue_.push(op);
  wake_one_thread_and_unlock(lock);
}

void task_io_service::post_deferred_completions(
    op_queue<task_io_service::operation>& ops)
{
  if (!ops.empty())
  {
    mutex::scoped_lock lock(mutex_);
    op_queue_.push(ops);
    wake_one_thread_and_unlock(lock);
  }
}

std::size_t task_io_service::do_one(mutex::scoped_lock& lock,
    task_io_service::idle_thread_info* this_idle_thread)
{
  bool polling = !this_idle_thread;
  bool task_has_run = false;
  while (!stopped_)
  {
    if (!op_queue_.empty())
    {
      // Prepare to execute first handler from queue.
      operation* o = op_queue_.front();
      op_queue_.pop();
      bool more_handlers = (!op_queue_.empty());

      if (o == &task_operation_)
      {
        task_interrupted_ = more_handlers || polling;

        // If the task has already run and we're polling then we're done.
        if (task_has_run && polling)
        {
          task_interrupted_ = true;
          op_queue_.push(&task_operation_);
          return 0;
        }
        task_has_run = true;

        if (!more_handlers || !wake_one_idle_thread_and_unlock(lock))
          lock.unlock();

        op_queue<operation> completed_ops;
        task_cleanup c = { this, &lock, &completed_ops };
        (void)c;

        // Run the task. May throw an exception. Only block if the operation
        // queue is empty and we're not polling, otherwise we want to return
        // as soon as possible.
        task_->run(!more_handlers && !polling, completed_ops);
      }
      else
      {
        if (more_handlers)
          wake_one_thread_and_unlock(lock);
        else
          lock.unlock();

        // Ensure the count of outstanding work is decremented on block exit.
        work_finished_on_block_exit on_exit = { this };
        (void)on_exit;

        // Complete the operation. May throw an exception.
        o->complete(*this); // deletes the operation object

        return 1;
      }
    }
    else if (this_idle_thread)
    {
      // Nothing to run right now, so just wait for work to do.
      this_idle_thread->next = first_idle_thread_;
      first_idle_thread_ = this_idle_thread;
      this_idle_thread->wakeup_event.clear(lock);
      this_idle_thread->wakeup_event.wait(lock);
    }
    else
    {
      return 0;
    }
  }

  return 0;
}

void task_io_service::stop_all_threads(
    mutex::scoped_lock& lock)
{
  stopped_ = true;

  while (first_idle_thread_)
  {
    idle_thread_info* idle_thread = first_idle_thread_;
    first_idle_thread_ = idle_thread->next;
    idle_thread->next = 0;
    idle_thread->wakeup_event.signal(lock);
  }

  if (!task_interrupted_ && task_)
  {
    task_interrupted_ = true;
    task_->interrupt();
  }
}

bool task_io_service::wake_one_idle_thread_and_unlock(
    mutex::scoped_lock& lock)
{
  if (first_idle_thread_)
  {
    idle_thread_info* idle_thread = first_idle_thread_;
    first_idle_thread_ = idle_thread->next;
    idle_thread->next = 0;
    idle_thread->wakeup_event.signal_and_unlock(lock);
    return true;
  }
  return false;
}

void task_io_service::wake_one_thread_and_unlock(
    mutex::scoped_lock& lock)
{
  if (!wake_one_idle_thread_and_unlock(lock))
  {
    if (!task_interrupted_ && task_)
    {
      task_interrupted_ = true;
      task_->interrupt();
    }
    lock.unlock();
  }
}

} // namespace detail
} // namespace asio

#include "asio/detail/pop_options.hpp"

#endif // !defined(ASIO_HAS_IOCP)

#endif // ASIO_DETAIL_IMPL_TASK_IO_SERVICE_IPP

ext: ipp


text:
#include <boost/python/module.hpp>

namespace smtbx { namespace refinement { namespace least_squares {
  namespace boost_python {

  void wrap_weighting_schemes();
  void wrap_least_squares();
  namespace {
    void init_module() {
      wrap_weighting_schemes();
      wrap_least_squares();
    }
  }
}}}}

BOOST_PYTHON_MODULE(smtbx_refinement_least_squares_ext)
{
  smtbx::refinement::least_squares::boost_python::init_module();
}


text:
#include <iostream>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>

namespace ublas = boost::numeric::ublas;

ublas::matrix<double> get_K(int N, double a0 = 2, double a1 = 2)
{
	ublas::identity_matrix<double> I(N, N);
	ublas::matrix<double> m1 = 2.0 * I;
	m1(0, 0) = a0;
	m1(N-1, N-1) = a1;

	ublas::symmetric_matrix<double, ublas::lower> m2(N, N);
	for (unsigned i = 0; i < m2.size1(); ++ i)
		for (unsigned j = 0; j <= i; ++ j)
			m2(i, j) = (j == i-1)? -1:0;
	return m1 + m2;
}

int main()
{
	int N = 3;
	double h = 1.0 / (N - 1);
	ublas::matrix<double> K = get_K(N);
	std::cout << K << std::endl;

	ublas::matrix<double> A = get_K(N, 1, 1);
	std::cout << A << std::endl;

	ublas::matrix<double> A1 = get_K(N, 2, 1);
	std::cout << A1 << std::endl;

	ublas::matrix<double> A2 = get_K(N, 1, 2);
	std::cout << A2 << std::endl;

	ublas::matrix<double> Kinv(N, N);
	Kinv.assign(ublas::identity_matrix<double> (K.size1()));
	ublas::permutation_matrix<size_t> pm(K.size1());
	ublas::lu_factorize(K, pm);
	ublas::lu_substitute(K, pm, Kinv);

	std::cout << Kinv << std::endl;

	double* tmp = (double*) Kinv.data().begin();
	int size = Kinv.data().size();

	for (int i = 0; i < size; ++i)
		std::cout << tmp[i] << std::endl;
	return 0;
}

max_stars_repo_name: yoon-gu/la-table

max_issues_repo_name: yoon-gu/la-table

max_forks_repo_name: yoon-gu/la-table


text:
#include "CorePch.h"
#include <rtp++/rfc3550/Rfc3550RtcpValidator.h>

#if 0
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#endif

namespace rtp_plus_plus
{
namespace rfc3550
{

#define EXIT_ON_TRUE(condition, log_message) if ((condition)){\
  LOG(WARNING) << log_message;return false;}

bool RtcpValidator::validateCompoundRtcpPacket(CompoundRtcpPacket compoundPacket, uint32_t uiTotalLength)
{
  EXIT_ON_TRUE(compoundPacket.empty(), "Empty compound RTCP packet");

  // check if is compound packet
  if (uiTotalLength != 0)
      EXIT_ON_TRUE((((uint32_t)compoundPacket[0]->getLength() + 1) << 2) == uiTotalLength, "No compound RTCP packet");

  // check versions
  for (size_t i = 0; i < compoundPacket.size(); ++i)
  {
    EXIT_ON_TRUE((compoundPacket[i]->getVersion() != RTP_VERSION_NUMBER), "Invalid version number");
  }

  // check if first packet is SR or RR
  EXIT_ON_TRUE((compoundPacket[0]->getPacketType() != PT_RTCP_SR) &&
    (compoundPacket[0]->getPacketType() != PT_RTCP_RR),
    "First packet is no SR/RR: " << (uint32_t)compoundPacket[0]->getPacketType());

  // check padding
  for (size_t i = 0; i < compoundPacket.size() - 1; ++i)
  {
    EXIT_ON_TRUE((compoundPacket[i]->getPadding()), "Padding before last RTCP packet");
  }

  // commenting out this check: it causes validation to fail when one or more RTCP packets
  // could not be parsed (e.g. due to unknown RTCP packet types)
  // This should not cause the validation to fail
#if 0
  if (uiTotalLength != 0)
  {
    // check total length: (add lengths + number of packets (for common header)) * 4 (measured in words)
#if 0
    // with boost lambda
    uint32_t uiSumLengths = ((std::accumulate(compoundPacket.begin(),
      compoundPacket.end(),
      0,
      boost::lambda::_1 + boost::lambda::bind(&RtcpPacketBase::getLength, *boost::lambda::_2))
      ) + compoundPacket.size()) * 4;
#endif
    uint32_t uiSumLengths = (std::accumulate(compoundPacket.begin(),
      compoundPacket.end(),
      compoundPacket.size(),
      [](int iLength, RtcpPacketBase::ptr pPacket){ return iLength + pPacket->getLength();}))*4;

      EXIT_ON_TRUE(uiSumLengths != uiTotalLength, "RTCP lengths don't match packet length: " << uiSumLengths << "!=" << uiTotalLength);
  }
#endif

  return true;
}

}
}


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 INCLUDED_SLIDESHOW_ANIMATIONFACTORY_HXX
#define INCLUDED_SLIDESHOW_ANIMATIONFACTORY_HXX

#include "numberanimation.hxx"
#include "enumanimation.hxx"
#include "coloranimation.hxx"
#include "stringanimation.hxx"
#include "boolanimation.hxx"
#include "pairanimation.hxx"

#include "shape.hxx"
#include "shapeattributelayer.hxx"
#include "shapemanager.hxx"

#include <boost/noncopyable.hpp>

namespace rtl
{
    class OUString;
}

/* Definition of AnimationFactory class */

namespace slideshow
{
    namespace internal
    {

        /** Factory for Animation objects

        	Given a SMIL XAnimate node, this factory generates the
        	appropriate Animation object from that, which will modify
        	the attribute as specified.
         */
        class AnimationFactory : private boost::noncopyable
        {
        public:
            /** Classifies the attribute name.

				This enum maps names to appropriate factory methods.
             */
            enum AttributeClass
            {
                /// Unknown, prolly invalid name
                CLASS_UNKNOWN_PROPERTY,
                /// Use createNumberPropertyAnimation
                CLASS_NUMBER_PROPERTY,
                /// Use createEnumPropertyAnimation
                CLASS_ENUM_PROPERTY,
                /// Use createColorPropertyAnimation
                CLASS_COLOR_PROPERTY,
                /// Use createStringPropertyAnimation
                CLASS_STRING_PROPERTY,
                /// Use createBoolPropertyAnimation
                CLASS_BOOL_PROPERTY
            };

            static AttributeClass classifyAttributeName( const ::rtl::OUString& rAttrName );

            /// Collection of flags common to all factory methods
            enum FactoryFlags
            {
                /** Don't call enter/leaveAnimation for the Shape.

					This is useful for set effects
                 */
                FLAG_NO_SPRITE = 1
            };

            static NumberAnimationSharedPtr createNumberPropertyAnimation( const ::rtl::OUString&				rAttrName,
                                                                           const AnimatableShapeSharedPtr&		rShape,
                                                                           const ShapeManagerSharedPtr&			rShapeManager,
                                                                           const ::basegfx::B2DVector&          rSlideSize,
                                                                           int									nFlags=0 );

            static EnumAnimationSharedPtr createEnumPropertyAnimation( const ::rtl::OUString&					rAttrName,
                                                                       const AnimatableShapeSharedPtr&			rShape,
                                                                       const ShapeManagerSharedPtr&				rShapeManager,
                                                                       const ::basegfx::B2DVector&              rSlideSize,
                                                                       int										nFlags=0 );

            static ColorAnimationSharedPtr 	createColorPropertyAnimation( const ::rtl::OUString&				rAttrName,
                                                                          const AnimatableShapeSharedPtr&		rShape,
                                                                          const ShapeManagerSharedPtr&			rShapeManager,
                                                                          const ::basegfx::B2DVector&           rSlideSize,
                                                                          int									nFlags=0 );

            /** Create scale or move animation

            	@param nTransformType
                Must be one of
                animations::AnimationTransformType::TRANSLATE or
                animations::AnimationTransformType::SCALE.
             */
            static PairAnimationSharedPtr 	createPairPropertyAnimation( const AnimatableShapeSharedPtr&		rShape,
                                                                         const ShapeManagerSharedPtr&			rShapeManager,
                                                                         const ::basegfx::B2DVector&            rSlideSize,
                                                                         sal_Int16								nTransformType,
                                                                         int									nFlags=0 );

            static StringAnimationSharedPtr createStringPropertyAnimation( const ::rtl::OUString&				rAttrName,
                                                                           const AnimatableShapeSharedPtr&		rShape,
                                                                           const ShapeManagerSharedPtr&			rShapeManager,
                                                                           const ::basegfx::B2DVector&          rSlideSize,
                                                                           int									nFlags=0 );

            static BoolAnimationSharedPtr 	createBoolPropertyAnimation( const ::rtl::OUString&					rAttrName,
                                                                         const AnimatableShapeSharedPtr&		rShape,
                                                                         const ShapeManagerSharedPtr&			rShapeManager,
                                                                         const ::basegfx::B2DVector&            rSlideSize,
                                                                         int									nFlags=0 );

            static NumberAnimationSharedPtr	createPathMotionAnimation( const ::rtl::OUString&					rSVGDPath,
																	   sal_Int16								nAdditive,
                                                                       const AnimatableShapeSharedPtr&			rShape,
                                                                       const ShapeManagerSharedPtr&				rShapeManager,
                                                                       const ::basegfx::B2DVector&              rSlideSize,
                                                                       int										nFlags=0);
        private:
            // default: constructor/destructor disabed
            AnimationFactory();
            ~AnimationFactory();
        };
    }
}

#endif /* INCLUDED_SLIDESHOW_ANIMATIONFACTORY_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/* Copyright (c) 2012-2013 University of Cape Town
 *
 * 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
 *
 * Miscellaneous utilities for command-line option processing, shared
 * between the test frontend and clogs-benchmark.
 */

#include "../src/clhpp11.h"
#include <boost/program_options.hpp>
#include <vector>
#include "options.h"

using namespace std;
namespace po = boost::program_options;

void addOptions(boost::program_options::options_description &opts)
{
    opts.add_options()
        ("cl-device",     po::value<string>(),        "OpenCL device name")
        ("cl-gpu",                                    "Only search GPU devices")
        ("cl-cpu",                                    "Only search CPU devices");
}

std::vector<cl::Device> findDevices(const boost::program_options::variables_map &vm)
{
    std::vector<cl::Device> ans;

    vector<cl::Platform> platforms;
    cl::Platform::get(&platforms);
    for (const cl::Platform &platform : platforms)
    {
        vector<cl::Device> devices;
        cl_device_type type = CL_DEVICE_TYPE_ALL;

        platform.getDevices(type, &devices);
        for (const cl::Device &d : devices)
        {
            bool good = true;
            /* Match name if given */
            if (vm.count("cl-device"))
            {
                if (d.getInfo<CL_DEVICE_NAME>() != vm["cl-device"].as<string>())
                    good = false;
            }
            /* Match type if given */
            if (vm.count("cl-gpu"))
            {
                if (!(d.getInfo<CL_DEVICE_TYPE>() & CL_DEVICE_TYPE_GPU))
                    good = false;
            }
            if (vm.count("cl-cpu"))
            {
                if (!(d.getInfo<CL_DEVICE_TYPE>() & CL_DEVICE_TYPE_CPU))
                    good = false;
            }
            /* Require device to be online */
            if (!d.getInfo<CL_DEVICE_AVAILABLE>())
                good = false;
            if (!d.getInfo<CL_DEVICE_COMPILER_AVAILABLE>())
                good = false;
            if (good)
                ans.push_back(d);
        }
    }
    return ans;
}

bool findDevice(const boost::program_options::variables_map &vm, cl::Device &device)
{
    std::vector<cl::Device> devices = findDevices(vm);
    if (!devices.empty())
    {
        device = devices[0];
        return true;
    }
    else
        return false;
}

cl::Context makeContext(const cl::Device &device)
{
    const cl::Platform &platform = device.getInfo<CL_DEVICE_PLATFORM>();
    cl_context_properties props[3] = {CL_CONTEXT_PLATFORM, (cl_context_properties) platform(), 0};
    return cl::Context(device.getInfo<CL_DEVICE_TYPE>(), props, NULL);
}

max_stars_repo_name: bmerry/clogs

max_issues_repo_name: bmerry/clogs

max_forks_repo_name: bmerry/clogs


text:
// Copyright 2021 Hans Dembinski
//
// Distributed under the Boost Software License, version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_HISTOGRAM_ACCUMULATORS_IS_THREAD_SAFE_HPP
#define BOOST_HISTOGRAM_ACCUMULATORS_IS_THREAD_SAFE_HPP

#include <boost/histogram/detail/priority.hpp>
#include <boost/histogram/fwd.hpp>
#include <type_traits>

namespace boost {
namespace histogram {
namespace detail {

template <class T>
constexpr bool is_thread_safe_impl(priority<0>) {
  return false;
}

template <class T>
constexpr auto is_thread_safe_impl(priority<1>) -> decltype(T::thread_safe()) {
  return T::thread_safe();
}

} // namespace detail

namespace accumulators {

template <class T>
struct is_thread_safe
    : std::integral_constant<bool,
                             detail::is_thread_safe_impl<T>(detail::priority<1>{})> {};

} // namespace accumulators
} // namespace histogram
} // namespace boost

#endif