text:
//============================================================================
// Name        : main.cpp
// Author      : kc
// Version     :
// Copyright   : Your copyright notice
// Description : POC TI Pipeline
//============================================================================

//#include <cuda.h>
#include <iostream>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/thread/thread.hpp>
#include "util/timeClock.h"
#include "util/threads.h"
#include <X11/Xlib.h>
#include <gtk/gtk.h>

static void spawnThreads(void);

int main(int argc, char **argv)
{
	std::cout << "Date compiled: " << __DATE__ << " - " << __TIME__  << std::endl;
	try
	{
		timeClock();
        //Deprecated, not necessary anymore
//		if( ! g_thread_supported() )
//			g_thread_init( NULL );

		/* Secure gtk */
		gdk_threads_init();
		XInitThreads();
		gtk_disable_setlocale();

		if (argc == 1)
			threads::useCamera = true;
		else
		{
			threads::useCamera = false;
			threads::framePath = argv[1];
		}
		spawnThreads();
		for(;;)
		{
			//System monitor
		}
	}
	catch (std::exception& e)
	{
		std::cout << "Caught exception:" << std::endl;
		std::cout << e.what() << std::endl;
		std::cout << "Exciting application" << std::endl;
	}
	catch (std::exception* e)
	{
		std::cout << "Caught exception:" << std::endl;
		std::cout << e->what() << std::endl;
	}
}

static void spawnThreads(void)
{
    //create message queues
    static boost::lockfree::spsc_queue<FromTiCameraThread> fromTiCameraToGui(queueDepth);
    static boost::lockfree::spsc_queue<ToTiCameraThread> fromGuiToTiCamera(queueDepth);
    static boost::lockfree::spsc_queue<FromTiDspThread> fromTiDspToGui(queueDepth);
    static boost::lockfree::spsc_queue<ToTiDspThread> fromGuiToTiDsp(queueDepth);
    static boost::lockfree::spsc_queue<FromGuiThread> fromGuiToGui(queueDepth);
    Queues qs {
        .fromTiCameraToGui = fromTiCameraToGui,
        .fromGuiToTiCamera = fromGuiToTiCamera,
        .fromTiDspToGui = fromTiDspToGui,
        .fromGuiToTiDsp = fromGuiToTiDsp,
        .fromGuiToGui = fromGuiToGui
    };

    //create threads objects
	static auto tiCamera = threads::create(Threads::Ti_Thread_CameraBuffer, qs);
    static auto tiDsp = threads::create(Threads::Ti_Thread_SignalProcessing, qs);
    static auto gui = threads::create(Threads::Gui_Thread, qs);

    //launch threads
#pragma clang diagnostic push
#pragma ide diagnostic ignored "IncompatibleTypes"
    boost::thread tiCameraThread {&threads::run, tiCamera};
    boost::thread tiDspThread {&threads::run, tiDsp};
    boost::thread guiThread {&threads::run, gui};
#pragma clang diagnostic pop
}

max_stars_repo_name: kabousvlieg/Nedi-image-upscaling

max_issues_repo_name: kabousvlieg/Nedi-image-upscaling

max_forks_repo_name: kabousvlieg/Nedi-image-upscaling


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * 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 <map>
#include <fstream>
#include <cstdio>
#include <stdexcept>

#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/filesystem.hpp>
#include <boost/shared_ptr.hpp>

#include "../../include/moost/io/file_backed_data_source.hpp"
#include "../../include/moost/testing/test_directory_creator.hpp"

using namespace moost::io;
using namespace std;

BOOST_AUTO_TEST_SUITE( file_backed_data_source_test )

namespace
{
   const int MIN_SECS = 100;
   const bool THROW_ON_FIRST = false;
   const double MIN_PROPORTION = 0.8;

   char const VALID_OPTIONS_XML[] = {
      "<FileBackedDataSource>\n"
      "  <Filepath>testpath</Filepath>\n"
      "  <MinSecsSinceLastLoad>100</MinSecsSinceLastLoad>\n"
      "  <ThrowOnFirstLoadFail>false</ThrowOnFirstLoadFail>\n"
      "  <MinProportionOfLastLoad>0.8</MinProportionOfLastLoad>\n"
      "</FileBackedDataSource>"
   };

   char const SOME_OPTIONS_XML[] = {
      "<FileBackedDataSource>\n"
      "  <Filepath>testpath</Filepath>\n"
      "  <MinSecsSinceLastLoad>100</MinSecsSinceLastLoad>\n"
      "  <ThrowOnFirstLoadFail>false</ThrowOnFirstLoadFail>\n"
      "</FileBackedDataSource>"
   };

   char const INVALID_OPTIONS_XML[] = {
      "<FileBackedDataSource>\n"
      "  <Filepath>testpath</Filepath>\n"
      "  <MinSecsSinceLastLoad>100</MinSecsSinceLastLoad>\n"
      "  <ThrowOnFirstLoadFail>zog</ThrowOnFirstLoadFail>\n"
      "  <MinProportionOfLastLoad>0.8</MinProportionOfLastLoad>\n"
      "</FileBackedDataSource>"
   };

   char const WRONG_OPTIONS_XML[] = {
      "<FileBackedDataSource>\n"
      "  <Filepath>testpath</Filepath>\n"
      "  <MinSecsSinceLastLoad>100</MinSecsSinceLastLoad>\n"
      "  <ThrowOnFirstLoadFail>false</ThrowOnFirstLoadFail>\n"
      "  <MinProportionOfLastLoad>0.8</MinProportionOfLastLoad>\n"
      "  <Zog>0.8</Zog>\n"
      "</FileBackedDataSource>"
   };
}

class IncrementingIntDataPolicy : public data_policy_base<int>
{
public:
   IncrementingIntDataPolicy(int iThrow = -1) : m_i(0), m_iThrow(iThrow) { }

   std::string getName() const
   {
      return "IncrementingIntData";
   }

   boost::shared_ptr<int> loadFromFile(const std::string& /*filepath*/) const
   {
      // doesn't actually read from file!
      if (m_i == m_iThrow)
      {
         ++m_i;
         throw runtime_error("this policy just threw");
      }
      boost::shared_ptr<int> pData(new int);
      *pData = m_i;
      ++m_i;
      return pData;
   }

   size_t size(boost::shared_ptr<int> /*pData*/) const
   {
      return m_i;
   }

private:
   mutable int m_i, m_iThrow;
};

struct Fixture
{
   typedef file_backed_data_source<IncrementingIntDataPolicy> int_source_t;

   Fixture() : m_tdc("MoostFileBackedDataSourceTestDirectory")
   {

   }

   virtual ~Fixture()
   {
   }

   void waitASecond() const
   {
      boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
   }

   void writeToFile(const std::string& filepath, const std::string& toWrite, bool wait) const
   {
      if (wait)  // wait briefly so we know that the write time of the file will change
         waitASecond();

      ofstream ofs(filepath.c_str());
      ofs << toWrite;
      ofs.close();

      // useful for debug to see the time that the file_watcher is seeing
      MLOG_DEFAULT_INFO(filepath << " updated at " << boost::filesystem::last_write_time(filepath) << endl);

      if (wait)  // give the source a chance to update
         waitASecond();
   }

   void testReloadFails(boost::shared_ptr<int_source_t> pSource, const std::string& filepath) const
   {
      writeToFile(filepath, "1", false);

      pSource->load();

      size_t currentSize = pSource->size();
      boost::shared_ptr<int> pData = pSource->get_shared_ptr();
      int currentData = *pData;

      writeToFile(filepath, "2", true);  // force a reload by updating the file

      BOOST_CHECK(pSource->size() == currentSize);

      boost::shared_ptr<int> pNewData = pSource->get_shared_ptr();
      BOOST_CHECK(*pNewData == currentData);
   }

   moost::testing::test_directory_creator m_tdc;
   file_backed_data_source_factory m_sourceFactory;
};

BOOST_FIXTURE_TEST_CASE( test_initial_load, Fixture )
{
   file_backed_data_source_config conf;
   IncrementingIntDataPolicy dataPolicy;
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);

   BOOST_CHECK(pSource->size() == 0);

   pSource->load();

   BOOST_CHECK(pSource->size() == 1);

   boost::shared_ptr<int> pData = pSource->get_shared_ptr();
   BOOST_CHECK(*pData == 0);
}

BOOST_FIXTURE_TEST_CASE( test_auto_reload, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_auto_reload"));
   writeToFile(filepath, "1", false);

   file_backed_data_source_config conf;
   conf.minSecsSinceLastLoad = 0;  // so we can force a reload straight away
   conf.filepath = filepath;
   IncrementingIntDataPolicy dataPolicy;
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);

   pSource->load();

   BOOST_CHECK(pSource->size() == 1);

   boost::shared_ptr<int> pData = pSource->get_shared_ptr();
   BOOST_CHECK(*pData == 0);

   writeToFile(filepath, "2", true);  // force a reload by updating the file

   BOOST_CHECK(pSource->size() == 2);

   boost::shared_ptr<int> pNewData = pSource->get_shared_ptr();
   BOOST_CHECK(*pNewData == 1);
   BOOST_CHECK(*pData == 0);  // old pointer to data remains unaffected
}

BOOST_FIXTURE_TEST_CASE( test_first_load_fail_throw, Fixture )
{
   file_backed_data_source_config conf;

   // configure policy to throw on first load
   IncrementingIntDataPolicy dataPolicy(0);
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);

   BOOST_CHECK_THROW(pSource->load(), std::runtime_error);
}

BOOST_FIXTURE_TEST_CASE( test_first_load_fail_log, Fixture )
{
   file_backed_data_source_config conf;
   conf.throwOnFirstLoadFail = false;

   // configure policy to throw on first load
   IncrementingIntDataPolicy dataPolicy(0);
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);

   BOOST_CHECK_NO_THROW(pSource->load());
}

BOOST_FIXTURE_TEST_CASE( test_reload_too_soon, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_reload_too_soon"));

   file_backed_data_source_config conf;
   conf.minSecsSinceLastLoad = 60;
   conf.filepath = filepath;
   IncrementingIntDataPolicy dataPolicy;
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);

   testReloadFails(pSource, filepath);
}

BOOST_FIXTURE_TEST_CASE( test_new_data_too_small, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_new_data_too_small"));

   file_backed_data_source_config conf;
   conf.minProportionOfLastLoad = 2;  // usually this would be less than 1 of course
   conf.filepath = filepath;
   IncrementingIntDataPolicy dataPolicy;
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);

   testReloadFails(pSource, filepath);
}

BOOST_FIXTURE_TEST_CASE( test_load_throws, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_load_throws"));

   file_backed_data_source_config conf;

   // configure policy to throw on second load
   IncrementingIntDataPolicy dataPolicy(1);
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);

   testReloadFails(pSource, filepath);
}

BOOST_FIXTURE_TEST_CASE( test_register, Fixture )
{
   file_backed_data_source_config conf;
   IncrementingIntDataPolicy dataPolicy;
   boost::shared_ptr<int_source_t> pSource = m_sourceFactory.createFromConfig(dataPolicy, conf);
   boost::shared_ptr<int_source_t> pOther = m_sourceFactory.createFromConfig(dataPolicy, conf);

   pSource->registerLoadable(pOther);
   pSource->load();

   BOOST_CHECK(pOther->size() == 1);

   boost::shared_ptr<int> pData = pOther->get_shared_ptr();
   BOOST_CHECK(*pData == 0);
}

BOOST_FIXTURE_TEST_CASE( test_valid_options_from_xml, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_options_from_xml"));

   std::string xml(VALID_OPTIONS_XML);
   std::ofstream ofs(filepath.c_str());
   ofs << xml;
   ofs.close();

   file_backed_data_source_config_factory factory;
   file_backed_data_source_config conf = factory.createFromXml(filepath);

   BOOST_CHECK(conf.minSecsSinceLastLoad == MIN_SECS);
   BOOST_CHECK(conf.throwOnFirstLoadFail == THROW_ON_FIRST);
   BOOST_CHECK(conf.minProportionOfLastLoad == MIN_PROPORTION);
}

BOOST_FIXTURE_TEST_CASE( test_some_valid_options_from_xml, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_some_valid_options_from_xml"));

   std::string xml(SOME_OPTIONS_XML);
   std::ofstream ofs(filepath.c_str());
   ofs << xml;
   ofs.close();

   file_backed_data_source_config_factory factory;
   file_backed_data_source_config conf = factory.createFromXml(filepath);

   BOOST_CHECK(conf.minSecsSinceLastLoad == MIN_SECS);
   BOOST_CHECK(conf.throwOnFirstLoadFail == THROW_ON_FIRST);
}

BOOST_FIXTURE_TEST_CASE( test_invalid_options_from_xml, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_invalid_options_from_xml"));

   std::string xml(INVALID_OPTIONS_XML);
   std::ofstream ofs(filepath.c_str());
   ofs << xml;
   ofs.close();

   file_backed_data_source_config_factory factory;
   BOOST_CHECK_THROW(factory.createFromXml(filepath), std::runtime_error);
}

BOOST_FIXTURE_TEST_CASE( test_wrong_options_from_xml, Fixture )
{
   string filepath(m_tdc.GetFilePath("test_wrong_options_from_xml"));

   std::string xml(WRONG_OPTIONS_XML);
   std::ofstream ofs(filepath.c_str());
   ofs << xml;
   ofs.close();

   file_backed_data_source_config_factory factory;
   BOOST_CHECK_THROW(factory.createFromXml(filepath), std::runtime_error);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: lastfm/libmoost

max_issues_repo_name: lastfm/libmoost

max_forks_repo_name: lastfm/libmoost


text:
//****************************************************************************
// (c) 2008, 2009 by the openOR Team
//****************************************************************************
// The contents of this file are available under the GPL v2.0 license
// or under the openOR commercial license. see
//   /Doc/openOR_free_license.txt or
//   /Doc/openOR_comercial_license.txt
// for Details.
//****************************************************************************
//#include <iostream>
#include <cstdio>

#include "../include/openOR/Log/Logger.hpp"

#include <boost/function_equal.hpp>

OPENOR_SINGLETON_INIT(openOR::Log::Logger)

namespace openOR {
   namespace Log {

      //! \brief Log level tags
      namespace Level {
         const char* Everything::Severity() { return ""; }
         const char* Debug::Severity() { return "Debug"; }
         const char* Info::Severity() { return "Info"; }
         const char* Warning::Severity() { return "Warning"; }
         const char* Error::Severity() { return "Error"; }
         const char* Fatal::Severity() { return "Fatal"; }
      }

      Attributes::create::create() : m_pAttributeMap(std::tr1::shared_ptr<AttributeMap> ()) {}
      Attributes::create& Attributes::create::operator()(const std::string& name, boost::any value) {

         if (!m_pAttributeMap) {
            m_pAttributeMap = std::tr1::shared_ptr<AttributeMap>(new AttributeMap);
         }

         (*m_pAttributeMap)[name] = value;
         return *this;
      }

      Attributes::Attributes() :
            m_pAttributeMap(std::tr1::shared_ptr<AttributeMap> ()),
            m_noValue()
      {}
      Attributes::Attributes(const create& paramSet) :
            m_pAttributeMap(paramSet.m_pAttributeMap),
            m_noValue()
      {}

      const boost::any& Attributes::get(const std::string& key) const {

         if (!m_pAttributeMap) { return m_noValue; }

         AttributeMap::const_iterator attr = m_pAttributeMap->find(key);
         if (attr != m_pAttributeMap->end()) {
            return (attr->second);
         }

         return m_noValue;
      }

      Attributes noAttribs = Attributes();

      Logger::Logger() :
         m_filters(),
         m_log(stderr),
         m_showModuleName(true)
      {}

      Logger::~Logger() {
         fflush(m_log);
         if (!(m_log == NULL || m_log == stdout || m_log == stderr)) {
            fclose(m_log);
         }
      }

      void Logger::add_filter(Filter_type filter) {
         m_filters.push_back(filter);
      }

      void Logger::remove_filter(Filter_type filter) {
         // TODO: can we have a sensible remove filter with this interface?
         //m_filters.erase( std::find(m_filters.begin(), m_filters.end(), filter) );
      }

      void Logger::outputModuleName(bool doOutput /*= true*/) {
         m_showModuleName = doOutput;
      }

      void Logger::set_log_file(const std::string& fileName) {

         fflush(m_log);
         if (!(m_log == NULL || m_log == stdout || m_log == stderr)) {
            fclose(m_log);
         }

         if (fileName.empty() || fileName == "stderr") {
            m_log = stderr;
         } else if (fileName == "stdout") {
            m_log = stdout;
         } else {
            m_log = fopen(fileName.c_str(), "wt");
            if (m_log == NULL) {
               m_log = stderr;
            }
         }
      }

      bool Logger::is_enabled(const Attributes& attr, size_t severityId) const {

         // all messages are logged by default.
         if (m_filters.empty()) {
            return true;
         }

         // if one filter matches the log message gets filtered out
         bool enabled = true;
         for (Filters::const_iterator it = m_filters.begin(), end = m_filters.end();
               it != end; ++it) {
            enabled &= !((*it)(attr, severityId));
         }
         return enabled;
      }

      void Logger::log_msg(const char severity[], const Attributes& attr, const char file[], int line, std::string msg) {

         #ifndef OPENOR_DISABLE_ALL_LOGGING
         if (m_showModuleName) {
            std::string moduleName = "Unknown Module";
            try {
               moduleName = boost::any_cast<std::string>(attr.get("Module"));
            } catch (...) {
               // ignore: its not fatal that we couldn't determine the modules name
            }
            fprintf(m_log, "[%s][%s]: %s\n", severity, moduleName.c_str(), msg.c_str());
         } else {
            fprintf(m_log, "[%s]: %s\n", severity, msg.c_str());
         }

         #ifndef NDEBUG
            fflush(m_log);
         #endif
         #endif
      }
   }
}

max_stars_repo_name: avinfinity/UnmanagedCodeSnippets

max_issues_repo_name: avinfinity/UnmanagedCodeSnippets

max_forks_repo_name: avinfinity/UnmanagedCodeSnippets


text:
//Copyright (c) 2006-2008 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)

#ifndef UUID_0C5D492E909711DCB658AD4556D89593
#define UUID_0C5D492E909711DCB658AD4556D89593

#include <boost/exception/exception.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/config.hpp>
#include <stddef.h>

namespace
boost
    {
    namespace
    exception_detail
        {
        template <class T>
        struct
        error_info_injector:
            public T,
            public exception
            {
            explicit
            error_info_injector( T const & x ):
                T(x)
                {
                }

            ~error_info_injector() throw()
                {
                }

            char const *
            diagnostic_information() const throw()
                {
                return boost::exception::_diagnostic_information(T::what());
                }
            };

        struct large_size { char c[256]; };
        large_size dispatch( exception * );

        struct small_size { };
        small_size dispatch( void * );

        template <class,size_t>
        struct enable_error_info_helper;

        template <class T>
        struct
        enable_error_info_helper<T,sizeof(large_size)>
            {
            typedef T type;
            };

        template <class T>
        struct
        enable_error_info_helper<T,sizeof(small_size)>
            {
            typedef error_info_injector<T> type;
            };

#if BOOST_WORKAROUND(__BORLANDC__,BOOST_TESTED_AT(0x582))
        template <class T>
        struct
        sizeof_dispatch
            {
            BOOST_STATIC_CONSTANT(int, value = sizeof(dispatch((T*)0)) );
            };

        template <class T>
        struct
        enable_error_info_return_type
            {
            typedef typename enable_error_info_helper<T,sizeof_dispatch<T>::value>::type type;
            };
#else
        template <class T>
        struct
        enable_error_info_return_type
            {
            typedef typename enable_error_info_helper<T,sizeof(dispatch((T*)0))>::type type;
            };
#endif
        }

    template <class T>
    inline
#if !BOOST_WORKAROUND(__BORLANDC__,BOOST_TESTED_AT(0x582))
    typename
#endif
    exception_detail::enable_error_info_return_type<T>::type
    enable_error_info( T const & x )
        {
        return
#if !BOOST_WORKAROUND(__BORLANDC__,BOOST_TESTED_AT(0x582))
        typename
#endif
        exception_detail::enable_error_info_return_type<T>::type(x);
        }
    }

#endif

ext: hpp


text:
//---------------------------------------------------------------------------//
//!
//! \file   Utility_EvaporationDistribution.hpp
//! \author Aaron Tumulak
//! \brief  Evaporation distribution class declaration. Modified by Alex
//!         Robinson to accommodate units.
//!
//---------------------------------------------------------------------------//

#ifndef UTILITY_EVAPORATION_DISTRIBUTION_HPP
#define UTILITY_EVAPORATION_DISTRIBUTION_HPP

// Std Lib Includes
#include <limits>

// Boost Includes
#include <boost/units/physical_dimensions/energy.hpp>

// FRENSIE Includes
#include "Utility_UnivariateDistribution.hpp"

namespace Utility{

/*! The unit-aware evaporation distribution class
 * \ingroup univariate_distributions
 */
template<typename IndependentUnit, typename DependentUnit>
class UnitAwareEvaporationDistribution : public UnitAwareUnivariateDistribution<IndependentUnit,DependentUnit>
{
  // Only allow construction when the independent unit corresponds to energy
  RESTRICT_UNIT_TO_BOOST_DIMENSION( IndependentUnit, energy_dimension );

  // Typedef for base type
  typedef UnitAwareUnivariateDistribution<IndependentUnit,DependentUnit> BaseType;

  // The distribution multiplier unit traits typedef
  typedef UnitTraits<typename UnitTraits<DependentUnit>::template GetMultipliedUnitType<typename UnitTraits<IndependentUnit>::InverseUnit>::type> DistMultiplierUnitTraits;

  // The distribution multiplier quantity type
  typedef typename DistMultiplierUnitTraits::template GetQuantityType<double>::type DistMultiplierQuantity;

  // The distribution normalization quantity type
  typedef typename BaseType::DistNormQuantity DistNormQuantity;

  // Typedef for QuantityTraits<double>
  typedef QuantityTraits<double> QT;

  // Typedef for QuantityTraits<IndepQuantity>
  typedef QuantityTraits<typename BaseType::IndepQuantity> IQT;

  // Typedef for QuantityTraits<InverseIndepQuantity>
  typedef QuantityTraits<typename BaseType::InverseIndepQuantity> IIQT;

  // Typedef for QuantityTraits<DepQuantity>
  typedef QuantityTraits<typename BaseType::DepQuantity> DQT;

  // Typedef for QuantityTraits<DistMultiplierQuantity>
  typedef QuantityTraits<DistMultiplierQuantity> DMQT;

public:

  //! This distribution type
  typedef UnitAwareEvaporationDistribution<IndependentUnit,DependentUnit> ThisType;

  //! The independent quantity type
  typedef typename BaseType::IndepQuantity IndepQuantity;

  //! The inverse independent quantity type
  typedef typename BaseType::InverseIndepQuantity InverseIndepQuantity;

  //! The dependent quantity type
  typedef typename BaseType::DepQuantity DepQuantity;

  //! Constructor
  template<typename InputIndepQuantityA = IndepQuantity,
	   typename InputIndepQuantityB = IndepQuantity,
	   typename InputIndepQuantityC = IndepQuantity>
  UnitAwareEvaporationDistribution(
                 const InputIndepQuantityA incident_energy =
                 ThisType::getDefaultIncidentEnergy<InputIndepQuantityA>(),
                 const InputIndepQuantityB nuclear_temperature =
                 ThisType::getDefaultNuclearTemperature<InputIndepQuantityB>(),
                 const InputIndepQuantityC restriction_energy =
                 ThisType::getDefaultRestrictionEnergy<InputIndepQuantityC>(),
                 const double constant_multiplier =
                 ThisType::getDefaultConstantMultiplier() );

  //! Copy constructor
  template<typename InputIndepUnit, typename InputDepUnit>
  UnitAwareEvaporationDistribution( const UnitAwareEvaporationDistribution<InputIndepUnit,InputDepUnit>& dist_instance );

  //! Construct distribution from a unitless dist. (potentially dangerous)
  static UnitAwareEvaporationDistribution fromUnitlessDistribution( const UnitAwareEvaporationDistribution<void,void>& unitless_distribution );

  //! Assignment operator
  UnitAwareEvaporationDistribution& operator=( const UnitAwareEvaporationDistribution& dist_instance );

  //! Destructor
  ~UnitAwareEvaporationDistribution()
  { /* ... */ }

  //! Evaluate the distribution
  DepQuantity evaluate( const IndepQuantity indep_var_value ) const override;

  //! Evaluate the PDF
  InverseIndepQuantity evaluatePDF( const IndepQuantity indep_var_value ) const override;

  //! Return a sample from the distribution
  IndepQuantity sample() const override;

  //! Return a sample from the distribution
  static IndepQuantity sample( const IndepQuantity incident_energy,
			       const IndepQuantity nuclear_temperature,
			       const IndepQuantity restriction_energy );

  //! Return a random sample from the distribution, and record the number of trials
  IndepQuantity sampleAndRecordTrials( DistributionTraits::Counter& trials ) const override;

  //! Return a random sample from the corresponding CDF and record the number of trials
  static IndepQuantity sampleAndRecordTrials(
                                       const IndepQuantity incident_energy,
                                       const IndepQuantity nuclear_temperature,
                                       const IndepQuantity restriction_energy,
                                       DistributionTraits::Counter& trials );

  //! Return the upper bound of the distribution independent variable
  IndepQuantity getUpperBoundOfIndepVar() const override;

  //! Return the lower bound of the distribution independent variable
  IndepQuantity getLowerBoundOfIndepVar() const override;

  //! Return the distribution type
  UnivariateDistributionType getDistributionType() const override;

  //! Test if the distribution is continuous
  bool isContinuous() const override;

  //! Method for placing the object in an output stream
  void toStream( std::ostream& os ) const override;

  //! Equality comparison operator
  bool operator==( const UnitAwareEvaporationDistribution& other ) const;

  //! Inequality comparison operator
  bool operator!=( const UnitAwareEvaporationDistribution& other ) const;

protected:

  //! Copy constructor (copying from unitless distribution only)
  UnitAwareEvaporationDistribution( const UnitAwareEvaporationDistribution<void,void>& unitless_dist_instance, int );

  //! Test if the dependent variable can be zero within the indep bounds
  bool canDepVarBeZeroInIndepBounds() const override;

  //! Get the default incident energy
  template<typename InputIndepQuantity>
  static InputIndepQuantity getDefaultIncidentEnergy()
  { return QuantityTraits<InputIndepQuantity>::one(); }

  //! Get the default nuclear temperature
  template<typename InputIndepQuantity>
  static InputIndepQuantity getDefaultNuclearTemperature()
  { return QuantityTraits<InputIndepQuantity>::one(); }

  //! Get the default restriction energy
  template<typename InputIndepQuantity>
  static InputIndepQuantity getDefaultRestrictionEnergy()
  { return QuantityTraits<InputIndepQuantity>::zero(); }

  //! Get the default constant multiplier
  static double getDefaultConstantMultiplier()
  { return 1.0; }

private:

  // Calculate the normalization constant of the distribution
  void calculateNormalizationConstant();

  // Verify that the shape parameters are valid
  template<typename InputIndepQuantity, typename InputDistMultQuantity>
  static void verifyValidShapeParameters( InputIndepQuantity& incident_energy,
                                          InputIndepQuantity& nuclear_temp,
                                          InputIndepQuantity& restriction_energy,
                                          InputDistMultQuantity& multiplier );

  // Save the distribution to an archive
  template<typename Archive>
  void save( Archive& ar, const unsigned version ) const;

  // Load the distribution from an archive
  template<typename Archive>
  void load( Archive& ar, const unsigned version );

  BOOST_SERIALIZATION_SPLIT_MEMBER();

  // Declare the boost serialization access object as a friend
  friend class boost::serialization::access;

  // All possible instantiations are friends
  template<typename FriendIndepUnit, typename FriendDepUnit>
  friend class UnitAwareEvaporationDistribution;

  // The distribution type
  static const UnivariateDistributionType distribution_type = EVAPORATION_DISTRIBUTION;

  // The incident neutron energy of the distribution
  IndepQuantity d_incident_energy;

  // The nuclear temperature of the distribution
  IndepQuantity d_nuclear_temperature;

  // The restriction energy of the distribution
  IndepQuantity d_restriction_energy;

  // The distribution multiplier
  DistMultiplierQuantity d_multiplier;

  // The distribution normalization constant
  DistNormQuantity d_norm_constant;
};

/*! The evaporation distribution (unit-agnostic)
 * \ingroup univariate_distributions
 */
typedef UnitAwareEvaporationDistribution<void,void> EvaporationDistribution;

} // end Utility namespace

BOOST_SERIALIZATION_DISTRIBUTION2_VERSION( UnitAwareEvaporationDistribution, 0 );
BOOST_SERIALIZATION_DISTRIBUTION2_EXPORT_STANDARD_KEY( EvaporationDistribution );

//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//

#include "Utility_EvaporationDistribution_def.hpp"

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

#endif // end UTILITY_EVAPORATION_DISTRIBUTION_HPP

//---------------------------------------------------------------------------//
// end Utility_EvaporationDistribution.hpp
//---------------------------------------------------------------------------//


text:
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2012 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_FEATURE_COLLECTION_PARSER_HPP
#define MAPNIK_FEATURE_COLLECTION_PARSER_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/noncopyable.hpp>
#include <mapnik/unicode.hpp>

// boost
#include <boost/scoped_ptr.hpp>

// stl
#include <vector>

namespace mapnik { namespace json {

template <typename Iterator, typename FeatureType> struct feature_collection_grammar;

template <typename Iterator>
class MAPNIK_DECL feature_collection_parser : private mapnik::noncopyable
{
    typedef Iterator iterator_type;
    typedef mapnik::feature_impl feature_type;
public:
    feature_collection_parser(mapnik::context_ptr const& ctx, mapnik::transcoder const& tr);
    ~feature_collection_parser();
    bool parse(iterator_type first, iterator_type last, std::vector<mapnik::feature_ptr> & features);
private:
    boost::scoped_ptr<feature_collection_grammar<iterator_type,feature_type> > grammar_;
};

}}

#endif //MAPNIK_FEATURE_COLLECTION_PARSER_HPP

max_stars_repo_name: Wujingli/OpenWebGlobeDataProcessing

max_issues_repo_name: Wujingli/OpenWebGlobeDataProcessing

max_forks_repo_name: Wujingli/OpenWebGlobeDataProcessing


text:
#ifndef CLIENT_CONNECTION_HPP__
#define CLIENT_CONNECTION_HPP__

#include <memory>
#include <string_view>
#include <cstdint>
#include <cstddef>
#include <functional>

#include "DoubleBuffer.hpp"
#include "Message.hpp"
#include "Log.hpp"
#include "Client.hpp"

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>

/** TODO: implement these functions for Stream
 * - [ ] close
 * - [ ] shutdown
 * - [ ] async_connect
 * - [ ] remote_endpoint
 * - [ ] constructor
 * - [x] async_write_some
 * - [x] async_read_some
*/

namespace client {

// TODO: add constrains for Stream type
template<class Stream>
class Connection
    : public std::enable_shared_from_this<Connection<Stream>> {
public:

    Connection(std::weak_ptr<Client> client
        , std::shared_ptr<boost::asio::io_context> context
        , std::shared_ptr<boost::asio::ssl::context> sslContext
    );

    /**
     * Close connection if it's haven't been terminated yet.
     */
    ~Connection();

    /**
     * Trying to connect to the remote host
     *
     * @param path
     *  It's ip address of the remote host
     * @param port
     *  It's a port on which a remote host is listening
     */
    void Connect(std::string_view path, std::string_view port);

    void Write(std::string text);

    void Close();

private:

    void Handshake();

    void OnConnect(
        const boost::system::error_code& err,
        const boost::asio::ip::tcp::endpoint& endpoint
    );

    void Read();

    /**
     * Completion handler.
     * Called when the client read something from the remote endpoint
     */
    void OnRead(
        const boost::system::error_code& error,
        size_t transferredBytes
    );

    /**
     * Send everything from the passive buffers to remote peer.
     * It is called from the function wrapped in strand to prevent concurrent
     * access to outgoing buffer and other variables.
     */
    void Write();

    /**
     * Completion handler; called when the client write something to the remote endpoint
     */
    void OnWrite(
        const boost::system::error_code& error,
        size_t transferredBytes
    );

private:
    Log m_logger { "client_log.txt" };

    std::weak_ptr<Client> m_client;
    std::shared_ptr<boost::asio::io_context> m_io;
    std::shared_ptr<boost::asio::ssl::context> m_sslContext;

    boost::asio::io_context::strand m_strand;
    boost::asio::ssl::stream<Stream> m_stream;

    bool m_isWriting { false };
    boost::asio::streambuf m_inbox;
    Buffers m_outbox;
};

template<class Stream>
Connection<Stream>::Connection(std::weak_ptr<Client> client
    , std::shared_ptr<boost::asio::io_context> context
    , std::shared_ptr<boost::asio::ssl::context> sslContext
)
    : m_client { client }
    , m_io { context }
    , m_sslContext { sslContext }
    , m_strand { *context }
    , m_stream { *context, *sslContext }
{
}

template<class Stream>
Connection<Stream>::~Connection() {
    m_logger.Write(LogType::info, "Connection closed through destructor\n");
}

template<class Stream>
void Connection<Stream>::Connect(std::string_view path, std::string_view port) {
    using std::placeholders::_1;
    using std::placeholders::_2;

    m_stream.set_verify_mode(boost::asio::ssl::verify_peer
        | boost::asio::ssl::verify_fail_if_no_peer_cert
    );
    // m_stream.set_verify_callback(std::bind(&Connection::VerifyCertificate, this->shared_from_this(), _1, _2));
    m_stream.set_verify_callback([weak = this->weak_from_this()](
        bool preverified
        , boost::asio::ssl::verify_context& ctx)
    {
        // In this example we will simply print the certificate's subject name.
        char name[256];
        X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
        X509_NAME_oneline(X509_get_subject_name(cert), name, 256);

        if (auto shared = weak.lock(); shared) {
            shared->m_logger.Write(LogType::info, "Verifying", name, "\n");
        }

        return preverified;
    });

    asio::ip::tcp::resolver resolver(*m_io);
    const auto endpoints = resolver.resolve(path, port);
    if (endpoints.empty()) {
        this->Close();
    }
    else {
        boost::asio::async_connect(
            m_stream.lowest_layer(),
            endpoints,
            std::bind(&Connection::OnConnect, this->shared_from_this(), _1, _2)
        );
    }
}

template<class Stream>
void Connection<Stream>::Handshake() {
    m_stream.async_handshake(boost::asio::ssl::stream_base::client,
        [self = this->shared_from_this()] (const boost::system::error_code& error) {
            if (!error) {
                if(auto model = self->m_client.lock(); model) {
                    // update state
                    model->SetState(Client::State::RECEIVE_ACK);
                }
                // start waiting incoming calls
                self->Read();
            }
            else {
                self->m_logger.Write(LogType::error, "Handshake failed:", error.message(), "\n");
            }
        }
    );
}

template<class Stream>
void Connection<Stream>::OnConnect(
    const boost::system::error_code& error,
    const boost::asio::ip::tcp::endpoint& endpoint
) {
    if (error) {
        m_logger.Write(LogType::error,
            "Connection failed to connect with error: ", error.message(), "\n"
        );
    }
    else {
        m_logger.Write(LogType::info, "Connection connected successfully!\n");
        if(auto model = m_client.lock(); model) {
            // update state
            model->SetState(Client::State::WAIT_ACK);
        }
        this->Handshake();
    }
}

template<class Stream>
void Connection<Stream>::Close() {
    boost::asio::post(m_strand, [self = this->shared_from_this()]() {
        boost::system::error_code error;
        self->m_stream.lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, error);
        if (error) {
            self->m_logger.Write(LogType::error,
                "Connection's socket called shutdown with error: ", error.message(), '\n'
            );
            error.clear();
        }

        self->m_stream.lowest_layer().close(error);
        if (error) {
            self->m_logger.Write(LogType::error,
                "Connection's socket is being closed with error: ", error.message(), '\n'
            );
        }
        self->m_isWriting = false;

        if(auto model = self->m_client.lock(); model) {
            model->SetState(Client::State::CLOSED);
        }
    });
}

template<class Stream>
void Connection<Stream>::Read() {
    boost::asio::async_read_until(
        m_stream,
        m_inbox,
        Internal::MESSAGE_DELIMITER,
        boost::asio::bind_executor(
            m_strand,
            std::bind(&Connection::OnRead,
                this->shared_from_this(),
                std::placeholders::_1,
                std::placeholders::_2
            )
        )
    );
}

template<class Stream>
void Connection<Stream>::Write() {
    m_isWriting = true;
    m_outbox.SwapBuffers();
    boost::asio::async_write(
        m_stream,
        m_outbox.GetBufferSequence(),
        boost::asio::bind_executor(
            m_strand,
            std::bind(&Connection::OnWrite,
                this->shared_from_this(),
                std::placeholders::_1,
                std::placeholders::_2
            )
        )
    );
}

template<class Stream>
void Connection<Stream>::Write(std::string text) {
    // using strand we prevent concurrent access to variables and
    // concurrent writing to socket.
    boost::asio::post(m_strand, [text = std::move(text), self = this->shared_from_this()]() mutable {
        self->m_outbox.Enque(std::move(text));
        if (!self->m_isWriting) {
            self->Write();
        }
    });
}

template<class Stream>
void Connection<Stream>::OnRead(
    const boost::system::error_code& error,
    size_t transferredBytes
) {
    if (!error) {
        m_logger.Write(LogType::info, "Connection just recive:", transferredBytes, "bytes.\n");

        const auto data { m_inbox.data() }; // asio::streambuf::const_buffers_type
        std::string received {
            asio::buffers_begin(data),
            asio::buffers_begin(data) + transferredBytes - Internal::MESSAGE_DELIMITER.size()
        };
        m_inbox.consume(transferredBytes);

        Internal::Response incomingResponse;
        incomingResponse.Read(received);

        boost::system::error_code error;
        m_logger.Write(LogType::info, m_stream.lowest_layer().remote_endpoint(error), ':', received, '\n');

        if(auto model = m_client.lock(); model) {
            /* if it's ACK, we resolve the State in synchronous way, otherwise resolve asyncronously */
            model->HandleMessage(std::move(incomingResponse));
        }
        this->Read();
    }
    else {
        m_logger.Write(LogType::error, "Connection failed to read with error:", error.message(), "\n");
        this->Close();
    }
}

template<class Stream>
void Connection<Stream>::OnWrite(
    const boost::system::error_code& error,
    size_t transferredBytes
) {
    if (!error) {
        m_logger.Write(LogType::info, "Connection just sent:", transferredBytes, "bytes\n");
        if (m_outbox.GetQueueSize()) {
            // we need to send other data
            this->Write();
        }
        else {
            m_isWriting = false;
        }
    }
    else {
        m_isWriting = false;
        m_logger.Write(LogType::error, "Connection has error on writting:", error.message(), '\n');
        this->Close();
    }
}

} // namespace client

#endif // CLIENT_CONNECTION_HPP__

max_stars_repo_name: Roout/char

max_issues_repo_name: Roout/char

max_forks_repo_name: Roout/char


text:
#include <iostream>
#include <stdexcept>
#include <Eigen/Dense>
#include <Eigen/SparseCore>
#include "mex.h"
#include "ais.h"

#ifdef MX_API_VER
#if MX_API_VER < 0x07030000
typedef int mwIndex;
#endif
#endif

using namespace Eigen;
using namespace std;

void exit_with_help()
{
	mexPrintf(
	"Usage: [kpX] = kron_perm(X, block_size)\n"
	"       [kpX] = kron_perm(X, block_size, row_perm, col_perm)\n"
	"     X is an m-by-n sparse/dense double matrix\n"
	"     block_size is a length-2 array [block_m block_n] for the size of the last block\n"
	"     row_perm is an dense row permutation array\n"
	"     col_perm is an dense column permutation array\n"
	"     kpX is an M-by-N sparse double matrix\n"
	"        M = ceil(m/block_m)*ceil(n/block_n)\n"
	"        N = block_m*block_n\n"
	"Note: \n"
	"     kpX == kron_perm(X(row_perm, col_perm), block_size)\n"
	);
}

static void fake_answer(mxArray *plhs[]) { plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL); }

/***** MATLAB 2 EIGEN conversion *****/
double matlabScalar2scalar( const mxArray* mp ) {
    double scalar = mxGetScalar(mp);
    return scalar;
}

VectorXd matlabVec2eigenVec( const mxArray* mp ) {
    // Load with a certain size
    const mwSize* size = mxGetDimensions( mp );
    mwSize length;
    if(size[0] > 1) { length = size[0]; } else { length = size[1]; }
    VectorXd x(length);

    // Extract data
    double* data = mxGetPr( mp );
    for(size_t i = 0; i < length; i++) {
        x(i) = data[i];
    }

    return x;
}

mxArray* eigenVec2matlabVec( const VectorXd& x ) {
    mxArray* mp = mxCreateDoubleMatrix( x.size(), 1, mxREAL );
    double* data = mxGetPr( mp );
    // Copy data from vector
    for(size_t i = 0; i < x.size(); ++i) {
        data[i] = x(i);
    }
    return mp;
}

MatrixXd matlabMat2eigenMat( const mxArray* mp ) {
    // Load with a certain size
    const mwSize* size = mxGetDimensions( mp );
    MatrixXd A(size[0],size[1]);

    // Extract data
    double* data = mxGetPr( mp );
    size_t idx = 0;
    for(int j = 0; j < size[1]; j++) {
        for(int i = 0; i < size[0]; i++) {
            A(i,j) = data[ idx++ ];
        }
    }

    return A;
}

SparseMatrix<double> matlabSparse2eigenSparse( const mxArray* mp ) {
    const mwSize* size = mxGetDimensions( mp );
    mwSize nnz = mxGetNzmax( mp );

    // Setup triplets
    vector< Triplet< double > > triplets;
    triplets.reserve( nnz );

    // Extract nonzeros
    size_t *ir = mxGetIr( mp ); /* Row indexing */
    size_t *jc = mxGetJc( mp ); /* Column count */
    double *s = mxGetPr( mp ); /* Non-zero elements */
    for (int ci=0; ci < size[1]; ci++) { /* Loop through columns */
        for (int k = jc[ci]; k < jc[ci+1]; k++) { /* Loop through non-zeros in ith column */
            int ri = ir[k];
            double val = s[k];
            triplets.push_back( Triplet<double>( ri, ci, val ) );
        }
    }

    // Create matrix
    SparseMatrix<double> A(size[0],size[1]);
    A.setFromTriplets( triplets.begin(), triplets.end() );
    //cout << "Loaded sparse matrix:" << endl << A << endl;
    return A;
}

mxArray* eigenSparse2matlabSparse( SparseMatrix<double> A ) {
    mxArray* mp = mxCreateSparse( (mwSize)A.rows(), (mwSize)A.cols(), (mwSize)A.nonZeros(), mxREAL );
    double* sr = mxGetPr( mp );
    mwSize* irs = mxGetIr( mp );
    mwSize* jcs = mxGetJc( mp );

    // Loop through non-zeros
    size_t k = 0;
    for (size_t j = 0; j < A.outerSize(); ++j) {
        mwSize i;
        jcs[j] = k;
        for (SparseMatrix<double>::InnerIterator it(A,j); it; ++it) {
            sr[k] = it.value();
            irs[k] = it.row();
            k++;
        }
    }
    jcs[ A.cols() ] = k;

    return mp;
}

/***** Argument load functions *****/
VectorXd getVector( const mxArray* mp ) {
    const mwSize* size = mxGetDimensions( mp );
    // Error check
    if( !((size[0] == 1 && size[1] > 1) || (size[0] > 1 && size[1] == 1)) ) { throw invalid_argument( "MATLAB argument is not a vector n x 1 or 1 x n" ); }
    if( size[0] > 1 && size[1] > 1 ) { throw invalid_argument( "MATLAB argument is a matrix not a vector" ); }
    if( mxIsSparse(mp) ) { throw invalid_argument( "MATLAB argument is sparse but should be dense" ); }

    // Load vector
    VectorXd x = matlabVec2eigenVec( mp );
    //cout << "Loaded vector:" << endl << x << endl;
    return x;
}

MatrixXd getMatrix( const mxArray* mp ) {
    const mwSize* size = mxGetDimensions( mp );
    // Error check
    if( size[0] <= 1 || size[1] <= 1 ) { throw invalid_argument( "MATLAB argument is a vector rather than a matrix." ); }
    if( mxIsSparse(mp) ) { throw invalid_argument( "MATLAB argument is sparse but should be dense." ); }

    // Load matrix
    MatrixXd A = matlabMat2eigenMat( mp );
    //cout << "Loaded matrix:" << endl << A << endl;
    return A;
}

SparseMatrix< double > getSparseMatrix( const mxArray* mp ) {
    const mwSize* size = mxGetDimensions( mp );
    // Error check
    if( size[0] <= 1 || size[1] <= 1 ) { throw invalid_argument( "MATLAB argument is a vector rather than a matrix." ); }
    if( !mxIsSparse(mp) ) { throw invalid_argument( "MATLAB argument is dense but should be sparse." ); }

    // Load matrix
    SparseMatrix< double > A = matlabSparse2eigenSparse( mp );
    //cout << "Loaded matrix:" << endl << A << endl;
    return A;
}

template <typename T>
double getScalar( const mxArray* mp ) {
    const mwSize* size = mxGetDimensions( mp );
    // Error check
    if( size[0] != 1 || size[1] != 1 ) { throw invalid_argument( "MATLAB argument is not a scalar." ); }
    if( mxIsSparse(mp) ) { throw invalid_argument( "MATLAB argument is sparse but should be dense" ); }

    // Load matrix
    double c = matlabScalar2scalar( mp );
    //cout << "Loaded scalar: " << c << endl;
    return (T) c;
}

/***** MATLAB mex function *****/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    // ais_mex(thetaNode, thetaEdge, L, nSamples, betaVec, nGibbs, verbosity)
    /*
    printf("\nThere are %d right-hand-side argument(s).\n", nrhs);
    for (int i=0; i<nrhs; i++)  {
        const mwSize* dim = mxGetDimensions(prhs[i]);
        printf("\tInput Arg %i is of type:\t%s size: %d x %d, Sparsity: %d\n",
                i, mxGetClassName(prhs[i]), dim[0], dim[1], mxIsSparse(prhs[i]) );
    }
    */

    //mexPrintf("DEBUG: Before loading mex input");
    /* Verify and load arguments */
    VectorXd thetaNode, betaVec;
    SparseMatrix<double> thetaEdge;
    size_t L, nSamples, nGibbs, verbosity, nThreads;
    try {
        if( nrhs < 7 ) { throw invalid_argument( "Incorrect number of arguments." ); }
        thetaNode = getVector( prhs[0] );
        thetaEdge = getSparseMatrix( prhs[1] );
        L = getScalar<size_t>( prhs[2] );
        nSamples = getScalar<size_t>( prhs[3] );
        betaVec = getVector( prhs[4] );
        nGibbs = getScalar<size_t>( prhs[5] );
        verbosity = getScalar<size_t>( prhs[6] );
        if( nrhs >= 8) {
            nThreads = getScalar<size_t>( prhs[7] );
        } else {
            nThreads = 0;
        }
    } catch ( const std::invalid_argument& e ) {
        cerr << "Error loading arguments: " << e.what() << endl;
        fake_answer(plhs);
        return;
    }
    //mexPrintf("DEBUG: After loading mex input");

    /* Simply call ais function */
    //mexPrintf("DEBUG: Before calling ais function");
    VectorXd logW;
    SparseMatrix<double> X;
    ais( thetaNode, thetaEdge, L, nSamples, betaVec, nGibbs, nThreads, verbosity,
            logW, X );
    //mexPrintf("DEBUG: After calling ais function");

    /* Save final answer into MATLAB output */
    //mexPrintf("DEBUG: Before creating mex output arguments");
    if( nlhs >= 1 ) {
        // Sanity check test
        /*
        VectorXd temp(5);
        temp << 1,2,3,4,5;
        cout << "Vector temp:" << endl << temp << endl;
        plhs[0] = eigenVec2matlabVec( temp );
        */
        plhs[0] = eigenVec2matlabVec( logW );
    }
    if( nlhs >= 2 ) {
        // Sanity check test
        /*
        SparseMatrix<double> temp(4,3);
        std::vector< Triplet<double> > triplets;
        triplets.push_back( Triplet<double>(0,0,1) );
        triplets.push_back( Triplet<double>(0,1,1.5) );
        triplets.push_back( Triplet<double>(1,0,0.5) );
        triplets.push_back( Triplet<double>(1,1,2) );
        triplets.push_back( Triplet<double>(2,2,3) );
        temp.setFromTriplets( triplets.begin(), triplets.end() );
        cout << "Sparse matrix temp:" << endl << temp << endl;
        plhs[1] = eigenSparse2matlabSparse( temp );
        */
        plhs[1] = eigenSparse2matlabSparse( X );
    }
    //mexPrintf("DEBUG: After creating mex output arguments");
}

/*
mxArray* kron_perm_dense(const mxArray *mxX, size_t block_m, size_t block_n, size_t *row_perm, size_t *col_perm) {
	size_t rows = mxGetM(mxX), cols = mxGetN(mxX), size = rows*cols;
	double *X = mxGetPr(mxX);
	kmf_rk1_t rk1;
	rk1.fill_attributes(rows, cols, block_m, block_n, row_perm, col_perm);
	size_t new_rows = rk1.Asize(), new_cols = rk1.Bsize(), new_size = new_rows*new_cols;
	printf("%lu x %lu -> %lu x %lu\n", rows, cols, new_rows, new_cols);
	mxArray *mxkpX = mxCreateDoubleMatrix(new_rows, new_cols, mxREAL);
	double *kpX = mxGetPr(mxkpX);

	for(size_t new_idx = 0; new_idx < new_size; new_idx++)
		kpX[new_idx] = 0;
	for(size_t c = 0, idx = 0; c < cols; c++) {
		for(size_t r = 0; r < rows; r++) {
			size_t i=0, j=0;
			rk1.get_indices(r,c,i,j);
			kpX[j*new_rows+i] = X[idx++];
		}
	}
	return mxkpX;
}
mxArray* kron_perm_sparse(const mxArray *X, size_t block_m, size_t block_n, size_t *row_perm, size_t *col_perm) {
    // ir pointer to row indexes, jc pointer to column starts
	mwIndex *ir = mxGetIr(X), *jc = mxGetJc(X);
	double *val = mxGetPr(X);
	size_t rows = mxGetM(X), cols = mxGetN(X), nnz = jc[cols];

	kmf_rk1_t rk1;
	rk1.fill_attributes(rows, cols, block_m, block_n, row_perm, col_perm);
	size_t new_rows = rk1.Asize(), new_cols = rk1.Bsize();
	mxArray *kpX = mxCreateSparse(new_rows, new_cols, nnz, mxREAL);
	mwIndex *new_ir = mxGetIr(kpX), *new_jc = mxGetJc(kpX);
	double *new_val = mxGetPr(kpX);

    // Set all new column pointers to 0
	for(size_t j = 0; j <= new_cols; j++)
		new_jc[j] = 0;
    // Find sizes of new columns
	for(size_t c = 0; c < cols; c++) {
		for(mwIndex idx = jc[c]; idx != jc[c+1]; idx++) {
			size_t r = ir[idx];
			size_t i, j;
			rk1.get_indices(r,c,i,j);
			new_jc[j+1]++;
		}
	}
    // Make the column pointers be indexes instead of counts
	for(size_t j = 1; j <= new_cols; j++)
		new_jc[j] += new_jc[j-1];
    // Now find update new values
    // Essentially fill in the columns and update the for different j columns
    // Looping through in original order
	for(size_t c = 0; c < cols; c++) {
		for(mwIndex idx = jc[c]; idx != jc[c+1]; idx++) {
			size_t r = ir[idx];
			size_t i, j;
			rk1.get_indices(r,c,i,j);
			new_ir[new_jc[j]] = i;
			new_val[new_jc[j]] = val[idx];
			new_jc[j]++;
		}
	}
    // Reset column pointers
	for(size_t j = new_cols; j > 0; j--)
		new_jc[j] = new_jc[j-1];
	new_jc[0] = 0;
    // Sort column values based on row indices
	for(size_t j = 0; j < new_cols; j++)
		sort(zip_iter(&new_ir[new_jc[j]], &new_val[new_jc[j]]),
				zip_iter(&new_ir[new_jc[j+1]], &new_val[new_jc[j+1]]));
	return kpX;
}
*/

max_stars_repo_name: davidinouye/mrfs

max_issues_repo_name: davidinouye/mrfs

max_forks_repo_name: davidinouye/mrfs


text:
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <math.h>
#include <boost/python.hpp>
// #include <boost/python/list.hpp>

#define ERROR NULL;
using namespace std;

typedef struct tagBmpFileHeader //文件头
{
    short padding;
    unsigned short bfType;		//标识该文件为bmp文件,判断文件是否为bmp文件，即用该值与"0x4d42"比较是否相等即可，0x4d42 = 19778
    unsigned int  bfSize;		//文件大小
    unsigned short bfReserved1;	//预保留位
    unsigned short bfReserved2;	//预保留位
    unsigned int  bfOffBits;	//图像数据区的起始位置
}BmpFileHeader;//14字节

typedef struct tagBmpInfoHeader //信息头
{
    unsigned int  biSize;	//图像数据大小
    int     biWidth;	//宽度
    int     biHeight;	//高度
    unsigned short biPlanes;//为1
    unsigned short biBitCount; //像素位数，8-灰度图；24-真彩色
    unsigned int biCompression;//压缩方式
    unsigned int biSizeImage;  //图像区数据大小
    int     biXPelsPerMeter;  //水平分辨率，像素每米
    int     biYPelsPerMeter;
    unsigned int biClrUsed;   //位图实际用到的颜色数
    unsigned short biClrImportant;//位图显示过程，重要的颜色数；0--所有都重要
}BmpInfoHeader;//40字节

typedef struct tagRGBPallete //调色板
{
    unsigned char b;
    unsigned char g;
    unsigned char r;
    unsigned char alpha; //预保留位
}RGBPallete;

typedef struct tagVImage
{
    BmpFileHeader FileHeader;
    BmpInfoHeader InfoHeader;

    int width;
    int height;
    int channels;
    unsigned char* data;
    unsigned char** pixel;
}VImage;

VImage* loadBMP(const char* filename)
{
    VImage* newImage = new VImage;

    ifstream bmpFile;
    bmpFile.open(filename, ifstream::binary);
    if (!bmpFile.is_open())
    {
        cerr<<"Load file failed"<<endl;
        return ERROR;
    }

    // FileHeader
    BmpFileHeader* pFileHeader = new BmpFileHeader;

    bmpFile.read((char*)(&pFileHeader->bfType), sizeof(BmpFileHeader) - sizeof(short));

    if (pFileHeader->bfType != 0x4d42)// 0x4d42 = 19778
    {
        bmpFile.close();
        return ERROR;
    }
    memcpy(&newImage->FileHeader,pFileHeader, sizeof(BmpFileHeader));

    // InfoHeader
    BmpInfoHeader* pInfoHeader = new BmpInfoHeader;
    bmpFile.read((char*)pInfoHeader, sizeof(BmpInfoHeader));
    memcpy(&newImage->InfoHeader,pInfoHeader, sizeof(BmpInfoHeader));

    int width = 0, height = 0;
    width = pInfoHeader->biWidth;
    height = pInfoHeader->biHeight;
    width = ((width + 3) >> 2) << 2;

    if (8 == pInfoHeader->biBitCount)
    {
        unsigned int palleteSize;
        if(pInfoHeader->biClrUsed != 0)
        {
            palleteSize = pInfoHeader->biClrUsed;
        }
        else
        {
            palleteSize = pow(2, pInfoHeader->biBitCount);
        }

        RGBPallete **pRGBPallete = new RGBPallete*[palleteSize * sizeof(RGBPallete)];

        for(int i = 0 ; i < palleteSize; i++)
        {
            pRGBPallete[i] = new RGBPallete;
            bmpFile.read((char*)pRGBPallete[i], sizeof(RGBPallete));
        }

        newImage->width = width;
        newImage->height = height;
        newImage->channels = 1;

        unsigned char* tempBuf = new unsigned char[(width * height)];
        memset(tempBuf, 0, width * height);
        bmpFile.read((char*)tempBuf, width * height);

        newImage->data = new unsigned char[(width * height)];
        for (int i = 0; i < height; i++)
        {
            memcpy(newImage->data + i * width, tempBuf + (height - 1 - i) * width, width);
        }

        newImage->pixel = new unsigned char*[height];
        for(int i = 0; i < height; i++)
        {
            newImage->pixel[i] = new unsigned char[width];
            for(int j = 0; j < width; j++)
            {
                newImage->pixel[i][j] = pRGBPallete[int(newImage->data[i * width + j])]->r;
            }
        }

        delete pFileHeader;
        delete pInfoHeader;
        delete pRGBPallete[];
        delete tempBuf[];

        bmpFile.close();

        return newImage;
    }
    else if (24 == pInfoHeader->biBitCount) // 真彩色
    {
        cout<<"This is a colored picture"<<endl;
        bmpFile.close();
        return ERROR;
    }
    bmpFile.close();
    return ERROR;
}

void readBMP(const char* filename)
{
    VImage* Image = loadBMP(filename);

    ofstream fout;
    fout.open("./bmp_data.tmp");
    for(int i=0;i<Image->InfoHeader.biHeight;i++)
    {
        for(int j=0;j<Image->InfoHeader.biWidth;j++)
        {
            fout<<int(Image->pixel[i][j])<<' ';
        }
        fout<<endl;
    }
    fout.close();
}

BOOST_PYTHON_MODULE(bmp_reader)
{
    using namespace boost::python;
    def("readBMP", readBMP);
}

// int main()
// {
//     VImage* Image = loadBMP("/Users/simon/Desktop/CV第二次作业/Lena.bmp");

//     ofstream fout,fout_plot;
//     fout.open("./lena_data.dat");
//     fout_plot.open("./lena_data_plot.txt");
//     for(int i=0;i<Image->InfoHeader.biHeight;i++)
//     {
//         for(int j=0;j<Image->InfoHeader.biWidth;j++)
//         {
//             fout<<int(Image->pixel[i][j])<<' ';
//             fout_plot << (".:-=+*#%@"[(int) (Image->pixel[i][j] / 32)]);
//         }
//         fout<<endl;
//         fout_plot<<endl;
//     }
//     fout.close();
//     fout_plot.close();

//     return 0;
// }


text:
#include "FPGA_dequeue.h"
// Generated from the AFU JSON file by afu_json_mgr
#include "afu_json_info.h"

#include <unistd.h>
#include <time.h>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <stdlib.h>
#include <sys/mman.h>
#include <chrono>

#include "common.h"

#define ELEM_LINE   8
#define BUFFER_SIZE 32

// ========================================================================
//
// Each test must provide these functions used by main to find the
// specific test instance.
//
// ========================================================================

const char* testAFUID()
{
    return AFU_ACCEL_UUID;
}

void testConfigOptions(po::options_description &desc)
{
    // Add test-specific options
    desc.add_options()
      ("rdline-mode", po::value<string>()->default_value("S"), "Emit read requests with mode (I [invalid], S [shared])")
      ("rdline-channel", po::value<string>()->default_value("VA"), "Emit read requests on channel (VA [automatic], VL0 [QPI], VH0 [PCIe0], VH1 [PCIe1])")
      ("wrline-mode", po::value<string>()->default_value("M"), "Emit write requests with mode (I [invalid], M [modified], or P [push])")
      ("wrline-channel", po::value<string>()->default_value("VA"), "Emit write requests on channel (VA [automatic], VL0 [QPI], VH0 [PCIe0], VH1 [PCIe1])")
      ("fence", po::value<bool>()->default_value(false), "Enable fence ")
      ("fence_rsp", po::value<bool>()->default_value(false), "Enable fence response")
      ("wr_rsp_write_head", po::value<bool>()->default_value(true), "Enable write response write head")
      ("elements,e", po::value<int>()->default_value(100), "The total nuber of elements to enqueue/dequeue")
      ("VL0_enemy", po::value<int>()->default_value(0), "Activate a VL0 enemy, a higher number coresponds to a higher frequency")
      ("VH0_enemy", po::value<int>()->default_value(0), "Activate a VH0 enemy, a higher number coresponds to a higher frequency")
      ("VH1_enemy", po::value<int>()->default_value(0), "Activate a VH1 enemy, a higher number coresponds to a higher frequency")
      ;

}

CCI_TEST* allocTest(const po::variables_map& vm, SVC_WRAPPER& svc)
{
    return new FPGA_dequeue(vm, svc);
}

// ========================================================================
//
// Coherance write after read.
//
// ========================================================================

int FPGA_dequeue::test()
{

    uint64_t elements = uint64_t(vm["elements"].as<int>());
    uint64_t fence = (vm["fence"].as<bool>() ? 1 : 0);
    uint64_t fence_rsp = (vm["fence_rsp"].as<bool>() ? 1 : 0);
    uint64_t wr_rsp_write_head = (vm["wr_rsp_write_head"].as<bool>() ? 1 : 0);

    uint64_t VL0_enemy = uint64_t(vm["VL0_enemy"].as<int>());
    uint64_t VH0_enemy = uint64_t(vm["VH0_enemy"].as<int>());
    uint64_t VH1_enemy = uint64_t(vm["VH1_enemy"].as<int>());

    uint64_t head = 0;
    uint64_t tail = 0;

    // Alocate memory for the queue
    auto queue_handle = this->allocBuffer( BUFFER_SIZE * ELEM_LINE * sizeof(uint64_t) );
    auto queue = reinterpret_cast<volatile uint64_t*>(queue_handle->c_type());
    assert(NULL != queue);
    // Initialize the x linked list in the buffer
    setArray(const_cast<uint64_t*>(queue), 0, BUFFER_SIZE * ELEM_LINE);

    // Alocate memory for the head and tail
    auto head_tail_handle = this->allocBuffer( 4 * ELEM_LINE * sizeof(uint64_t) );
    auto head_tail = reinterpret_cast<volatile uint64_t*>(head_tail_handle->c_type());
    assert(NULL != head_tail);
    // Initialize the x linked list in the buffer
    setArray(const_cast<uint64_t*>(head_tail), 0, 4 * ELEM_LINE);

    // Alocate memory for final space
    auto back_handle = this->allocBuffer( elements * ELEM_LINE * sizeof(uint64_t) );
    auto back = reinterpret_cast<volatile uint64_t*>(back_handle->c_type());
    assert(NULL != back);
    // Initialize the final
    setArray(const_cast<uint64_t*>(back), 0, elements * ELEM_LINE);

    //
    // Configure the HW test
    //
    writeTestCSR(1, intptr_t(queue));
    writeTestCSR(2, intptr_t(head_tail));
    writeTestCSR(3, intptr_t(back));

    uint64_t rdline_mode;
    switch (toupper(vm["rdline-mode"].as<string>()[0]))
    {
      case 'I':
        rdline_mode = 0;
        break;
      case 'S':
        rdline_mode = 1;
        break;
      default:
        cerr << "Invalid --rdline-mode.  Expected I or S." << endl;
        exit(1);
    }

    auto  r_channel = vm["rdline-channel"].as<string>();
    uint64_t rdline_channel;

    if (boost::iequals(r_channel, "VA")) { rdline_channel = 0; }
    else if (boost::iequals(r_channel, "VL0")) { rdline_channel = 1; }
    else if (boost::iequals(r_channel, "VH0")) { rdline_channel = 2; }
    else if (boost::iequals(r_channel, "VH1")) { rdline_channel = 3; }
    else
    {
        cerr << "Invalid --rdline-channel  Expected VA, VL0, VH0 or VH1." << endl;
        exit(1);
    }

    uint64_t wrline_mode;
    switch (toupper(vm["wrline-mode"].as<string>()[0]))
    {
      case 'I':
        wrline_mode = 0;
        break;
      case 'M':
        wrline_mode = 1;
        break;
      case 'P':
        wrline_mode = 2;
        break;
      default:
        cerr << "Invalid --wrline-mode.  Expected I, M or P." << endl;
        exit(1);
    }

    auto w_channel = vm["wrline-channel"].as<string>();
    uint64_t wrline_channel;

    if (boost::iequals(w_channel, "VA")) { wrline_channel = 0; }
    else if (boost::iequals(w_channel, "VL0")) { wrline_channel = 1; }
    else if (boost::iequals(w_channel, "VH0")) { wrline_channel = 2; }
    else if (boost::iequals(w_channel, "VH1")) { wrline_channel = 3; }
    else
    {
        cerr << "Invalid --wtline-channel  Expected VA, VL0, VH0 or VH1." << endl;
        exit(1);
    }

    uint64_t vl0_lines = readCommonCSR(CCI_TEST::CSR_COMMON_VL0_RD_LINES) +
                         readCommonCSR(CCI_TEST::CSR_COMMON_VL0_WR_LINES);
    uint64_t vh0_lines = readCommonCSR(CCI_TEST::CSR_COMMON_VH0_LINES);
    uint64_t vh1_lines = readCommonCSR(CCI_TEST::CSR_COMMON_VH1_LINES);

    writeTestCSR(4, elements);

    writeTestCSR(5, VL0_enemy);

    writeTestCSR(6, VH0_enemy);

    writeTestCSR(7, VH1_enemy);

    // Start the test
    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
    writeTestCSR(0,
                 (wrline_channel << 8) |
                 (wrline_mode << 6) |
                 (rdline_channel << 4) |
                 (rdline_mode << 3) |
                 (fence_rsp << 2) |
                 (fence << 1) |
                 (wr_rsp_write_head) );

    cout << "Queue address " << hex << intptr_t(queue) << endl;
    cout << "Head and tail address " << hex << intptr_t(head_tail)  << endl << endl;
    cout << "Tail at " << hex << intptr_t(&head_tail[ELEM_LINE])  << endl << endl;

    cout << "Streaming  " << dec << elements << "elements" << endl;
    cout << "wrline_mode " << dec << wrline_mode << endl;
    cout << "rdline_mode " << dec << rdline_mode << endl;
    cout << "fence " << dec << fence << endl;

    struct timespec pause;
    // Longer when simulating
    pause.tv_sec = (hwIsSimulated() ? 1 : 0);
    pause.tv_nsec = 2500000;

    cout << endl << "Started streaming elements" << endl;

    int sent = 0;

    while(0 == head_tail[2*ELEM_LINE])
    {
        while (sent < elements)
        {
            head = head_tail[0]; // Read head
            if (((tail + 1) % BUFFER_SIZE) != head) //If not full
            {
                queue[tail*ELEM_LINE] = sent;
                std::atomic_thread_fence(std::memory_order_seq_cst);
                tail = (head_tail[ELEM_LINE] + 1) % BUFFER_SIZE;
                head_tail[ELEM_LINE] = tail;
                std::atomic_thread_fence(std::memory_order_seq_cst);
                sent++;
//                cout<<" Tail is"<<tail<<endl;
//                cout<<" Head is"<<head<<endl;
            } else {
//                nanosleep(&pause, NULL);
            }
        }
    }

    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( t2 - t1 ).count();

    cout << "Test took " << duration << " miliseconds" << endl;
    cout << endl << endl;

    nanosleep(&pause, NULL);
    int wrong_entries = 0;
    int reorderings = 0;
    for(int i=0; i<elements; i++) {
        if (i != back[i*ELEM_LINE]) {
          wrong_entries++;
          int seen_before = 0;
          for(int j=0; j<i; j=j++) {
            if (back[i*ELEM_LINE] == back[j*ELEM_LINE]) seen_before = 1;
          }
          if (!seen_before) reorderings++;
        }
//       cout << back[i * ELEM_LINE] << " ";
    }
    cout << endl;
    cout << "Number of wrong entries " << wrong_entries << endl;
    cout << "Number of reorderings " << reorderings << endl <<endl;

    uint64_t read_cnt = readTestCSR(4);
    uint64_t write_cnt = readTestCSR(5);
    uint64_t checked_read_cnt = readTestCSR(6);

    uint64_t vl0_lines_n = readCommonCSR(CCI_TEST::CSR_COMMON_VL0_RD_LINES) +
                           readCommonCSR(CCI_TEST::CSR_COMMON_VL0_WR_LINES);
    uint64_t vh0_lines_n = readCommonCSR(CCI_TEST::CSR_COMMON_VH0_LINES);
    uint64_t vh1_lines_n = readCommonCSR(CCI_TEST::CSR_COMMON_VH1_LINES);

    cout << "   VL0 " << vl0_lines_n - vl0_lines
         << " : VH0 " << vh0_lines_n - vh0_lines
         << " : VH1 " << vh1_lines_n - vh1_lines
         << endl;

     // Reads CSRs to get some statistics
     cout << "#" << endl
          << "# AFU frequency: " << getAFUMHz() << " MHz"
          << (hwIsSimulated() ? " [simulated]" : "")
          << endl;

    // Stall the CPU so that it does not deallocate memory too soon
    pause.tv_sec = 2;
    nanosleep(&pause, NULL);

    return 0;
}

uint64_t
FPGA_dequeue::testNumCyclesExecuted()
{
    return totalCycles;
}

max_stars_repo_name: diorga/harpy

max_issues_repo_name: diorga/harpy

max_forks_repo_name: diorga/harpy


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.
*/

#include <boost/test/unit_test.hpp>
#include <ored/portfolio/schedule.hpp>
#include <oret/toplevelfixture.hpp>

using namespace boost::unit_test_framework;
using namespace ore::data;
using namespace QuantLib;

BOOST_FIXTURE_TEST_SUITE(OREDataTestSuite, ore::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(ScheduleDataTests)

BOOST_AUTO_TEST_CASE(testScheduleData) {

    BOOST_TEST_MESSAGE("Testing ScheduleData...");

    ScheduleDates dates1("TARGET", "", "", {"2015-01-09", "2015-02-09", "2015-03-09", "2015-04-09"});

    ScheduleDates dates2("TARGET", "", "",
                         {"2015-04-09",
                          "2016-04-11", // 9th = Saturday
                          "2017-04-10", // 9th = Sunday
                          "2018-04-09"});

    ScheduleRules rules1("2015-01-09", "2015-04-09", "1M", "TARGET", "MF", "MF", "Forward");

    ScheduleRules rules2("2015-04-09", "2018-04-09", "1Y", "TARGET", "MF", "MF", "Forward");

    // Test <Dates> and <Dates>
    ScheduleData data(dates1);
    data.addDates(dates2);
    QuantLib::Schedule s = makeSchedule(data);
    BOOST_CHECK_EQUAL(s.size(), 7UL); // 7 dates, 6 coupons
    BOOST_CHECK_EQUAL(s.startDate(), Date(9, Jan, 2015));
    BOOST_CHECK_EQUAL(s.endDate(), Date(9, Apr, 2018));

    // Test <Rules> and <Rules>
    data = ScheduleData(rules1);
    data.addRules(rules2);
    QuantLib::Schedule s2 = makeSchedule(data);
    BOOST_CHECK_EQUAL(s2.size(), s.size());
    for (Size i = 0; i < s.size(); i++)
        BOOST_CHECK_EQUAL(s[i], s2[i]);

    // Test <Dates> and <Rules>
    data = ScheduleData(dates1);
    data.addRules(rules2);
    QuantLib::Schedule s3 = makeSchedule(data);
    BOOST_CHECK_EQUAL(s3.size(), s.size());
    for (Size i = 0; i < s.size(); i++)
        BOOST_CHECK_EQUAL(s[i], s3[i]);
}

// The original reason for adding the LastWednesday date generation rule was to generate the AU CPI publication dates
// using a rules based schedule. Here, we compare the dates for a number of years against the release dates from
// https://www.abs.gov.au/statistics/economy/price-indexes-and-inflation/consumer-price-index-australia
BOOST_AUTO_TEST_CASE(testLastWednesdayDateGenerationRule) {

    vector<Date> expected{
        Date(30, Oct, 2018),
        Date(30, Jan, 2019), Date(24, Apr, 2019), Date(31, Jul, 2019), Date(30, Oct, 2019), // 2019
        Date(29, Jan, 2020), Date(29, Apr, 2020), Date(29, Jul, 2020), Date(28, Oct, 2020), // 2020
        Date(27, Jan, 2021), Date(28, Apr, 2021), Date(28, Jul, 2021), Date(27, Oct, 2021), // 2021
        Date(25, Jan, 2022)
    };

    // AU CPI publication dates are the last Wednesday of Jan, Apr, Jul and Oct. If that is not a good AU business
    // day, it is the preceding good AU business day.
    Schedule s = makeSchedule(ScheduleData(ScheduleRules("2018-10-30", "2022-01-25", "3M", "AUD",
        "Preceding", "Unadjusted", "LastWednesday")));

    // Check
    BOOST_CHECK_EQUAL_COLLECTIONS(s.dates().begin(), s.dates().end(), expected.begin(), expected.end());
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
#ifndef TRAJECTORY_HPP
#define TRAJECTORY_HPP

#include <set>
#include <boost/serialization/list.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/vector.hpp>

#include "bib/Assert.hpp"
#include "bib/Logger.hpp"
#include "bib/Utils.hpp"
#include "kdtree++/kdtree.hpp"

//#define KDTREE_OWNDIST
// old code where the distribution of the state
// is computed online -> wrong idea

template <typename _Tp, typename _Dist>
struct L1_distance
{
  typedef _Dist distance_type;

  distance_type
  operator() (const _Tp& __a, const _Tp& __b, const size_t) const
  {
    distance_type d = fabs(__a - __b);
    return d;
  }
};

typedef struct _sa_sample {
  std::vector<double> s;
  std::vector<double> a;

  typedef double value_type;

  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int) {
    ar& BOOST_SERIALIZATION_NVP(s);
    ar& BOOST_SERIALIZATION_NVP(a);
  }

  bool operator< (const _sa_sample& b) const {
    for (uint i = 0; i < s.size(); i++) {
      if(s[i] != b.s[i])
        return s[i] < b.s[i];
    }

    return false;
  }

  inline value_type operator[](size_t const N) const{
        return s[N];
  }

} SA_sample;

typedef struct _sasrg_sample {
  std::vector<double> s;
  std::vector<double> a;
  std::vector<double> next_s;
  double r;
  bool goal_reached;

  typedef double value_type;

  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int v) {
    ar& BOOST_SERIALIZATION_NVP(s);
    ar& BOOST_SERIALIZATION_NVP(a);
    ar& BOOST_SERIALIZATION_NVP(next_s);
    ar& BOOST_SERIALIZATION_NVP(r);
    ar& BOOST_SERIALIZATION_NVP(goal_reached);
  }

  bool operator< (const _sasrg_sample& b) const {
    for (uint i = 0; i < s.size(); i++) {
      if(s[i] != b.s[i])
        return s[i] < b.s[i];
    }

    return false;
  }

  inline double operator[](size_t const N) const{
        return s[N];
  }

} SASRG_sample;

typedef struct _qsasrg_sample {
  std::vector<double> s;
  std::vector<double> a;
  std::vector<double> next_s;
  double r;
  bool goal_reached;

  typedef double value_type;

  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int v) {
    ar& BOOST_SERIALIZATION_NVP(s);
    ar& BOOST_SERIALIZATION_NVP(a);
    ar& BOOST_SERIALIZATION_NVP(next_s);
    ar& BOOST_SERIALIZATION_NVP(r);
    ar& BOOST_SERIALIZATION_NVP(goal_reached);
  }

  bool operator< (const _qsasrg_sample& b) const {
    for (uint i = 0; i < s.size(); i++) {
      if(s[i] != b.s[i])
        return s[i] < b.s[i];
    }

    for (uint i = 0; i < a.size(); i++) {
      if(a[i] != b.a[i])
        return a[i] < b.a[i];
    }

    return false;
  }

  inline double operator[](size_t const N) const{
        size_t l = s.size();
        return N < l ? s[N] : a[N-l];
  }

} QSASRG_sample;

typedef struct _qsasrgr_sample {
  std::vector<double> s;
  std::vector<double> a;
  std::vector<double> next_s;
  double r;
  bool goal_reached;
  uint replayed ;

  typedef double value_type;

  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int v) {
    ar& BOOST_SERIALIZATION_NVP(s);
    ar& BOOST_SERIALIZATION_NVP(a);
    ar& BOOST_SERIALIZATION_NVP(next_s);
    ar& BOOST_SERIALIZATION_NVP(r);
    ar& BOOST_SERIALIZATION_NVP(goal_reached);
  }

  bool operator< (const _qsasrgr_sample& b) const {
    for (uint i = 0; i < s.size(); i++) {
      if(s[i] != b.s[i])
        return s[i] < b.s[i];
    }

    for (uint i = 0; i < a.size(); i++) {
      if(a[i] != b.a[i])
        return a[i] < b.a[i];
    }

    return false;
  }

  inline double operator[](size_t const N) const{
        size_t l = s.size();
        return N < l ? s[N] : a[N-l];
  }

} QSASRGR_sample;

typedef struct _qsasrgpa_sample {
  std::vector<double> s;
  std::vector<double> a;
  std::vector<double> next_s;
  double r;
  bool goal_reached;
  std::vector<double> pa;

  typedef double value_type;

  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int v) {
    ar& BOOST_SERIALIZATION_NVP(s);
    ar& BOOST_SERIALIZATION_NVP(a);
    ar& BOOST_SERIALIZATION_NVP(next_s);
    ar& BOOST_SERIALIZATION_NVP(r);
    ar& BOOST_SERIALIZATION_NVP(goal_reached);
    ar& BOOST_SERIALIZATION_NVP(pa);
  }

  bool operator< (const _qsasrgpa_sample& b) const {
    for (uint i = 0; i < s.size(); i++) {
      if(s[i] != b.s[i])
        return s[i] < b.s[i];
    }

    for (uint i = 0; i < a.size(); i++) {
      if(a[i] != b.a[i])
        return a[i] < b.a[i];
    }

    return false;
  }

  inline double operator[](size_t const N) const{
        size_t l = s.size();
        return N < l ? s[N] : a[N-l];
  }

} QSASRGPA_sample;

template<typename Struct>
struct UniqTest
{
   bool operator()(const Struct& t ) const
   {
      return been_tested.find(t) == been_tested.end();//not in => not yet tested
   }

   std::set<Struct> been_tested;
};

class Observer{
public:
  Observer(uint _size) : column(_size), data_number(0), mean(_size, 0), var(_size, 0), subvar(_size, 0){}

  void transform(std::vector<double>& output, const std::vector<double> x){
    update_mean_var(x);

    for(uint i=0; i < column; i++){
        output[i] = (x[i] - mean[i]);

        if(var[i] != 0.d)
          output[i] /= sqrt(var[i]) / 0.26115f;
    }

  }

  void update_mean_var(const std::vector<double>& x){
    double dndata_number = data_number + 1;
    double ddata_number = data_number;
    for(uint i=0; i < column; i++){
      mean[i] = (mean[i] * ddata_number + x[i])/dndata_number;

      subvar[i] = (subvar[i] * ddata_number + (x[i]*x[i]))/dndata_number;
      var[i] = subvar[i] - (mean[i]*mean[i]);
    }

    data_number ++;
  }

  uint column;
  ulong data_number;
  std::vector<double> mean;
  std::vector<double> var;
  std::vector<double> subvar;
};

template <typename _Tp, typename _Dist>
class ObserverL1Distance : public Observer{
public:
  typedef _Dist distance_type;

  ObserverL1Distance(uint _size):Observer(_size){}

  distance_type
  operator() (const _Tp& __a, const _Tp& __b, const size_t __dim) const
  {
    distance_type d = fabs(__a - __b);
    if(data_number > 3)
      d /= (sqrt(var[__dim])/0.26115d);

    return d;
  }
};

template <typename Struct=SA_sample >
class Trajectory {

#ifdef KDTREE_OWNDIST
  typedef KDTree::KDTree<Struct, KDTree::_Bracket_accessor<Struct>, ObserverL1Distance< typename Struct::value_type, typename Struct::value_type> > tree_type;
#else
  typedef KDTree::KDTree<Struct, KDTree::_Bracket_accessor<Struct>, L1_distance< typename Struct::value_type, typename Struct::value_type> > tree_type;
#endif

 public:
  Trajectory(size_t _column, double _proba_transform=0.5f, bool _remove_nearest=true, double _proba_threshold=1.f):
  column(_column),
#ifdef KDTREE_OWNDIST
  obs(_column),
  kd_tree(_column, KDTree::_Bracket_accessor<Struct>(), obs),
#else
  kd_tree(_column),
#endif
  proba_transform(_proba_transform), remove_nearest(_remove_nearest), proba_threshold(_proba_threshold), count_removed(0), count_inserted(0) {}

  ~Trajectory(){

  }

  size_t size() {
    return kd_tree.size();
  }

  void addPoint(Struct& elem) {
    count_inserted++;

#ifdef KDTREE_OWNDIST
    std::vector<double> x(column);
    for(uint i=0; i < column;i++)
      x[i] = elem[i];
    obs.update_mean_var(x);
#endif

    if(remove_nearest){
      UniqTest<Struct> predicate;

      while(kd_tree.size() - predicate.been_tested.size() > 0){
          //look for the closest and may be remove it
//           auto pr = kd_tree.find_nearest_if(elem, 2.f * column, predicate);
//           double proba = 1.f - pow(pr.second/proba_threshold, proba_transform); //small than 0.5 -> implies probability to drop

          auto pr = kd_tree.find_nearest_if(elem, sqrt(column), predicate);
          double proba = 1.f - powf((pr.second*pr.second)/(column), proba_transform);

//           LOG_DEBUG(proba << " " << (pr.second*pr.second)/column );
//           bib::Logger::PRINT_ELEMENTS<>(*pr.first, 4);
//           bib::Logger::PRINT_ELEMENTS<>(elem.s, 4);

//           ASSERT(pr.second <= 2 * column, "not normalized");

          if(proba > 0 && bib::Utils::rand01() < proba) {
  //             if(kd_tree->getPoint(indices[i]) == 0){
  //                 LOG_DEBUG("remove proba(" << distance << ") vec dist(" << dists[i] << ") normal dist(" << dists[i] / (2. * column) << " " << indices[i]);
  //                 bib::Logger::PRINT_ELEMENTS<>(kd_tree->getPoint(indices[i]), 3);
  //             }
              kd_tree.erase(pr.first);
              count_removed++;
          }
          else if(proba <= 0)
            break;
          else //proba >= 0 but didn't been tackle
            predicate.been_tested.insert(*pr.first);
      }
    }

      //if elem colide with a data, it has just been removed with probability 1
      kd_tree.insert(elem);

  }

  tree_type& tree(){
      return kd_tree;
  }

  void print(){
//     for(auto it = kd_tree.begin(); it != kd_tree.end() ; ++it)
//       LOG_DEBUG(it->print);
  }
  void clear(){
      kd_tree.clear();
  }

 private :
  size_t column;
#ifdef KDTREE_OWNDIST
  ObserverL1Distance<typename Struct::value_type, typename Struct::value_type> obs;
#endif
  tree_type kd_tree;
  const double proba_transform;
  bool remove_nearest;
  const double proba_threshold;
public:
  uint count_removed;
  uint count_inserted;
};

#endif


text:
//=======================================================================
// Copyright 2002 Indiana University.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// 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_GRAPH_DAG_SHORTEST_PATHS_HPP
#define BOOST_GRAPH_DAG_SHORTEST_PATHS_HPP

#include <boost/graph/topological_sort.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>

// single-source shortest paths for a Directed Acyclic Graph (DAG)

namespace boost
{

// Initalize distances and call depth first search
template < class VertexListGraph, class DijkstraVisitor, class DistanceMap,
    class WeightMap, class ColorMap, class PredecessorMap, class Compare,
    class Combine, class DistInf, class DistZero >
inline void dag_shortest_paths(const VertexListGraph& g,
    typename graph_traits< VertexListGraph >::vertex_descriptor s,
    DistanceMap distance, WeightMap weight, ColorMap color, PredecessorMap pred,
    DijkstraVisitor vis, Compare compare, Combine combine, DistInf inf,
    DistZero zero)
{
    typedef typename graph_traits< VertexListGraph >::vertex_descriptor Vertex;
    std::vector< Vertex > rev_topo_order;
    rev_topo_order.reserve(num_vertices(g));

    // Call 'depth_first_visit', not 'topological_sort', because we don't
    // want to traverse the entire graph, only vertices reachable from 's',
    // and 'topological_sort' will traverse everything. The logic below
    // is the same as for 'topological_sort', only we call 'depth_first_visit'
    // and 'topological_sort' calls 'depth_first_search'.
    topo_sort_visitor< std::back_insert_iterator< std::vector< Vertex > > >
        topo_visitor(std::back_inserter(rev_topo_order));
    depth_first_visit(g, s, topo_visitor, color);

    typename graph_traits< VertexListGraph >::vertex_iterator ui, ui_end;
    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)
    {
        put(distance, *ui, inf);
        put(pred, *ui, *ui);
    }

    put(distance, s, zero);
    vis.discover_vertex(s, g);
    typename std::vector< Vertex >::reverse_iterator i;
    for (i = rev_topo_order.rbegin(); i != rev_topo_order.rend(); ++i)
    {
        Vertex u = *i;
        vis.examine_vertex(u, g);
        typename graph_traits< VertexListGraph >::out_edge_iterator e, e_end;
        for (boost::tie(e, e_end) = out_edges(u, g); e != e_end; ++e)
        {
            vis.discover_vertex(target(*e, g), g);
            bool decreased
                = relax(*e, g, weight, pred, distance, combine, compare);
            if (decreased)
                vis.edge_relaxed(*e, g);
            else
                vis.edge_not_relaxed(*e, g);
        }
        vis.finish_vertex(u, g);
    }
}

namespace detail
{

    // Defaults are the same as Dijkstra's algorithm

    // Handle Distance Compare, Combine, Inf and Zero defaults
    template < class VertexListGraph, class DijkstraVisitor, class DistanceMap,
        class WeightMap, class ColorMap, class IndexMap, class Params >
    inline void dag_sp_dispatch2(const VertexListGraph& g,
        typename graph_traits< VertexListGraph >::vertex_descriptor s,
        DistanceMap distance, WeightMap weight, ColorMap color, IndexMap /*id*/,
        DijkstraVisitor vis, const Params& params)
    {
        typedef typename property_traits< DistanceMap >::value_type D;
        dummy_property_map p_map;
        D inf = choose_param(get_param(params, distance_inf_t()),
            (std::numeric_limits< D >::max)());
        dag_shortest_paths(g, s, distance, weight, color,
            choose_param(get_param(params, vertex_predecessor), p_map), vis,
            choose_param(
                get_param(params, distance_compare_t()), std::less< D >()),
            choose_param(
                get_param(params, distance_combine_t()), closed_plus< D >(inf)),
            inf, choose_param(get_param(params, distance_zero_t()), D()));
    }

    // Handle DistanceMap and ColorMap defaults
    template < class VertexListGraph, class DijkstraVisitor, class DistanceMap,
        class WeightMap, class ColorMap, class IndexMap, class Params >
    inline void dag_sp_dispatch1(const VertexListGraph& g,
        typename graph_traits< VertexListGraph >::vertex_descriptor s,
        DistanceMap distance, WeightMap weight, ColorMap color, IndexMap id,
        DijkstraVisitor vis, const Params& params)
    {
        typedef typename property_traits< WeightMap >::value_type T;
        typename std::vector< T >::size_type n;
        n = is_default_param(distance) ? num_vertices(g) : 1;
        std::vector< T > distance_map(n);
        n = is_default_param(color) ? num_vertices(g) : 1;
        std::vector< default_color_type > color_map(n);

        dag_sp_dispatch2(g, s,
            choose_param(distance,
                make_iterator_property_map(
                    distance_map.begin(), id, distance_map[0])),
            weight,
            choose_param(color,
                make_iterator_property_map(
                    color_map.begin(), id, color_map[0])),
            id, vis, params);
    }

} // namespace detail

template < class VertexListGraph, class Param, class Tag, class Rest >
inline void dag_shortest_paths(const VertexListGraph& g,
    typename graph_traits< VertexListGraph >::vertex_descriptor s,
    const bgl_named_params< Param, Tag, Rest >& params)
{
    // assert that the graph is directed...
    null_visitor null_vis;
    detail::dag_sp_dispatch1(g, s, get_param(params, vertex_distance),
        choose_const_pmap(get_param(params, edge_weight), g, edge_weight),
        get_param(params, vertex_color),
        choose_const_pmap(get_param(params, vertex_index), g, vertex_index),
        choose_param(
            get_param(params, graph_visitor), make_dijkstra_visitor(null_vis)),
        params);
}

} // namespace boost

#endif // BOOST_GRAPH_DAG_SHORTEST_PATHS_HPP

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.

// All rights reserved.

// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/

//////////////////////////////////////////////////////////////////////
/// @file
/// Test @ref stapl::rmi_fence().
//////////////////////////////////////////////////////////////////////

#include <stapl/runtime.hpp>
#include <iostream>
#include "test_utils.h"
#include <boost/lexical_cast.hpp>

using namespace stapl;

struct p_test
: public p_object
{
  unsigned int m_fence_count;
  // source and  destination must not be directly linked in the spanning tree of
  // the fence
  unsigned int m_src;
  unsigned int m_dst;

  p_test(const unsigned int src = 0,
         const unsigned int dst = (stapl::get_num_locations()-1))
  : m_fence_count(0),
    m_src(src % this->get_num_locations()),
    m_dst(dst % this->get_num_locations())
  {
    rmi_fence(); // initialize p_object and do the first fence
    ++m_fence_count;
  }

  void check_count(const unsigned int count)
  {
    // problem: the initial message was sent in the previous fence. As this is
    // the answer to the initiating  message, it results from the activity
    // initiated by the call to fence_bust(). It must be received before the
    // fence can pass.
    STAPL_RUNTIME_TEST_CHECK(m_fence_count, count);
  }

  void check_count2(const unsigned int src, const unsigned int count)
  {
    check_count(count);
    for (unsigned int i=0; i<2; ++i) {
      async_rmi(src, this->get_rmi_handle(),
                       &p_test::check_count, count);
      rmi_flush();
      delay(1);
    }
  }

  void fence_bust(void)
  {
    if (this->get_location_id()==m_src) {
      async_rmi(m_dst, this->get_rmi_handle(),
                &p_test::check_count2, m_src, m_fence_count);
      rmi_flush();
    }
    rmi_fence(); // first fence
    ++m_fence_count;
    rmi_fence(); // check if RMIs leaked from the first fence
    ++m_fence_count;
  }

  void execute(void)
  {
    fence_bust();
  }
};

exit_code stapl_main(int argc, char* argv[])
{
  if (argc < 3) {
    p_test pt;
    pt.execute();
  }
  else {
    p_test pt(boost::lexical_cast<unsigned int>(argv[1]),
              boost::lexical_cast<unsigned int>(argv[2]));
    pt.execute();
  }
#ifndef _TEST_QUIET
  std::cout << get_location_id() << " successfully passed!" << std::endl;
#endif
  return EXIT_SUCCESS;
}

ext: cc