text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
/*!
 * \file
**/
#ifndef NT2_COMPLEX_CONSTANTS_I_HPP_INCLUDED
#define NT2_COMPLEX_CONSTANTS_I_HPP_INCLUDED

#include <nt2/include/functor.hpp>
#include <boost/simd/constant/hierarchy.hpp>
#include <complex>

/*!
 * \ingroup nt2_complex
 * \defgroup nt2_complex_i I
 *
 * \par Description
 * Constant I : Imag unit.
 *
 * \par Header file
 *
 * \code
 * #include <nt2/include/functions/i.hpp>
 * \endcode
 *
 * \alias:
 *    J
 *
 * \synopsis
 *
 * \code
 * namespace boost::simd
 * {
 *   template <class T>
 *     meta::call<tag::I(as_<T>)>::type
 *     I();
 * }
 * \endcode
 *
 *
 * \param T template parameter of I
 *
 * \return type T value
 *
 *
**/

namespace nt2
{
  namespace tag
  {
    /*!
     * \brief Define the tag I of functor I
     *        in namespace nt2::tag for toolbox complex
    **/
    struct I : ext::constant_<I>
    {
      typedef std::complex<double> default_type;
      typedef ext::constant_<I> parent;
      template<class... Args>
      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
      BOOST_AUTO_DECLTYPE_BODY( dispatching_I( ext::adl_helper(), static_cast<Args&&>(args)... ) )
    };
  }
  namespace ext
  {
    template<class Site, class... Ts>
    BOOST_FORCEINLINE generic_dispatcher<tag::I, Site> dispatching_I(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
    {
      return generic_dispatcher<tag::I, Site>();
    }
    template<class... Args>
    struct impl_I;
  }

  BOOST_SIMD_CONSTANT_IMPLEMENTATION(nt2::tag::I, I)
  BOOST_SIMD_CONSTANT_IMPLEMENTATION(nt2::tag::I, J)
}

#endif


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

// With contributions from Cornelius Steinhardt

#include <cstdlib>
#include <iostream>
#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/mtl/operation/cuppen.hpp>

using namespace std;

const double 			tol= 1.0e-5;

template <typename Matrix, typename Value, typename Vector>
void test_vector(const Matrix& A, const Value& alpha, const Vector& v, int i)
{
    Vector diff(A*v-alpha*v), v1(A*v), v2(alpha*v); // , diff(v1-v2);
    if (size(v1) < 17)
	cout << "A*v is     " << v1 << "\nalpha*v is " << v2 << '\n';
    if (two_norm(diff) > tol) cout << "two_norm(difference) of the " << i << "-th eigenvector is " << two_norm(diff) << '\n'; // throw "wrong eigenvector";
}

template <typename Matrix, typename Value, typename Vector>
void test(const Matrix& B, Matrix& BQ, Value scaling, Vector& lambda_b)
{
    if (num_rows(B) <= 20)
	std::cout << "B=\n" << B << "\n";

    mtl::dense_vector<double> eig_b= eigenvalue_symmetric(B,22);
    sort(eig_b);
    eig_b*= scaling;
    std::cout<<"eigenvalues with QR ="<< eig_b <<"\n";

    cuppen(B, BQ, lambda_b);
    lambda_b*= scaling;
    // std::cout<<"B  =\n"<< B <<"\n";
    if (num_rows(B) <= 20)
	std::cout<<"Q  =\n"<< BQ <<"\n";
    std::cout<<"eigenvalues with Cuppen ="<< lambda_b <<"\n";

    eig_b-= lambda_b;
    std::cout<<"two_norm(diff)  ="<< two_norm(eig_b) <<"\n";
    MTL_THROW_IF(two_norm(eig_b) > tol, mtl::runtime_error("Cuppen computes wrong eigenvalues"));

    Matrix Bs(scaling * B);
    for (unsigned i= 0; i < num_rows(B); i++)
	test_vector(Bs, lambda_b[i], mtl::dense_vector<double>(BQ[mtl::iall][i]), i);
}

int main(int argc, char** argv)
{
    using namespace mtl;
    int size= 16;
    if (argc > 1) size= atoi(argv[1]);

    dense_vector<double>        eig, lam(2), lambda(4),  lambda_b(size), eig_b(size);
#if 1
    dense2D<double> Mini(2, 2), QM(2, 2);
    Mini= 1, 2, 2, -11;
    cuppen(Mini, QM, lam);

    std::cout << "eigenvalues of Mini  =" << lam <<"\n";
    std::cout << "eigenvectors of Mini are\n" << QM;
#endif

    double array[][4]= {{1,  2,   0,  0},
                        {2, -9,  -2,  0},
                        {0, -2,   1,  3},
                        {0,  0,   3, 10}};
    dense2D<double> A(array), Q(4,4);
    std::cout << "A=\n" << A << "\n";

    eig= eigenvalue_symmetric(A,22);
    sort(eig);
    std::cout<<"eigenvalues  ="<< eig <<"\n";

    cuppen(A, Q, lambda);
    std::cout<<"A  =\n"<< A <<"\n";
    std::cout<<"Q  =\n"<< Q <<"\n";
    std::cout<<"eigenvalues  ="<< lambda <<"\n";

    eig-= lambda;
    std::cout<<"two_norm(diff)  ="<< two_norm(eig) <<"\n";
    MTL_THROW_IF(two_norm(eig) > tol, mtl::runtime_error("Cuppen computes wrong eigenvalues"));

    for (unsigned i= 0; i < num_rows(A); i++)
	test_vector(A, lambda[i], dense_vector<double>(Q[iall][i]), i);

    dense2D<double> B(size,size), BQ(size,size);
    B= 0; BQ= 0;

    const double scale= 64.0 / double(size);
    for(int i= 1; i < size ; i++){
      B[i][i]= scale*i+6;
      B[i][i-1]= 1;
      B[i-1][i]= 1;
    }
    B[0][0]= 6;

    test(B, BQ, 1.0, lambda_b);

    const double maxv= B[size-1][size-1];
    B/= maxv;
    test(B, BQ, maxv, lambda_b);

#if 0
    // Poisson equation cannot be solved, double eigenvalues are now correctly handled by the secular equation
    // but Q_tilde in cuppen contains nans (0/0)
    int lsize= 4;
    if (argc > 1) lsize= atoi(argv[1]);

    dense2D<double> C(lsize, lsize), CQ(lsize, lsize);
    C= 0; CQ= 0;

    C[0][0]= 2;
    for(int i= 1; i < lsize; i++) {
	C[i][i]= 2;
	C[i][i-1]= -1;
	C[i-1][i]= -1;
    }
    cout << "The matrix of the 1D-Poisson equations I\n" << C << '\n';

    dense_vector<double> lambda_c(lsize);
    cuppen(C, CQ, lambda_c);

    if (lsize <= 100)
	cout << "The eigenvalues of the 1D-Poisson equations are " << lambda_c << '\n';
    if (lsize <= 20)
	cout << "The eigenvectors of the 1D-Poisson equations are\n" << CQ << '\n';

    for (unsigned i= 0; i < num_rows(C); i++);
	//test_vector(C, lambda_c[i], dense_vector<double>(CQ[iall][i]));
#endif

    return 0;
}

ext: cpp


text:
#include <boost/test/unit_test.hpp>
#include <fc/exception/exception.hpp>
#include <fc/lru_cache.hpp>
#include <boost/filesystem/operations.hpp>
#include <iostream>

BOOST_AUTO_TEST_SUITE( lru_cache_tests )

BOOST_AUTO_TEST_CASE( lru_cache_tests )
{
   try
   {
      BOOST_TEST_MESSAGE( "Testing: lru_cache" );
      constexpr uint32_t max_pool_size = 3;

      using Cache = fc::LruCache<std::string, std::string>;
      Cache resourcePool(max_pool_size, Cache::default_timeout, std::chrono::milliseconds(0));
      resourcePool.emplace("key1", "value1");
      resourcePool.emplace("key2", "value2");
      resourcePool.emplace("key3", "value3");
      resourcePool.emplace("key4", "value4");

      BOOST_TEST_MESSAGE( "--- Test max number of resources enabled in pool" );
      BOOST_CHECK_EQUAL(max_pool_size, resourcePool.size());

      BOOST_TEST_MESSAGE( "--- Test if the least used resource was deleted" );
      BOOST_CHECK( !resourcePool.get("key1") );

      BOOST_TEST_MESSAGE( "--- Test trying to get non-existing resource" );
      BOOST_CHECK( !resourcePool.get("key5") );

      BOOST_TEST_MESSAGE( "--- Test automatic creation of non-existing resource with getAut method" );
      BOOST_CHECK_EQUAL( resourcePool.emplace("key6", "value6"), "value6" );

      // There are now resources mapped to key key3, key4, key6 that are ordered(according to the last access_time): key3, key4, key6
      resourcePool.get("key3"); // use resource key3 -> updates last access_time
      // Now there should be present resources in order: key4, key6, key3
      std::string& createdResource = resourcePool.emplace("key7", "value7");  // create new resource for key7
      BOOST_TEST_MESSAGE( "--- Test if newly created resource original value" );
      BOOST_CHECK_EQUAL( resourcePool.get("key7").value(), "value7");

      // Now there should be present resources in order: key6, key3, key7
      BOOST_TEST_MESSAGE( "--- Test if last_access time of resource was updated when get called" );
      BOOST_CHECK( resourcePool.get("key3") );

      BOOST_TEST_MESSAGE( "--- Test if the least used resource was deleted" );
      BOOST_CHECK( !resourcePool.get("key4"));

      // Change internal value of newly created resource
      createdResource = "here we go changing the value";
      BOOST_TEST_MESSAGE( "--- Test if newly created resource value was changed" );
      BOOST_CHECK_EQUAL( resourcePool.get("key7").value(), "here we go changing the value");

      // Change internal value of resource obtained by get method
      boost::optional<std::string&> foundResourceOpt = resourcePool.get("key7");
      std::string& foundResource = foundResourceOpt.get();
      foundResource = "Change me again";
      BOOST_TEST_MESSAGE( "--- Test if obtained resource value was changed" );
      BOOST_CHECK_EQUAL( resourcePool.get("key7").value(), "Change me again");

      // Get resource by method, which automatically creates new resource, if there is none mapped to the provided key
      std::string& foundResource2 = resourcePool.emplace("key7", "default new value");
      BOOST_TEST_MESSAGE( "--- Test if getAut did not create new resource if there exist one with provided key" );
      BOOST_CHECK_EQUAL( resourcePool.get("key7").value(), "Change me again");

      // Change internal value of resource obtained by getAut method
      foundResource2 = "And again";
      BOOST_TEST_MESSAGE( "--- Test if obtained resource value was changed" );
      BOOST_CHECK_EQUAL( resourcePool.get("key7").value(), "And again");
   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: SophiaTX/SophiaTx-Blockchain

max_issues_repo_name: SophiaTX/SophiaTx-Blockchain

max_forks_repo_name: SophiaTX/SophiaTx-Blockchain


text:
#include "WebpImageReader.h"

#include <webp/decode.h>
#include <webp/demux.h>

#include <boost/format.hpp>

#include "Core/Logging.h"
#include "Utils.h"

struct WebPPic {
    int width;
    int height;
    uint8_t* rgba;
    bool animated;
};

using namespace Gdiplus;

std::unique_ptr<Gdiplus::Bitmap> WebpImageReader::readFromFile(const wchar_t* fileName) {
    uint8_t* dataRaw = nullptr;
    std::unique_ptr<uint8_t> data;
    size_t dataSize = 0;
    if (!ImageUtils::ExUtilReadFile(fileName, &dataRaw, &dataSize)) {
        return nullptr;
    }
    data.reset(dataRaw);
    return readFromMemory(dataRaw, dataSize);
}

std::unique_ptr<Gdiplus::Bitmap> WebpImageReader::readFromMemory(uint8_t* data, size_t size) {
    WebPPic pic;
    memset(&pic, 0, sizeof(pic));
    if (!readWebP(data, size, &pic)) {
        return nullptr;
    }
    std::unique_ptr<Gdiplus::Bitmap> bm = std::make_unique<Gdiplus::Bitmap>(pic.width, pic.height, PixelFormat32bppARGB);

    BitmapData dstData;
    Rect rc(0, 0, pic.width, pic.height);

    if (bm->LockBits(&rc, ImageLockModeWrite, PixelFormat32bppARGB, &dstData) == Ok) {
        auto dstBits = reinterpret_cast<uint8_t *>(dstData.Scan0);
        memcpy(dstBits, pic.rgba, pic.height * pic.width * 4);

        bm->UnlockBits(&dstData);
    }
    if (pic.animated) {
        delete[] pic.rgba;
    }
    else {
        WebPFree(pic.rgba);
    }
    return bm;
}

std::unique_ptr<Gdiplus::Bitmap> WebpImageReader::readFromStream(IStream* stream) {
    LARGE_INTEGER li;
    li.QuadPart = 0;

    if (FAILED(stream->Seek(li, STREAM_SEEK_SET, nullptr))) {
        return nullptr;
    }

    STATSTG stats;
    if (FAILED(stream->Stat(&stats, STATFLAG_NONAME))) {
        return nullptr;
    }
    ULONGLONG sSize = stats.cbSize.QuadPart;
    ULONG bytesRead;
    std::unique_ptr<uint8_t[]> pBuffer;
    try {
        pBuffer.reset(new uint8_t[sSize]);
    }
    catch (std::exception &) {
        lastError_ = str(boost::wformat(L"Unable to allocate %d bytes") % sSize);
        return nullptr;
    }

    if (FAILED(stream->Read(pBuffer.get(), ULONG(sSize), &bytesRead))) {
        lastError_ = L"Failed to read from IStream";
        return nullptr;
    }

    return readFromMemory(pBuffer.get(), sSize);

}

bool WebpImageReader::readWebP(const uint8_t* const data, size_t data_size, WebPPic* pic) {
    VP8StatusCode status = VP8_STATUS_OK;
    WebPDecoderConfig config;
    WebPDecBuffer* const output_buffer = &config.output;
    WebPBitstreamFeatures* const bitstream = &config.input;

    if (!WebPInitDecoderConfig(&config)) {
        LOG(ERROR) << "Library version mismatch!\n";
        return false;
    }

    status = WebPGetFeatures(data, data_size, bitstream);
    if (status != VP8_STATUS_OK) {
        LOG(WARNING) << "Error loading input webp data, status code=" << status;
        return false;
    }
    pic->animated = !!bitstream->has_animation;

    if (bitstream->has_animation) {
        WebPData webp_data;
        WebPDataInit(&webp_data);
        webp_data.bytes = data;
        webp_data.size = data_size;
        WebPAnimInfo anim_info;
        WebPAnimDecoderOptions options;
        memset(&options, 0, sizeof(options));
        options.color_mode = MODE_BGRA;

        WebPAnimDecoder* dec = WebPAnimDecoderNew(&webp_data, &options);
        if (dec == nullptr) {
            LOG(WARNING) << "Error parsing webp image";
            return false;
        }

        if (!WebPAnimDecoderGetInfo(dec, &anim_info)) {
            LOG(WARNING) << "Error getting global info about the animation";
            return false;
        }

        pic->width = anim_info.canvas_width;
        pic->height = anim_info.canvas_height;

        // Decode just first frame
        if (WebPAnimDecoderHasMoreFrames(dec)) {
            uint8_t* frame_rgba;
            int timestamp;

            if (!WebPAnimDecoderGetNext(dec, &frame_rgba, &timestamp)) {
                return false;
            }
            unsigned int frameSize = anim_info.canvas_width*anim_info.canvas_height * 4;
            pic->rgba = new uint8_t[frameSize];
            memcpy(pic->rgba, frame_rgba, frameSize);
        }
        WebPAnimDecoderDelete(dec);

    }
    else {
        //output_buffer->colorspace = has_alpha ? MODE_RGBA : MODE_RGB;

        pic->rgba = WebPDecodeBGRA(data, data_size, &pic->width, &pic->height);
    }
    if (!pic->rgba) {
        return false;
    }
    /*if (status == VP8_STATUS_OK) {
          /*pic->rgba = output_buffer->u.RGBA.rgba;
          pic->stride = output_buffer->u.RGBA.stride;
          pic->width = output_buffer->width;
          pic->height = output_buffer->height;*/

          /*ok = has_alpha ? WebPPictureImportRGBA(pic, rgba, stride)
                    : WebPPictureImportRGB(pic, rgba, stride);*
            }*/

    WebPFreeDecBuffer(output_buffer);
    return true;
}

std::wstring WebpImageReader::getLastError() {
    return lastError_;
}

max_stars_repo_name: igor-sadchenko/image-uploader

max_issues_repo_name: igor-sadchenko/image-uploader

max_forks_repo_name: igor-sadchenko/image-uploader


text:
// Copyright (c) 2016-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.

#include <boost/algorithm/hex.hpp>
#include <openssl/md5.h>

#include <chrono>
#include <stdexcept>

#include <folly/GLog.h>

#include <devmand/channels/mikrotik/Channel.h>
#include <devmand/channels/mikrotik/LengthComputation.h>
#include <devmand/utils/EventBaseUtils.h>
#include <devmand/utils/StringUtils.h>

namespace devmand {
namespace channels {
namespace mikrotik {

const constexpr std::chrono::milliseconds connectTimeout(1);
const constexpr std::chrono::seconds retryTime{10};

Channel::Channel(
    folly::EventBase& _eventBase,
    folly::SocketAddress addr,
    const std::string& _username,
    const std::string& _password)
    : eventBase(_eventBase),
      address(addr),
      socket(nullptr),
      state(State::Disconnected),
      reconnect(true),
      username(_username),
      password(_password) {}

Channel::~Channel() {
  reconnect = false;
}

std::string sentenceTerminator{};

void Channel::terminateSentence() {
  writeWordAndLength(sentenceTerminator);
}

void Channel::login() {
  state = State::LoggingIn;
  writeWordAndLength("/login");
  writeWordAndLength(folly::sformat("=name={}", username));
  writeWordAndLength(folly::sformat("=password={}", password));
  terminateSentence();
}

void Channel::loginDeprecated(const std::string& code) {
  LOG(ERROR) << "Logging in with deprecated version";
  state = State::LoggingInDeprecated;

  // Convert the code from a hex string to a binary string
  std::string binaryCode;
  boost::algorithm::unhex(code, std::back_inserter(binaryCode));

  // Concat it with a null and the password.
  std::string concat{"\x00", 1};
  concat.append(password);
  concat.append(binaryCode.c_str(), binaryCode.length());

  // MD5 Sum the concatenation
  unsigned char buffer[MD5_DIGEST_LENGTH];
  MD5(reinterpret_cast<const unsigned char*>(concat.data()),
      concat.size(),
      buffer);

  // Convert the md5 sum into a hex string
  std::string md5;
  boost::algorithm::hex(
      std::string(reinterpret_cast<char*>(buffer), MD5_DIGEST_LENGTH),
      std::back_inserter(md5));

  writeWordAndLength("/login");
  writeWordAndLength(folly::sformat("=name={}", username));
  writeWordAndLength(folly::sformat("=response=00{}", md5));
  writeWordAndLength(sentenceTerminator);
}

void Channel::writeWordAndLength(const Word& word) {
  if (socket != nullptr) {
    write(computeLength(static_cast<uint32_t>(word.length())));
    write(word);
  } else {
    // TODO handle this
  }
}

void Channel::write(const Word& word) {
  debugPrintHex("Outgoing Mikrotik data: ", word);
  assert(socket != nullptr);
  WriteTask task{*this, word};
  auto result = writeTasks.emplace(task.getId(), std::move(task));
  if (result.second) {
    result.first->second.writeTo(socket);
  } else {
    LOG(ERROR) << "failed to write to device";
    // TODO handle error
  }
}

folly::Future<Reply> Channel::write(const Sentence&& sentence) {
  outstandingRequests.emplace_back(folly::Promise<Reply>());
  auto& promise = outstandingRequests.back();
  for (auto& word : sentence) {
    writeWordAndLength(word);
  }
  terminateSentence();
  return promise.getFuture();
}

void Channel::complete(WriteTask::Id id) {
  if (writeTasks.erase(id) != 1) {
    LOG(ERROR) << "failed to completed write task " << id;
  }
}

void Channel::disconnect() {
  if (socket != nullptr) {
    socket = nullptr;
  }
  currentIn.clear();
  state = State::Disconnected;
  clearOutstandingRequests();
}

bool Channel::isConnected() const {
  return state != State::Disconnected;
}

bool Channel::isLoggedIn() const {
  return state == State::FullyConnected;
}

void Channel::connect() {
  if (socket != nullptr) {
    LOG(INFO) << "Socket already connected so not connecting.";
  }

  socket = folly::AsyncSocket::newSocket(&eventBase);
  if (socket != nullptr) {
    socket->connect(this, address, connectTimeout.count());
  } else {
    LOG(ERROR) << "socket new failed";
  }
}

void Channel::connectSuccess() noexcept {
  socket->setReadCB(this);
  login();
}

void Channel::connectErr(const folly::AsyncSocketException& ex) noexcept {
  LOG(ERROR) << "connection error " << ex.what();
  if (socket != nullptr) {
    disconnect();
    tryReconnect();
  }
}

void Channel::tryReconnect() {
  if (reconnect) {
    std::weak_ptr<Channel> weak(this->shared_from_this());
    EventBaseUtils::scheduleIn(
        eventBase,
        [weak]() {
          if (auto shared = weak.lock()) {
            shared->connect();
          }
        },
        retryTime);
  }
}

void Channel::clearOutstandingRequests() {
  for (auto& request : outstandingRequests) {
    request.setValue(Reply{});
  }
  outstandingRequests.clear();
}

void Channel::getReadBuffer(void** bufReturn, size_t* lenReturn) {
  currentBuffer.reserve(maxBuffer);
  *bufReturn = reinterpret_cast<void*>(currentBuffer.data());
  *lenReturn = maxBuffer;
}

void Channel::readDataAvailable(size_t len) noexcept {
  data += std::string(currentBuffer.data(), len);

  handleData();
}

void Channel::debugPrintHex(const std::string& prefix, const std::string& buf) {
  LOG(INFO) << prefix << " " << StringUtils::asHexString(buf, " ");
}

bool Channel::readWord(Word& wordOut) {
  ReadLength length = readLength(data.data(), data.length());
  if (length.lengthSize == 0) {
    LOG(INFO) << "insufficient data to read length";
    return false;
  } else if ((length.contentLength + length.lengthSize) > data.length()) {
    LOG(INFO) << "insufficient data to read entire msg";
    return false;
  } else {
    wordOut =
        std::string{data.data() + length.lengthSize, length.contentLength};
    data = data.substr(
        length.lengthSize + length.contentLength, std::string::npos);
    return true;
  }
}

void Channel::handleData() {
  debugPrintHex("Incoming Mikrotik data: ", data);
  Word word;
  while (readWord(word)) {
    if (word.empty()) {
      LOG(INFO) << "End of sentence";
      if (not handle(currentIn)) {
        LOG(ERROR) << "login failed";
        if (socket != nullptr) {
          disconnect();
          tryReconnect();
        }
      } else {
        currentIn.clear();
      }
    } else {
      LOG(INFO) << "Read word [" << word << "]";
      currentIn.emplace_back(word);
    }
  }
}

bool Channel::handle(const Sentence& sentence) {
  if (sentence.empty()) {
    return false;
  }

  switch (state) {
    case State::LoggingIn:
    case State::LoggingInDeprecated:
      if (sentence.front() == "!done") {
        if (sentence.size() == 1) {
          state = State::FullyConnected;
          writeSentence(currentOut);
          currentOut.clear();
          return true;
        } else if (sentence.size() == 2 and sentence[1].size() > 5) {
          std::string code = sentence[1];
          code = code.substr(5, code.size());
          loginDeprecated(code);
          return true;
        }
      } else {
        // TODO print error msg (=message=error message)
      }
      return false;
    case State::FullyConnected:
      LOG(ERROR) << "handle msg!";
      return true;
    case State::Disconnected:
    default:
      return false;
  }
}

void Channel::readEOF() noexcept {
  LOG(ERROR) << "read eof";
  if (socket != nullptr) {
    disconnect();
    tryReconnect();
  }
}

void Channel::readErr(const folly::AsyncSocketException& ex) noexcept {
  LOG(ERROR) << "read error " << ex.what();
  if (socket != nullptr) {
    disconnect();
    tryReconnect();
  }
}

State Channel::getOperationalDatastore() const {
  return state;
}

void Channel::enableSyslog() {
  // TODO don't just assume success
  writeWordAndLength("/system/logging/action/add");
  writeWordAndLength("=name=syslog");
  writeWordAndLength("=target=remote");
  writeWordAndLength(folly::sformat("=remote={}", "192.168.90.100"));
  terminateSentence();
}

void Channel::writeSentence(const Sentence& sentence) {
  if (state == State::FullyConnected) {
    for (auto& word : sentence) {
      writeWordAndLength(word);
    }
    terminateSentence();
  } else {
    currentOut.insert(currentOut.end(), sentence.begin(), sentence.end());
  }
}

} // namespace mikrotik
} // namespace channels
} // namespace devmand


text: #include <boost/spirit/include/qi_omit.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (c) 2008-2017 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 BOOST_QVM_187092DA6454CEB1853E6915F8466A4
#define BOOST_QVM_187092DA6454CEB1853E6915F8466A4

// This file was generated by a program. Do not edit manually.

#include <boost/qvm/deduce_vec.hpp>
#include <boost/qvm/enable_if.hpp>
#include <boost/qvm/inline.hpp>
#include <boost/qvm/mat_traits.hpp>
#include <boost/qvm/vec_traits.hpp>

namespace boost {
namespace qvm {
template <class A, class B>
BOOST_QVM_INLINE_OPERATIONS
    typename lazy_enable_if_c<mat_traits<A>::rows == 4 &&
                                  mat_traits<A>::cols == 4 &&
                                  vec_traits<B>::dim == 4,
                              deduce_vec2<A, B, 4>>::type
    operator*(A const &a, B const &b) {
  typedef typename mat_traits<A>::scalar_type Ta;
  typedef typename vec_traits<B>::scalar_type Tb;
  Ta const a00 = mat_traits<A>::template read_element<0, 0>(a);
  Ta const a01 = mat_traits<A>::template read_element<0, 1>(a);
  Ta const a02 = mat_traits<A>::template read_element<0, 2>(a);
  Ta const a03 = mat_traits<A>::template read_element<0, 3>(a);
  Ta const a10 = mat_traits<A>::template read_element<1, 0>(a);
  Ta const a11 = mat_traits<A>::template read_element<1, 1>(a);
  Ta const a12 = mat_traits<A>::template read_element<1, 2>(a);
  Ta const a13 = mat_traits<A>::template read_element<1, 3>(a);
  Ta const a20 = mat_traits<A>::template read_element<2, 0>(a);
  Ta const a21 = mat_traits<A>::template read_element<2, 1>(a);
  Ta const a22 = mat_traits<A>::template read_element<2, 2>(a);
  Ta const a23 = mat_traits<A>::template read_element<2, 3>(a);
  Ta const a30 = mat_traits<A>::template read_element<3, 0>(a);
  Ta const a31 = mat_traits<A>::template read_element<3, 1>(a);
  Ta const a32 = mat_traits<A>::template read_element<3, 2>(a);
  Ta const a33 = mat_traits<A>::template read_element<3, 3>(a);
  Tb const b0 = vec_traits<B>::template read_element<0>(b);
  Tb const b1 = vec_traits<B>::template read_element<1>(b);
  Tb const b2 = vec_traits<B>::template read_element<2>(b);
  Tb const b3 = vec_traits<B>::template read_element<3>(b);
  typedef typename deduce_vec2<A, B, 4>::type R;
  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 4);
  R r;
  vec_traits<R>::template write_element<0>(r) =
      a00 * b0 + a01 * b1 + a02 * b2 + a03 * b3;
  vec_traits<R>::template write_element<1>(r) =
      a10 * b0 + a11 * b1 + a12 * b2 + a13 * b3;
  vec_traits<R>::template write_element<2>(r) =
      a20 * b0 + a21 * b1 + a22 * b2 + a23 * b3;
  vec_traits<R>::template write_element<3>(r) =
      a30 * b0 + a31 * b1 + a32 * b2 + a33 * b3;
  return r;
}

namespace sfinae {
using ::boost::qvm::operator*;
}

namespace qvm_detail {
template <int R, int C> struct mul_mv_defined;

template <> struct mul_mv_defined<4, 4> { static bool const value = true; };
} // namespace qvm_detail

template <class A, class B>
BOOST_QVM_INLINE_OPERATIONS
    typename lazy_enable_if_c<mat_traits<B>::rows == 4 &&
                                  mat_traits<B>::cols == 4 &&
                                  vec_traits<A>::dim == 4,
                              deduce_vec2<A, B, 4>>::type
    operator*(A const &a, B const &b) {
  typedef typename vec_traits<A>::scalar_type Ta;
  typedef typename mat_traits<B>::scalar_type Tb;
  Ta const a0 = vec_traits<A>::template read_element<0>(a);
  Ta const a1 = vec_traits<A>::template read_element<1>(a);
  Ta const a2 = vec_traits<A>::template read_element<2>(a);
  Ta const a3 = vec_traits<A>::template read_element<3>(a);
  Tb const b00 = mat_traits<B>::template read_element<0, 0>(b);
  Tb const b01 = mat_traits<B>::template read_element<0, 1>(b);
  Tb const b02 = mat_traits<B>::template read_element<0, 2>(b);
  Tb const b03 = mat_traits<B>::template read_element<0, 3>(b);
  Tb const b10 = mat_traits<B>::template read_element<1, 0>(b);
  Tb const b11 = mat_traits<B>::template read_element<1, 1>(b);
  Tb const b12 = mat_traits<B>::template read_element<1, 2>(b);
  Tb const b13 = mat_traits<B>::template read_element<1, 3>(b);
  Tb const b20 = mat_traits<B>::template read_element<2, 0>(b);
  Tb const b21 = mat_traits<B>::template read_element<2, 1>(b);
  Tb const b22 = mat_traits<B>::template read_element<2, 2>(b);
  Tb const b23 = mat_traits<B>::template read_element<2, 3>(b);
  Tb const b30 = mat_traits<B>::template read_element<3, 0>(b);
  Tb const b31 = mat_traits<B>::template read_element<3, 1>(b);
  Tb const b32 = mat_traits<B>::template read_element<3, 2>(b);
  Tb const b33 = mat_traits<B>::template read_element<3, 3>(b);
  typedef typename deduce_vec2<A, B, 4>::type R;
  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 4);
  R r;
  vec_traits<R>::template write_element<0>(r) =
      a0 * b00 + a1 * b10 + a2 * b20 + a3 * b30;
  vec_traits<R>::template write_element<1>(r) =
      a0 * b01 + a1 * b11 + a2 * b21 + a3 * b31;
  vec_traits<R>::template write_element<2>(r) =
      a0 * b02 + a1 * b12 + a2 * b22 + a3 * b32;
  vec_traits<R>::template write_element<3>(r) =
      a0 * b03 + a1 * b13 + a2 * b23 + a3 * b33;
  return r;
}

namespace sfinae {
using ::boost::qvm::operator*;
}

namespace qvm_detail {
template <int R, int C> struct mul_vm_defined;

template <> struct mul_vm_defined<4, 4> { static bool const value = true; };
} // namespace qvm_detail

} // namespace qvm
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
/**
 * @file split_data_test.cpp
 * @author Tham Ngap Wei
 *
 * Test the SplitData method.
 *
 * mlpack is free software; you may redistribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#include <mlpack/core.hpp>
#include <mlpack/core/data/split_data.hpp>

#include <boost/test/unit_test.hpp>
#include "test_tools.hpp"

using namespace mlpack;
using namespace arma;
using namespace mlpack::data;

BOOST_AUTO_TEST_SUITE(SplitDataTest);

/**
 * Compare the data after train test split.  This assumes that the labels
 * correspond to each column, so that we can easily check each point against its
 * original.
 *
 * @param inputData The original data set before split.
 * @param compareData The data want to compare with the inputData;
 *   it could be train data or test data.
 * @param inputLabel The labels of each point in compareData.
 */
void CompareData(const mat& inputData,
                 const mat& compareData,
                 const Row<size_t>& inputLabel)
{
  for (size_t i = 0; i != compareData.n_cols; ++i)
  {
    const mat& lhsCol = inputData.col(inputLabel(i));
    const mat& rhsCol = compareData.col(i);
    for (size_t j = 0; j != lhsCol.n_rows; ++j)
    {
      if (std::abs(rhsCol(j)) < 1e-5)
        BOOST_REQUIRE_SMALL(lhsCol(j), 1e-5);
      else
        BOOST_REQUIRE_CLOSE(lhsCol(j), rhsCol(j), 1e-5);
    }
  }
}

void CheckMatEqual(const mat& inputData,
                   const mat& compareData)
{
  const mat& sortedInput = arma::sort(inputData, "ascend", 1);
  const mat& sortedCompare = arma::sort(compareData, "ascend", 1);
  for (size_t i = 0; i < sortedInput.n_cols; ++i)
  {
    const mat& lhsCol = sortedInput.col(i);
    const mat& rhsCol = sortedCompare.col(i);
    for (size_t j = 0; j < lhsCol.n_rows; ++j)
    {
      if (std::abs(rhsCol(j)) < 1e-5)
        BOOST_REQUIRE_SMALL(lhsCol(j), 1e-5);
      else
        BOOST_REQUIRE_CLOSE(lhsCol(j), rhsCol(j), 1e-5);
    }
  }
}

/**
 * Check that no labels have been duplicated.
 */
void CheckDuplication(const Row<size_t>& trainLabels,
                      const Row<size_t>& testLabels)
{
  // Assemble a vector that will hold the counts of each element.
  Row<size_t> counts(trainLabels.n_elem + testLabels.n_elem);
  counts.zeros();

  for (size_t i = 0; i < trainLabels.n_elem; ++i)
  {
    BOOST_REQUIRE_LT(trainLabels[i], counts.n_elem);
    counts[trainLabels[i]]++;
  }
  for (size_t i = 0; i < testLabels.n_elem; ++i)
  {
    BOOST_REQUIRE_LT(testLabels[i], counts.n_elem);
    counts[testLabels[i]]++;
  }

  // Now make sure each point has been used once.
  for (size_t i = 0; i < counts.n_elem; ++i)
    BOOST_REQUIRE_EQUAL(counts[i], 1);
}

BOOST_AUTO_TEST_CASE(SplitDataResultMat)
{
  mat input(2, 10);
  size_t count = 0; // count for putting unique sequential values
  input.imbue([&count] () { return ++count; });

  const auto value = Split(input, 0.2);
  BOOST_REQUIRE_EQUAL(std::get<0>(value).n_cols, 8); // train data
  BOOST_REQUIRE_EQUAL(std::get<1>(value).n_cols, 2); // test data

  mat concat = arma::join_rows(std::get<0>(value), std::get<1>(value));
  CheckMatEqual(input, concat);
}

BOOST_AUTO_TEST_CASE(SplitLabeledDataResultMat)
{
  mat input(2, 10);
  input.randu();

  // Set the labels to the column ID, so that CompareData can compare the data
  // after Split is called.
  const Row<size_t> labels = arma::linspace<Row<size_t>>(0, input.n_cols - 1,
      input.n_cols);

  const auto value = Split(input, labels, 0.2);
  BOOST_REQUIRE_EQUAL(std::get<0>(value).n_cols, 8);
  BOOST_REQUIRE_EQUAL(std::get<1>(value).n_cols, 2);
  BOOST_REQUIRE_EQUAL(std::get<2>(value).n_cols, 8);
  BOOST_REQUIRE_EQUAL(std::get<3>(value).n_cols, 2);

  CompareData(input, std::get<0>(value), std::get<2>(value));
  CompareData(input, std::get<1>(value), std::get<3>(value));

  // The last thing to check is that we aren't duplicating any points in the
  // train or test labels.
  CheckDuplication(std::get<2>(value), std::get<3>(value));
}

/**
 * The same test as above, but on a larger dataset.
 */
BOOST_AUTO_TEST_CASE(SplitDataLargerTest)
{
  size_t count = 0;
  mat input(10, 497);
  input.imbue([&count] () { return ++count; });

  const auto value = Split(input, 0.3);
  BOOST_REQUIRE_EQUAL(std::get<0>(value).n_cols, 497 - size_t(0.3 * 497));
  BOOST_REQUIRE_EQUAL(std::get<1>(value).n_cols, size_t(0.3 * 497));

  mat concat = arma::join_rows(std::get<0>(value), std::get<1>(value));
  CheckMatEqual(input, concat);
}

BOOST_AUTO_TEST_CASE(SplitLabeledDataLargerTest)
{
  mat input(10, 497);
  input.randu();

  // Set the labels to the column ID.
  const Row<size_t> labels = arma::linspace<Row<size_t>>(0, input.n_cols - 1,
      input.n_cols);

  const auto value = Split(input, labels, 0.3);
  BOOST_REQUIRE_EQUAL(std::get<0>(value).n_cols, 497 - size_t(0.3 * 497));
  BOOST_REQUIRE_EQUAL(std::get<1>(value).n_cols, size_t(0.3 * 497));
  BOOST_REQUIRE_EQUAL(std::get<2>(value).n_cols, 497 - size_t(0.3 * 497));
  BOOST_REQUIRE_EQUAL(std::get<3>(value).n_cols, size_t(0.3 * 497));

  CompareData(input, std::get<0>(value), std::get<2>(value));
  CompareData(input, std::get<1>(value), std::get<3>(value));

  CheckDuplication(std::get<2>(value), std::get<3>(value));
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: RMaron/mlpack

max_issues_repo_name: RMaron/mlpack

max_forks_repo_name: RMaron/mlpack


text:
/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2013, PAL Robotics, S.L.
 *  All rights reserved.
 *
 *	Copyright (c) 20135, NWPU
 *	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 the PAL Robotics 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 OWNER 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.
 *********************************************************************/

/*
 * Author:Luke Liao
 */

#include <tf/transform_datatypes.h>

//#include <urdf_parser/urdf_parser.h>

#include <boost/assign.hpp>

#include <omni_triangle_controller.h>
/*
static double euclideanOfVectors(const urdf::Vector3& vec1, const urdf::Vector3& vec2)
{
	return std::sqrt(std::pow(vec1.x-vec2.x,2) +
			std::pow(vec1.y-vec2.y,2) +
			std::pow(vec1.z-vec2.z,2));
}
*/
/*
 * \brief Check if the link is modeled as a cylinder
 * \param link Link
 * \return true if the link is modeled as a Cylinder; false otherwise
 */
//static bool isCylinder(const boost::shared_ptr<const urdf::Link>& link)
//{
//	if(!link)
//	{
//		ROS_ERROR("Link == NULL.");
//		return false;
//	}
//
//	if(!link->collision)
//	{
//		ROS_ERROR_STREAM("Link " << link->name << " does not have collision description. Add collision description for link to urdf.");
//		return false;
//	}
//
//	if(!link->collision->geometry)
//	{
//		ROS_ERROR_STREAM("Link " << link->name << " does not have collision geometry description. Add collision geometry description for link to urdf.");
//		return false;
//	}
//
//	if(link->collision->geometry->type != urdf::Geometry::CYLINDER)
//	{
//		ROS_ERROR_STREAM("Link " << link->name << " does not have cylinder geometry");
//		return false;
//	}
//
//	return true;
//}
//
///*
// * \brief Get the wheel radius
// * \param [in]  wheel_link   Wheel link
// * \param [out] wheel_radius Wheel radius [m]
// * \return true if the wheel radius was found; false otherwise
// */
//static bool getWheelRadius(const boost::shared_ptr<const urdf::Link>& wheel_link, double& wheel_radius)
//{
//	if(!isCylinder(wheel_link))
//	{
//		ROS_ERROR_STREAM("Wheel link " << wheel_link->name << " is NOT modeled as a cylinder!");
//		return false;
//	}
//
//	wheel_radius = (static_cast<urdf::Cylinder*>(wheel_link->collision->geometry.get()))->radius;
//	return true;
//}

namespace omni_triangle_controller{

OmniDriveController::OmniDriveController()
: open_loop_(false)
, command_struct_()
, wheel_center_(0.0)
, wheel_radius_(0.0)
, cmd_vel_timeout_(0.5)
, base_frame_id_("base_link")
, enable_odom_tf_(true)
{
}

bool OmniDriveController::init(hardware_interface::VelocityJointInterface* hw,
		ros::NodeHandle& root_nh,
		ros::NodeHandle &controller_nh)
{
	const std::string complete_ns = controller_nh.getNamespace();
	std::size_t id = complete_ns.find_last_of("/");
	name_ = complete_ns.substr(id + 1);

	// Get joint names from the parameter server
	if (!getWheelNames(controller_nh, "wheel1", wheel1_name) ||
			!getWheelNames(controller_nh, "wheel2", wheel2_name) ||
			!getWheelNames(controller_nh, "wheel3", wheel3_name))
	{
		return false;
	}

	// Odometry related:
	double publish_rate;
	controller_nh.param("publish_rate", publish_rate, 20.0);
	ROS_INFO_STREAM_NAMED(name_, "Controller state will be published at "
			<< publish_rate << "Hz.");
	publish_period_ = ros::Duration(1.0 / publish_rate);

	// Twist command related:
	controller_nh.param("cmd_vel_timeout", cmd_vel_timeout_, cmd_vel_timeout_);
	ROS_INFO_STREAM_NAMED(name_, "Velocity commands will be considered old if they are older than "
			<< cmd_vel_timeout_ << "s.");

	controller_nh.param("base_frame_id", base_frame_id_, base_frame_id_);
	ROS_INFO_STREAM_NAMED(name_, "Base frame_id set to " << base_frame_id_);

	controller_nh.param("enable_odom_tf", enable_odom_tf_, enable_odom_tf_);
	ROS_INFO_STREAM_NAMED(name_, "Publishing to tf is " << (enable_odom_tf_?"enabled":"disabled"));

	// Velocity and acceleration limits:
	controller_nh.param("linear/x/has_velocity_limits"    , limiter_linear_x_.has_velocity_limits    , limiter_linear_x_.has_velocity_limits    );
	controller_nh.param("linear/x/has_acceleration_limits", limiter_linear_x_.has_acceleration_limits, limiter_linear_x_.has_acceleration_limits);
	controller_nh.param("linear/x/max_velocity"           , limiter_linear_x_.max_velocity           ,  limiter_linear_x_.max_velocity          );
	controller_nh.param("linear/x/min_velocity"           , limiter_linear_x_.min_velocity           , -limiter_linear_x_.max_velocity          );
	controller_nh.param("linear/x/max_acceleration"       , limiter_linear_x_.max_acceleration       ,  limiter_linear_x_.max_acceleration      );
	controller_nh.param("linear/x/min_acceleration"       , limiter_linear_x_.min_acceleration       , -limiter_linear_x_.max_acceleration      );

	controller_nh.param("linear/y/has_velocity_limits"    , limiter_linear_y_.has_velocity_limits    , limiter_linear_y_.has_velocity_limits    );
	controller_nh.param("linear/y/has_acceleration_limits", limiter_linear_y_.has_acceleration_limits, limiter_linear_y_.has_acceleration_limits);
	controller_nh.param("linear/y/max_velocity"           , limiter_linear_y_.max_velocity           ,  limiter_linear_y_.max_velocity          );
	controller_nh.param("linear/y/min_velocity"           , limiter_linear_y_.min_velocity           , -limiter_linear_y_.max_velocity          );
	controller_nh.param("linear/y/max_acceleration"       , limiter_linear_y_.max_acceleration       ,  limiter_linear_y_.max_acceleration      );
	controller_nh.param("linear/y/min_acceleration"       , limiter_linear_y_.min_acceleration       , -limiter_linear_y_.max_acceleration      );

	controller_nh.param("angular/z/has_velocity_limits"    , limiter_angular_.has_velocity_limits    , limiter_angular_.has_velocity_limits    );
	controller_nh.param("angular/z/has_acceleration_limits", limiter_angular_.has_acceleration_limits, limiter_angular_.has_acceleration_limits);
	controller_nh.param("angular/z/max_velocity"           , limiter_angular_.max_velocity           ,  limiter_angular_.max_velocity          );
	controller_nh.param("angular/z/min_velocity"           , limiter_angular_.min_velocity           , -limiter_angular_.max_velocity          );
	controller_nh.param("angular/z/max_acceleration"       , limiter_angular_.max_acceleration       ,  limiter_angular_.max_acceleration      );
	controller_nh.param("angular/z/min_acceleration"       , limiter_angular_.min_acceleration       , -limiter_angular_.max_acceleration      );

	if (!setOdomParamsFromUrdf(root_nh, wheel1_name, wheel2_name, wheel3_name))
		return false;

	setOdomPubFields(root_nh, controller_nh);

	// Get the joint object to use in the realtime loop
	wheel1_joint = hw->getHandle(wheel1_name);  // throws on failure
	wheel2_joint = hw->getHandle(wheel2_name);  // throws on failure
	wheel3_joint = hw->getHandle(wheel3_name);

	sub_command_ = controller_nh.subscribe("cmd_vel", 1, &OmniDriveController::cmdVelCallback, this);
	ROS_INFO("wocao");
	return true;
}

void OmniDriveController::update(const ros::Time& time, const ros::Duration& period)
{
	//get the wheel velocity from the handle
	double wheel1_vel = wheel1_joint.getVelocity();
	double wheel2_vel = wheel2_joint.getVelocity();
	double wheel3_vel = wheel3_joint.getVelocity();

	// Estimate linear and angular velocity using joint information
			odometry_.update(wheel1_vel, wheel2_vel, wheel3_vel, time);

			// Publish odometry message
			if(last_state_publish_time_ + publish_period_ < time)
			{
				last_state_publish_time_ += publish_period_;
				// Compute and store orientation info
				const geometry_msgs::Quaternion orientation(
						tf::createQuaternionMsgFromYaw(odometry_.getHeading()));

				// Populate odom message and publish
				if(odom_pub_->trylock())
				{
					odom_pub_->msg_.header.stamp = time;
					odom_pub_->msg_.pose.pose.position.x = odometry_.getX();
					odom_pub_->msg_.pose.pose.position.y = odometry_.getY();
					odom_pub_->msg_.pose.pose.orientation = orientation;
					odom_pub_->msg_.twist.twist.linear.x  = odometry_.getLinearX();
					odom_pub_->msg_.twist.twist.linear.y  = odometry_.getLinearY();
					odom_pub_->msg_.twist.twist.angular.z = odometry_.getAngular();
					odom_pub_->unlockAndPublish();
				}

				// Publish tf /odom frame
				if (enable_odom_tf_ && tf_odom_pub_->trylock())
				{
					geometry_msgs::TransformStamped& odom_frame = tf_odom_pub_->msg_.transforms[0];
					odom_frame.header.stamp = time;
					odom_frame.transform.translation.x = odometry_.getX();
					odom_frame.transform.translation.y = odometry_.getY();
					odom_frame.transform.rotation = orientation;
					tf_odom_pub_->unlockAndPublish();
				}
			}

			// MOVE ROBOT
			// Retreive current velocity command and time step:
			Commands curr_cmd = *(command_.readFromRT());
			const double dt = (time - curr_cmd.stamp).toSec();

			// Brake if cmd_vel has timeout:
			if (dt > cmd_vel_timeout_)
			{
				ROS_INFO("wocao nima");
				curr_cmd.linear_x = 0.0;
				curr_cmd.linear_y = 0.0;
				curr_cmd.angular = 0.0;
			}

			// Limit velocities and accelerations:
			const double cmd_dt(period.toSec());
			limiter_linear_x_.limit(curr_cmd.linear_x, last_cmd_.linear_x, cmd_dt);
			limiter_linear_y_.limit(curr_cmd.linear_y, last_cmd_.linear_y, cmd_dt);
			limiter_angular_. limit(curr_cmd.angular,  last_cmd_.angular,  cmd_dt);
			last_cmd_ = curr_cmd;

			// Compute wheels velocities:
			const double vth = curr_cmd.angular, vx = - curr_cmd.linear_x, vy = curr_cmd.linear_y;
			const double psi = 2 * 3.14159265 / 3;
			const double L = wheel_center_;

			const double wheel1_cmd  = (L*vth - vy) / wheel_radius_;
			const double wheel2_cmd  = (L*vth + vy*cos(psi/2) - vx*sin(psi/2)) / wheel_radius_;
			const double wheel3_cmd  = (L*vth + vy*cos(psi/2) + vx*sin(psi/2)) / wheel_radius_;

			ROS_INFO("send velocity is %f %f %f", wheel1_cmd,wheel2_cmd,wheel3_cmd);

			//ROS_INFO("the velocity is %f  %f  %f", wheel1_cmd, wheel2_cmd, wheel3_cmd);

			wheel1_joint.setCommand(wheel1_cmd);
			wheel2_joint.setCommand(wheel2_cmd);
			wheel3_joint.setCommand(wheel3_cmd);
}

void OmniDriveController::starting(const ros::Time& time)
{
	brake();

    // Register starting time used to keep fixed rate
    last_state_publish_time_ = time;

#if ROS_VERSION_MINOR < 15
    state_ = RUNNING;
#else
    state_ = ControllerState::RUNNING;
#endif

    odometry_.init(time);
}

void OmniDriveController::stopping(const ros::Time& time)
{
	brake();
}

void OmniDriveController::brake()
{
	const double vel = 0.0;
	ROS_INFO("wocao");
	wheel1_joint.setCommand(vel);
	wheel2_joint.setCommand(vel);
	wheel3_joint.setCommand(vel);
}

void OmniDriveController::cmdVelCallback(const geometry_msgs::Twist& command)
{
	if(isRunning())
	{
		command_struct_.angular    = command.angular.z;
		command_struct_.linear_x   = command.linear.x;
		command_struct_.linear_y   = command.linear.y;
		command_struct_.stamp = ros::Time::now();
		command_.writeFromNonRT (command_struct_);
		ROS_DEBUG_STREAM_NAMED(name_,
				"Added values to command. "
				<< "Ang: "   << command_struct_.angular << ", "
				<< "Lin x: "   << command_struct_.linear_x << ", "
				<< "Lin y: "   << command_struct_.linear_y << ", "
				<< "Stamp: " << command_struct_.stamp);
	}
	else
	{
		ROS_ERROR_NAMED(name_, "Can't accept new commands. Controller is not running.");
	}
}

bool OmniDriveController::getWheelNames(ros::NodeHandle& controller_nh,
		const std::string& wheel_param,
		std::string& wheel_name)
{
	XmlRpc::XmlRpcValue wheel_list;
	if (!controller_nh.getParam(wheel_param, wheel_list))
	{
		ROS_ERROR_STREAM_NAMED(name_,
				"Couldn't retrieve wheel param '" << wheel_param << "'.");
		return false;
	}

	if (wheel_list.getType() != XmlRpc::XmlRpcValue::TypeString)
	{
		ROS_ERROR_STREAM_NAMED(name_,
				"Wheel param '" << wheel_param << "' #" <<
				" isn't a string.");
		return false;
	}

	wheel_name = static_cast<std::string>(wheel_list);
	return true;
}

bool OmniDriveController::setOdomParamsFromUrdf(ros::NodeHandle& root_nh,
		const std::string& wheel1_name,
		const std::string& wheel2_name,
		const std::string& wheel3_name)
{
	// Parse robot description
//	const std::string model_param_name = "robot_description";
//	bool res = root_nh.hasParam(model_param_name);
//	std::string robot_model_str="";
//	if(!res || !root_nh.getParam(model_param_name,robot_model_str))
//	{
//		ROS_ERROR_NAMED(name_, "Robot descripion couldn't be retrieved from param server.");
//		return false;
//	}
//
//	boost::shared_ptr<urdf::ModelInterface> model(urdf::parseURDF(robot_model_str));
//
//	//check the wheel information in the urdf
//	boost::shared_ptr<const urdf::Joint> wheel1(model->getJoint(wheel1_name));
//	if(!wheel1)
//	{
//		ROS_ERROR_STREAM_NAMED(name_, wheel1
//				<< " couldn't be retrieved from model description");
//		return false;
//	}
//
//	boost::shared_ptr<const urdf::Joint> wheel2(model->getJoint(wheel2_name));
//	if(!wheel2)
//	{
//		ROS_ERROR_STREAM_NAMED(name_, wheel2
//				<< " couldn't be retrieved from model description");
//		return false;
//	}
//
//	boost::shared_ptr<const urdf::Joint> wheel3(model->getJoint(wheel3_name));
//	if(!wheel3)
//	{
//		ROS_ERROR_STREAM_NAMED(name_, wheel3
//				<< " couldn't be retrieved from model description");
//		return false;
//	}
//
//	ROS_INFO_STREAM("wheel1 to origin: " << wheel1->parent_to_joint_origin_transform.position.x << ","
//			<< wheel1->parent_to_joint_origin_transform.position.y << ", "
//			<< wheel1->parent_to_joint_origin_transform.position.z);
//	ROS_INFO_STREAM("wheel2 to origin: " << wheel2->parent_to_joint_origin_transform.position.x << ","
//			<< wheel2->parent_to_joint_origin_transform.position.y << ", "
//			<< wheel2->parent_to_joint_origin_transform.position.z);
//	ROS_INFO_STREAM("wheel3 to origin: " << wheel3->parent_to_joint_origin_transform.position.x << ","
//			<< wheel3->parent_to_joint_origin_transform.position.y << ", "
//			<< wheel3->parent_to_joint_origin_transform.position.z);
//
//	wheel_center_  = sqrt(wheel1->parent_to_joint_origin_transform.position.x * wheel1->parent_to_joint_origin_transform.position.x +
//			wheel1->parent_to_joint_origin_transform.position.y * wheel1->parent_to_joint_origin_transform.position.y +
//			wheel1->parent_to_joint_origin_transform.position.z * wheel1->parent_to_joint_origin_transform.position.z);

	// Get wheel radius
//	if(!getWheelRadius(model->getLink(wheel1->child_link_name), wheel_radius_))
//	{
//		ROS_ERROR_STREAM_NAMED(name_, "Couldn't retrieve " << wheel1_name << " wheel radius");
//		return false;
//	}

	wheel_radius_ = 0.1016 / 2;
	wheel_center_ = 0.1924;

	// Set wheel params for the odometry computation
	odometry_.setWheelParams(wheel_center_, wheel_radius_);
	ROS_INFO_STREAM_NAMED(name_,
			"Odometry params : wheel center " << wheel_center_
			<< ", wheel radius " << wheel_radius_);
	return true;
}

void OmniDriveController::setOdomPubFields(ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh)
{
	/*
    // Get and check params for covariances
    XmlRpc::XmlRpcValue pose_cov_list;
    controller_nh.getParam("pose_covariance_diagonal", pose_cov_list);
    ROS_ASSERT(pose_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
    ROS_ASSERT(pose_cov_list.size() == 6);
    for (int i = 0; i < pose_cov_list.size(); ++i)
      ROS_ASSERT(pose_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);

    XmlRpc::XmlRpcValue twist_cov_list;
    controller_nh.getParam("twist_covariance_diagonal", twist_cov_list);
    ROS_ASSERT(twist_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
    ROS_ASSERT(twist_cov_list.size() == 6);
    for (int i = 0; i < twist_cov_list.size(); ++i)
      ROS_ASSERT(twist_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);*/

	// Setup odometry realtime publisher + odom message constant fields
	odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100));
	odom_pub_->msg_.header.frame_id = "odom";
	odom_pub_->msg_.child_frame_id = base_frame_id_;
	odom_pub_->msg_.pose.pose.position.z = 0;
	/*odom_pub_->msg_.pose.covariance = boost::assign::list_of
        (static_cast<double>(pose_cov_list[0])) (0)  (0)  (0)  (0)  (0)
        (0)  (static_cast<double>(pose_cov_list[1])) (0)  (0)  (0)  (0)
        (0)  (0)  (static_cast<double>(pose_cov_list[2])) (0)  (0)  (0)
        (0)  (0)  (0)  (static_cast<double>(pose_cov_list[3])) (0)  (0)
        (0)  (0)  (0)  (0)  (static_cast<double>(pose_cov_list[4])) (0)
        (0)  (0)  (0)  (0)  (0)  (static_cast<double>(pose_cov_list[5]));*/
	odom_pub_->msg_.twist.twist.linear.z  = 0;
	odom_pub_->msg_.twist.twist.angular.x = 0;
	odom_pub_->msg_.twist.twist.angular.y = 0;
	/* odom_pub_->msg_.twist.covariance = boost::assign::list_of
        (static_cast<double>(twist_cov_list[0])) (0)  (0)  (0)  (0)  (0)
        (0)  (static_cast<double>(twist_cov_list[1])) (0)  (0)  (0)  (0)
        (0)  (0)  (static_cast<double>(twist_cov_list[2])) (0)  (0)  (0)
        (0)  (0)  (0)  (static_cast<double>(twist_cov_list[3])) (0)  (0)
        (0)  (0)  (0)  (0)  (static_cast<double>(twist_cov_list[4])) (0)
        (0)  (0)  (0)  (0)  (0)  (static_cast<double>(twist_cov_list[5]));*/
	//TODO: add the convarience matrix to the omni base
	tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(root_nh, "/tf", 100));
	tf_odom_pub_->msg_.transforms.resize(1);
	tf_odom_pub_->msg_.transforms[0].transform.translation.z = 0.0;
	tf_odom_pub_->msg_.transforms[0].child_frame_id = base_frame_id_;
	tf_odom_pub_->msg_.transforms[0].header.frame_id = "odom";
}

} // namespace diff_drive_controller

max_stars_repo_name: HANDS-FREE/handsfree

max_issues_repo_name: HANDS-FREE/handsfree

max_forks_repo_name: HANDS-FREE/handsfree


text:
#pragma once

//
// Standard C++
//

#include <cassert>
#include <ctime>
#include <cstring>
#include <memory>
#include <algorithm>
#include <random>
#include <chrono>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <unordered_map>
#include <queue>

// Functions that have different names on different platforms.
// Some of them are not included in C++ Standard, but are part of UNIX.
#if defined(_WIN32) || defined(_WIN64)
    #define strcasecmp _stricmp
#endif

//
// Dependencies
//

// Boost
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/tokenizer.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/crc.hpp>
#include <boost/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>

// GLM
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>

// SDL
#include <SDL.h>

// GLEW
#define GLEW_STATIC
#include <GL/glew.h>

// FreeType
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_BITMAP_H

// Lua
#include <lua.hpp>

// LuaBridge
#include <LuaBridge/LuaBridge.h>
namespace Lua = luabridge;

// UTF8
#include <utf8.h>

//
// Project
//

#include "Common/NonCopyable.hpp"
#include "Common/ScopeGuard.hpp"
#include "Common/Utility.hpp"

#include "Logger/Logger.hpp"

#include "Console/ConsoleCommand.hpp"
#include "Console/ConsoleVariable.hpp"

//
// Debug
//

// Memory leak detection.
#if defined(_WINDOWS) && defined(_DEBUG)
    #define _CRTDBG_MAP_ALLOC
    #define _CRTDBG_MAP_ALLOC_NEW
    #include <stdlib.h>
    #include <crtdbg.h>

    #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
    #define new DEBUG_NEW
#endif

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
#pragma once
#include <string>
#include <memory>
#include <unordered_map>
#include <Eigen/Dense>
#include "NeuronScene.hpp"
#include "SwcLoader.hpp"
#include "SwcNode.hpp"
#include "../render/Scene.hpp"
#include "../render/object/SdfSphere.hpp"
#include "../render/object/SdfRoundCone.hpp"
#include "../render/material/Material.hpp"
#include "../render/material/MaterialDiffuse.hpp"

class NeuronScene : public Scene
{
public:
    void load(std::string filepath)
    {
        auto root = SwcLoader::load(filepath);
        if (!root)
            return;

        add_swc_tree(root, nullptr);
    };

private:
    std::unordered_map<std::string, std::shared_ptr<Material>> materials
    {
        {"White",   std::make_unique<MaterialDiffuse>(Eigen::Vector3f{ 0.0, 0.0, 0.0 })},
        {"Red",     std::make_unique<MaterialDiffuse>(Eigen::Vector3f{ 1.0, 0.0, 0.0 })},
        {"Green",   std::make_unique<MaterialDiffuse>(Eigen::Vector3f{ 0.0, 1.0, 0.0 })},
        {"Blue",    std::make_unique<MaterialDiffuse>(Eigen::Vector3f{ 0.0, 0.0, 1.0 })}
    };

    void add_swc_tree(const std::unique_ptr<SwcNode> &root, const std::unique_ptr<SwcNode> &parent)
    {
        if (parent)
            add(std::move(create_cone(root, parent)));
        else if (!root->child)
            add(std::move(create_root(root)));

        if (root->next)
            add_swc_tree(root->next, parent);

        if (root->child)
            add_swc_tree(root->child, root);
    };

    std::unique_ptr<Object> create_cone(const std::unique_ptr<SwcNode>& root, const std::unique_ptr<SwcNode>& parent)
    {
        auto roundCone = std::make_unique<SdfRoundCone>(
            Eigen::Vector3f(root->x, root->y, root->z),
            Eigen::Vector3f(parent->x, parent->y, parent->z),
            root->raidus,
            parent->raidus);
        roundCone->set_material(materials["Red"]);
        return roundCone;
    }

    std::unique_ptr<Object> create_root(const std::unique_ptr<SwcNode>& root)
    {
        auto sphere = std::make_unique<SdfSphere>(
            Eigen::Vector3f{ root->x, root->y, root->z },
            root->raidus);
        sphere->set_material(materials["Green"]);
        return sphere;
    }
};


text:
///////////////////////////////////////////////////////////////////////////////
/// \file for_each.hpp
/// Invokes a \c TernaryFunction for each run in an \c InfiniteRangeRunStorage
//
//  Copyright 2006 Eric Niebler. 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_RANGE_RUN_STORAGE_ALGORITHM_FOR_EACH_EAN_08_04_2006_HPP
#define BOOST_RANGE_RUN_STORAGE_ALGORITHM_FOR_EACH_EAN_08_04_2006_HPP

#include <boost/range_run_storage/algorithm/detail/placeholders.hpp>
#include <boost/range_run_storage/algorithm/detail/transform.hpp>

namespace boost { namespace range_run_storage
{
    namespace rrs = range_run_storage;

    namespace detail
    {
        template<typename Fun>
        struct functor_inserter
        {
            functor_inserter(Fun const &fun)
              : fun(fun)
            {}

            template<typename Run, typename Value>
            void set_at(Run &run, Value &value)
            {
                this->fun(value, rrs::offset(run), rrs::end_offset(run));
            }

            Fun fun;
        };
    }

    /// \brief Invokes the specified \c TernaryFunction for each
    ///     (value, offset, end_offset) tuple in an \c InfiniteRangeRunStorage.
    ///
    /// Invokes the specified \c TernaryFunction for each
    ///     (value, offset, end_offset) tuple in an \c InfiniteRangeRunStorage.
    ///     The functor \c fun is invoked \e N times, where \e N is the number
    ///     of runs in the \c InfiniteRangeRunStorage.
    /// \param[in] in The input \c InfiniteRangeRunStorage.
    /// \param fun An \c TernaryFunction to be invoked with each
    ///     (value, offset, end_offset) tuple in the sequence.
    /// \return A copy of \c fun.
    /// \pre \c In is a model of \c InfiniteRangeRunStorage.
    /// \pre \c Fun is a model of \c TernaryFunction.
    template<typename In, typename Fun>
    Fun for_each(In &in, Fun fun)
    {
        detail::functor_inserter<Fun> out(fun);
        return detail::transform_impl(in, rrs::_1, out).fun;
    }

    /// \overload
    ///
    template<typename In, typename Fun>
    Fun for_each(In const &in, Fun fun)
    {
        detail::functor_inserter<Fun> out(fun);
        return detail::transform_impl(in, rrs::_1, out).fun;
    }

}}

#endif


text:
//
// Copyright (c) 2009, Markus Rickert
// 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.
//
// 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.
//

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <rl/math/Polynomial.h>

int
main(int argc, char** argv)
{
	if (argc < 2)
	{
		std::cout << "Usage: rlPolynomialRootsDemo C0 ... CN" << std::endl;
		return EXIT_FAILURE;
	}

	std::vector<rl::math::Real> c(argc - 1);

	for (std::size_t i = 0; i < c.size(); ++i)
	{
		c[i] = boost::lexical_cast<rl::math::Real>(argv[i + 1]);
		std::cout << (i > 0 ? " + " : "") << c[i] << " * x^" << i;
	}

	std::cout << " = 0" << std::endl;

	std::vector<rl::math::Real> roots = rl::math::Polynomial<rl::math::Real>::realRoots(c);

	std::cout << roots.size() << " solution" << (roots.size() != 1 ? "(s)" : "") << std::endl;

	for (std::size_t i = 0; i < roots.size(); ++i)
	{
		std::cout << "x[" << i << "] = " << roots[i] << std::endl;
	}

	return EXIT_SUCCESS;
}

max_stars_repo_name: Broekman/rl

max_issues_repo_name: jencureboy/rl

max_forks_repo_name: jencureboy/rl


text:
//
// Created by Przemek on 19.01.2020.
//
#include <boost/test/unit_test.hpp>
#include "Player/Move.h"
#include "Player/Previous_Move.h"
#include "Pieces/Piece.h"
#include "Pieces/Pawn.h"
#include "Field.h"

BOOST_AUTO_TEST_SUITE(MoveTestSuite)

BOOST_AUTO_TEST_CASE(MoveTest1) {
    Position pos1(1,1);
    Position pos2(3,3);
    std::shared_ptr<Move> test_move1 = std::make_shared<Move>(pos1, pos2);
    BOOST_CHECK(test_move1->get_beg_pos() == pos1);
    BOOST_CHECK(test_move1->get_end_pos() == pos2);
}

BOOST_AUTO_TEST_CASE(Previous_MoveTest1) {
        Position pos1(1,1);
        Position pos2(3,3);
        std::shared_ptr<Field> test_field_1 = std::make_shared<Field>(pos1);
        std::shared_ptr<Field> test_field_2 = std::make_shared<Field>(pos2);
        std::shared_ptr<Piece> test_pawn1 = std::make_shared<Pawn>(true);
        std::shared_ptr<Piece> test_pawn2 = std::make_shared<Pawn>(false);
        test_pawn1->set_field(test_field_1);
        test_pawn2->set_field(test_field_2);
        std::shared_ptr<Previous_Move> test_p_move1 = std::make_shared<Previous_Move>(pos1, pos2, test_pawn1, test_pawn2);
        BOOST_CHECK(test_p_move1->get_beg_pos() == pos1);
        BOOST_CHECK(test_p_move1->get_end_pos() == pos2);
        BOOST_CHECK(test_pawn1 == test_p_move1->get_piece_in_beg_position());
        BOOST_CHECK(test_pawn2 == test_p_move1->get_piece_in_end_position());
    }

BOOST_AUTO_TEST_SUITE_END()


text:
#include <gtest/gtest.h>
#include <phasar/DB/Hexastore.h>

#include <algorithm>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/isomorphism.hpp>
#include <iostream>

using namespace psr;
using namespace std;

TEST(HexastoreTest, QueryBlankFieldEntries) {
  Hexastore H("QueryBlankFieldEntries.sqlite");
  H.put({{"one", "", ""}});
  H.put({{"two", "", ""}});
  H.put({{"", "three", ""}});
  H.put({{"one", "", "four"}});

  // query results
  hs_result FirstRes("one", "", "");
  hs_result SecondRes("one", "", "four");

  auto Result = H.get({{"one", "", ""}});
  ASSERT_EQ(Result.size(), 1);
  ASSERT_EQ(Result[0], FirstRes);

  Result = H.get({{"one", "?", "?"}});
  ASSERT_EQ(Result.size(), 2);
  ASSERT_EQ(Result[0], FirstRes);
  ASSERT_EQ(Result[1], SecondRes);
}

TEST(HexastoreTest, AllQueryTypes) {
  Hexastore H("AllQueryTypes.sqlite");
  H.put({{"mary", "likes", "hexastores"}});
  H.put({{"mary", "likes", "apples"}});
  H.put({{"mary", "hates", "oranges"}});
  H.put({{"peter", "likes", "apples"}});
  H.put({{"peter", "hates", "hexastores"}});
  H.put({{"frank", "admires", "bananas"}});

  std::vector<hs_result> GroundTruth;
  GroundTruth.emplace_back(hs_result("mary", "likes", "hexastores"));
  GroundTruth.emplace_back(hs_result("mary", "likes", "apples"));
  GroundTruth.emplace_back(hs_result("mary", "hates", "oranges"));
  GroundTruth.emplace_back(hs_result("peter", "likes", "apples"));
  GroundTruth.emplace_back(hs_result("peter", "hates", "hexastores"));
  GroundTruth.emplace_back(hs_result("frank", "admires", "bananas"));

  // Does peter hate hexastores? (SPO query in 'spo' tables)
  auto Result = H.get({{"peter", "hates", "hexastores"}});
  ASSERT_EQ(Result.size(), 1);
  ASSERT_EQ(Result[0], GroundTruth[4]);

  // What does Mary like? (SPX query in 'spo' tables)
  Result = H.get({{"mary", "likes", "?"}});
  ASSERT_EQ(Result.size(), 2);
  ASSERT_EQ(Result[0], GroundTruth[0]);
  ASSERT_EQ(Result[1], GroundTruth[1]);

  // What's Franks opinion on bananas? (SXO query in 'sop' tables)
  Result = H.get({{"frank", "?", "bananas"}});
  ASSERT_EQ(Result.size(), 1);
  ASSERT_EQ(Result[0], GroundTruth[5]);

  // Who likes apples? (XPO query in 'pos' tables)
  Result = H.get({{"?", "likes", "apples"}});
  ASSERT_EQ(Result.size(), 2);
  ASSERT_EQ(Result[0], GroundTruth[1]);
  ASSERT_EQ(Result[1], GroundTruth[3]);

  // What's Marry up to? (SXX query in 'spo' tables)
  Result = H.get({{"mary", "?", "?"}});
  ASSERT_EQ(Result.size(), 3);
  ASSERT_EQ(Result[0], GroundTruth[0]);
  ASSERT_EQ(Result[1], GroundTruth[1]);
  ASSERT_EQ(Result[2], GroundTruth[2]);

  // Who likes what? (XPX query in 'pso' tables)
  Result = H.get({{"?", "likes", "?"}});
  ASSERT_EQ(Result.size(), 3);
  ASSERT_EQ(Result[0], GroundTruth[0]);
  ASSERT_EQ(Result[1], GroundTruth[1]);
  ASSERT_EQ(Result[2], GroundTruth[3]);

  // Who has what opinion on apples? (XXO query in 'osp' tables)
  Result = H.get({{"?", "?", "apples"}});
  ASSERT_EQ(Result.size(), 2);
  ASSERT_EQ(Result[0], GroundTruth[1]);
  ASSERT_EQ(Result[1], GroundTruth[3]);

  // All data in the Hexastore? (XXX query in 'spo' tables)
  Result = H.get({{"?", "?", "?"}});
  ASSERT_EQ(Result.size(), 6);
  ASSERT_EQ(Result, GroundTruth);
}

TEST(HexastoreTest, StoreGraphNoEdgeLabels) {
  struct Vertex {
    string name;
    Vertex() = default;
    Vertex(string name) : name(move(name)) {}
  };
  struct Edge {
    string edge_name;
    Edge() = default;
    Edge(string label) : edge_name(move(label)) {}
  };

  using graph_t = boost::adjacency_list<boost::setS, boost::vecS,
                                        boost::undirectedS, Vertex, Edge>;
  using vertex_t = boost::graph_traits<graph_t>::vertex_descriptor;
  typename boost::graph_traits<graph_t>::edge_iterator ei_start, e_end;

  // graph with unlabeled edges
  graph_t G;

  vertex_t v1 = boost::add_vertex(G);
  G[v1].name = "A";
  vertex_t v2 = boost::add_vertex(G);
  G[v2].name = "B";
  vertex_t v3 = boost::add_vertex(G);
  G[v3].name = "C";
  vertex_t v4 = boost::add_vertex(G);
  G[v4].name = "D";
  vertex_t v5 = boost::add_vertex(G);
  G[v5].name = "X";
  vertex_t v6 = boost::add_vertex(G);
  G[v6].name = "Y";
  vertex_t v7 = boost::add_vertex(G);
  G[v7].name = "Z";

  boost::add_edge(v2, v1, G);
  boost::add_edge(v3, v1, G);
  boost::add_edge(v7, v3, G);
  boost::add_edge(v7, v6, G);
  boost::add_edge(v6, v5, G);
  boost::add_edge(v4, v2, G);

  // std::cout << "Graph G:" << std::endl;
  // boost::print_graph(G, boost::get(&Vertex::name, G));

  Hexastore HS("StoreGraphNoEdgeLabels.sqlite");

  // serialize graph G
  for (tie(ei_start, e_end) = boost::edges(G); ei_start != e_end; ++ei_start) {
    auto source = boost::source(*ei_start, G);
    auto target = boost::target(*ei_start, G);
    HS.put({{G[source].name, "no label", G[target].name}});
  }

  // de-serialize graph G as graph H"
  graph_t H;
  set<string> Recognized;
  map<string, vertex_t> Vertices;

  vector<hs_result> result_set = HS.get({{"?", "no label", "?"}}, 20);

  for (auto entry : result_set) {
    if (Recognized.find(entry.subject) == Recognized.end()) {
      Vertices[entry.subject] = boost::add_vertex(H);
      H[Vertices[entry.subject]].name = entry.subject;
    }
    if (Recognized.find(entry.object) == Recognized.end()) {
      Vertices[entry.object] = boost::add_vertex(H);
      H[Vertices[entry.object]].name = entry.object;
    }
    boost::add_edge(Vertices[entry.subject], Vertices[entry.object], H);
    Recognized.insert(entry.subject);
    Recognized.insert(entry.object);
  }

  // boost::print_graph(H, boost::get(&Vertex::name, H));
  ASSERT_TRUE(boost::isomorphism(G, H));
}

TEST(HexastoreTest, StoreGraphWithEdgeLabels) {
  struct Vertex {
    string name;
    Vertex() = default;
    Vertex(string name) : name(move(name)) {}
  };
  struct Edge {
    string edge_name;
    Edge() = default;
    Edge(string label) : edge_name(move(label)) {}
  };

  using graph_t = boost::adjacency_list<boost::setS, boost::vecS,
                                        boost::undirectedS, Vertex, Edge>;
  using vertex_t = boost::graph_traits<graph_t>::vertex_descriptor;
  typename boost::graph_traits<graph_t>::edge_iterator ei_start, e_end;

  // graph with labeled edges
  graph_t I;

  vertex_t w1 = boost::add_vertex(I);
  I[w1].name = "A";
  vertex_t w2 = boost::add_vertex(I);
  I[w2].name = "B";
  vertex_t w3 = boost::add_vertex(I);
  I[w3].name = "C";
  vertex_t w4 = boost::add_vertex(I);
  I[w4].name = "D";
  vertex_t w5 = boost::add_vertex(I);
  I[w5].name = "X";
  vertex_t w6 = boost::add_vertex(I);
  I[w6].name = "Y";
  vertex_t w7 = boost::add_vertex(I);
  I[w7].name = "Z";

  boost::add_edge(w2, w1, Edge("one"), I);
  boost::add_edge(w3, w1, Edge("two"), I);
  boost::add_edge(w7, w3, Edge("three"), I);
  boost::add_edge(w7, w6, Edge("four"), I);
  boost::add_edge(w6, w5, Edge("five"), I);
  boost::add_edge(w4, w2, Edge("six"), I);

  // std::cout << "Graph I:" << std::endl;
  // boost::print_graph(I, boost::get(&Vertex::name, I));
  // for (tie(ei_start, e_end) = boost::edges(I); ei_start != e_end; ++ei_start)
  // {
  //   //		auto source = boost::source(*ei_start, I);
  //   //		auto target = boost::target(*ei_start, I);
  //   cout << boost::get(&Edge::edge_name, I, *ei_start) << endl;
  // }

  Hexastore HS("StoreGraphWithEdgeLabels.sqlite");

  // serialize graph I
  for (tie(ei_start, e_end) = boost::edges(I); ei_start != e_end; ++ei_start) {
    auto source = boost::source(*ei_start, I);
    auto target = boost::target(*ei_start, I);
    string edge = boost::get(&Edge::edge_name, I, *ei_start);
    HS.put({{I[source].name, edge, I[target].name}});
  }

  // de-serialize graph I as graph J
  graph_t J;
  set<string> RecognizedVertices;
  map<string, vertex_t> Vertices;
  vector<hs_result> hsi_res = HS.get({{"?", "?", "?"}}, 10);
  for (auto entry : hsi_res) {
    if (RecognizedVertices.find(entry.subject) == RecognizedVertices.end()) {
      Vertices[entry.subject] = boost::add_vertex(J);
      J[Vertices[entry.subject]].name = entry.subject;
    }
    if (RecognizedVertices.find(entry.object) == RecognizedVertices.end()) {
      Vertices[entry.object] = boost::add_vertex(J);
      J[Vertices[entry.object]].name = entry.object;
    }
    RecognizedVertices.insert(entry.subject);
    RecognizedVertices.insert(entry.object);
    boost::add_edge(Vertices[entry.subject], Vertices[entry.object],
                    Edge(entry.predicate), J);
  }

  // boost::print_graph(J, boost::get(&Vertex::name, J));
  // for (tie(ei_start, e_end) = boost::edges(J); ei_start != e_end; ++ei_start)
  // {
  //   cout << boost::get(&Edge::edge_name, J, *ei_start) << endl;
  // }
  ASSERT_TRUE(boost::isomorphism(I, J));
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

max_stars_repo_name: flix-/phasar

max_issues_repo_name: flix-/phasar

max_forks_repo_name: flix-/phasar


text:
// Copyright (C) 2005 Arkadiy Vertleyb, Peder Holt.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_TYPEOF_STD_iostream_hpp_INCLUDED
#define BOOST_TYPEOF_STD_iostream_hpp_INCLUDED

#include <iostream>
#include <boost/typeof/typeof.hpp>
#include <boost/typeof/std/string.hpp>

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TEMPLATE(std::fpos, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(std::basic_ios, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(std::basic_ios, 2)

#endif//BOOST_TYPEOF_STD_iostream_hpp_INCLUDED

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
/**
 * @file sfinae_utility.hpp
 * @author Trironk Kiatkungwanglai
 *
 * This file contains macro utilities for the SFINAE Paradigm. These utilities
 * determine if classes passed in as template parameters contain members at
 * compile time, which is useful for changing functionality depending on what
 * operations an object is capable of performing.
 */
#ifndef __MLPACK_CORE_SFINAE_UTILITY
#define __MLPACK_CORE_SFINAE_UTILITY

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits.hpp>

/*
 * Constructs a template supporting the SFINAE pattern.
 *
 * This macro generates a template struct that is useful for enabling/disabling
 * a method if the template class passed in contains a member function matching
 * a given signature with a specified name.
 *
 * The generated struct should be used in conjunction with boost::disable_if and
 * boost::enable_if. Here is an example usage:
 *
 * For general references, see:
 * http://stackoverflow.com/a/264088/391618
 *
 * For an mlpack specific use case, see /mlpack/core/util/prefixedoutstream.hpp
 * and /mlpack/core/util/prefixedoutstream_impl.hpp
 *
 * @param NAME the name of the struct to construct. For example: HasToString
 * @param FUNC the name of the function to check for. For example: ToString
 */
#define HAS_MEM_FUNC(FUNC, NAME)                                               \
template<typename T, typename sig>                                             \
struct NAME {                                                                  \
  typedef char yes[1];                                                         \
  typedef char no [2];                                                         \
  template<typename U, U> struct type_check;                                   \
  template<typename _1> static yes &chk(type_check<sig, &_1::FUNC> *);         \
  template<typename   > static no  &chk(...);                                  \
  static bool const value = sizeof(chk<T>(0)) == sizeof(yes);                  \
};

#endif

max_stars_repo_name: decltypeme/mlpack

max_issues_repo_name: decltypeme/mlpack

max_forks_repo_name: decltypeme/mlpack


text:
/**
 * @file
 * @copyright This code is licensed under the 3-clause BSD license.\n
 *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
 *            See LICENSE.txt for details.
 */

#include <Utils/Properties/Reactivity/ConceptualDft.h>
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <boost/optional.hpp>

using namespace Scine::Utils::ConceptualDft;

void init_conceptual_dft(pybind11::module& m) {
  auto conceptual_dft_submodule = m.def_submodule("conceptual_dft", R"delim(
      Functionality to calculate various conceptual DFT properties based on the finite difference approximation.

      To use this functionality the energy and/or atomic charges of the optimized structure of interest and of the same
      structure (not reoptimized!) with one additional electron and one electron less are needed.

      An introduction into conceptual DFT can be found in:
      Chattaraj, P. K. Chemical Reactivity Theory : A Density Functional View; CRC Press, 2009.
      https://doi.org/10.1201/9781420065442.
    )delim");

  pybind11::class_<GlobalConceptualDftContainer> globalConceptualDftContainer(conceptual_dft_submodule,
                                                                              "GlobalConceptualDftContainer");
  globalConceptualDftContainer.def_readonly("chemical_potential", &GlobalConceptualDftContainer::chemicalPotential);
  globalConceptualDftContainer.def_readonly("electronegativity", &GlobalConceptualDftContainer::electronegativity);
  globalConceptualDftContainer.def_readonly("hardness", &GlobalConceptualDftContainer::hardness);
  globalConceptualDftContainer.def_readonly("softness", &GlobalConceptualDftContainer::softness);
  globalConceptualDftContainer.def_readonly("electrophilicity", &GlobalConceptualDftContainer::electrophilicity);

  pybind11::class_<LocalConceptualDftContainer> localConceptualDftContainer(conceptual_dft_submodule,
                                                                            "LocalConceptualDftContainer");
  localConceptualDftContainer.def_readonly("fukui_plus", &LocalConceptualDftContainer::fukuiPlus);
  localConceptualDftContainer.def_readonly("fukui_minus", &LocalConceptualDftContainer::fukuiMinus);
  localConceptualDftContainer.def_readonly("fukui_radical", &LocalConceptualDftContainer::fukuiRadical);
  localConceptualDftContainer.def_readonly("dual_descriptor", &LocalConceptualDftContainer::dualDescriptor);

  pybind11::class_<ConceptualDftContainer> conceptualDftContainer(conceptual_dft_submodule, "ConceptualDftContainer");
  // NOTE: Cannot define global or local, those are reserved keywords in python
  conceptualDftContainer.def_readonly("global_v", &ConceptualDftContainer::global);
  conceptualDftContainer.def_readonly("local_v", &ConceptualDftContainer::local);

  conceptual_dft_submodule.def("calculate", &calculate, pybind11::arg("energy"), pybind11::arg("atomic_charges"),
                               pybind11::arg("energy_plus"), pybind11::arg("atomic_charges_plus"),
                               pybind11::arg("energy_minus"), pybind11::arg("atomic_charges_minus"), R"delim(
      Calculates a set of global and local conceptual DFT parameters.
      Note: The quality of the resulting Fukui and dual descriptor indices heavily depends on the quality of the atomic
      charges.
      We recommend Hirshfeld charges.

      :param energy: The energy of the structure of interest
      :param: atomic_charges The atomic charges of the structure of interest
      :param energy_plus: The energy for the same geometry with one additional electron
      :param: atomic_charges_plus The atomic charges for the same geometry with one additional electron
      :param energy_minus: The energy for the same geometry with one electron less
      :param: atomic_charges_minus The atomic charges for the same geometry with one electron less
      :return: A conceptualDftContainer with local and global cDFT properties
      )delim");

  conceptual_dft_submodule.def("calculate_global", &calculateGlobal, pybind11::arg("energy"),
                               pybind11::arg("energy_plus"), pybind11::arg("energy_minus"), R"delim(
      Calculates a set of global conceptual DFT parameters.

      :param energy: The energy of the structure of interest
      :param energy_plus: The energy for the same geometry with one additional electron
      :param energy_minus: The energy for the same geometry with one electron less
      :return: A globalConceptualDftContainer with global cDFT properties
      )delim");

  conceptual_dft_submodule.def("calculate_local", &calculateLocal, pybind11::arg("atomic_charges"),
                               pybind11::arg("atomic_charges_plus"), pybind11::arg("atomic_charges_minus"), R"delim(
      Calculates the condensed to atom Fukui and dual descriptor indices.

      Note: The quality of the resulting indices heavily depends on the quality of the atomic charges.
      We recommend Hirshfeld charges.

      :param: atomic_charges The atomic charges of the structure of interest
      :param: atomic_charges_plus The atomic charges for the same geometry with one additional electron
      :param: atomic_charges_minus The atomic charges for the same geometry with one electron less
      :return: A localConceptualDftContainer with global cDFT properties
      )delim");

  conceptual_dft_submodule.def("calculate_chemical_potential", &calculateChemicalPotential, pybind11::arg("energy"),
                               pybind11::arg("energy_plus"), pybind11::arg("energy_minus"), R"delim(
      Calculates the conceptual DFT chemical potential.

      Parr, R. G.; Pearson, R. G., J. Am. Chem. Soc. 1983, 105 (26), 7512–7516. https://doi.org/10.1021/ja00364a005.

      :param energy: The energy of the structure of interest
      :param energy_plus: The energy for the same geometry with one additional electron
      :param energy_minus: The energy for the same geometry with one electron less
      :return: The chemical potential
      )delim");

  conceptual_dft_submodule.def("calculate_electronegativity", &calculateElectronegativity, pybind11::arg("energy"),
                               pybind11::arg("energy_plus"), pybind11::arg("energy_minus"), R"delim(
      Calculates the Mulliken electronegativity.

      Mulliken, R. S.; J. Chem. Phys. 1934, 2 (11), 782–793. https://doi.org/10.1063/1.1749394.

      :param energy: The energy of the structure of interest
      :param energy_plus: The energy for the same geometry with one additional electron
      :param energy_minus: The energy for the same geometry with one electron less
      :return: The electronegativity
      )delim");

  conceptual_dft_submodule.def("calculate_hardness", &calculateHardness, pybind11::arg("energy"),
                               pybind11::arg("energy_plus"), pybind11::arg("energy_minus"), R"delim(
      Calculates the chemical hardness.

      Parr, R. G.; Pearson, R. G.; J. Am. Chem. Soc. 1983, 105 (26), 7512–7516. https://doi.org/10.1021/ja00364a005.

      :param energy: The energy of the structure of interest
      :param energy_plus: The energy for the same geometry with one additional electron
      :param energy_minus: The energy for the same geometry with one electron less
      :return: The chemical hardness.
      )delim");

  conceptual_dft_submodule.def("calculate_softness", &calculateSoftness, pybind11::arg("energy"),
                               pybind11::arg("energy_plus"), pybind11::arg("energy_minus"), R"delim(
      Calculates the chemical softness.

      Yang, W.; Parr, R. G.; PNAS 1985, 82 (20), 6723–6726. https://doi.org/10.1073/pnas.82.20.6723.

      :param energy: The energy of the structure of interest
      :param energy_plus: The energy for the same geometry with one additional electron
      :param energy_minus: The energy for the same geometry with one electron less
      :return: The chemical softness.
      )delim");

  conceptual_dft_submodule.def("calculate_electrophilicity", &calculateElectrophilicity, pybind11::arg("energy"),
                               pybind11::arg("energy_plus"), pybind11::arg("energy_minus"), R"delim(
      Calculates the electrophilicity.

      Parr, R. G.; Szentpály, L. v.; Liu, S.; J. Am. Chem. Soc. 1999, 121 (9), 1922–1924.
      https://doi.org/10.1021/ja983494x.

      :param energy: The energy of the structure of interest
      :param energy_plus: The energy for the same geometry with one additional electron
      :param energy_minus: The energy for the same geometry with one electron less
      :return: The electrophilicity.
      )delim");

  conceptual_dft_submodule.def("calculate_fukui_plus", &calculateFukuiPlus, pybind11::arg("atomic_charges"),
                               pybind11::arg("atomic_charges_plus"), pybind11::arg("atomic_charges_minus"), R"delim(
      Calculates the Fukui indices for nucleophilic attacks.
      Note: The quality of the results heavily depends on the quality of the atomic charges.
      We recommend Hirshfeld charges.

      Parr, R. G.; Yang, W.; J. Am. Chem. Soc. 1984, 106 (14), 4049–4050. https://doi.org/10.1021/ja00326a036.

      :param: atomic_charges The atomic charges of the structure of interest
      :param: atomic_charges_plus The atomic charges for the same geometry with one additional electron
      :param: atomic_charges_minus The atomic charges for the same geometry with one electron less
      :return: The Fukui indices for nucleophilic attacks.
      )delim");

  conceptual_dft_submodule.def("calculate_fukui_minus", &calculateFukuiMinus, pybind11::arg("atomic_charges"),
                               pybind11::arg("atomic_charges_plus"), pybind11::arg("atomic_charges_minus"), R"delim(
      Calculates the Fukui indices for nucleophilic attacks.
      Note: The quality of the results heavily depends on the quality of the atomic charges.
      We recommend Hirshfeld charges.

      Parr, R. G.; Yang, W.; J. Am. Chem. Soc. 1984, 106 (14), 4049–4050. https://doi.org/10.1021/ja00326a036.

      :param: atomic_charges The atomic charges of the structure of interest
      :param: atomic_charges_plus The atomic charges for the same geometry with one additional electron
      :param: atomic_charges_minus The atomic charges for the same geometry with one electron less
      :return: The Fukui indices for electrophilic attacks.
      )delim");

  conceptual_dft_submodule.def("calculate_fukui_radical", &calculateFukuiRadical, pybind11::arg("atomic_charges"),
                               pybind11::arg("atomic_charges_plus"), pybind11::arg("atomic_charges_minus"), R"delim(
      Calculates the Fukui indices for radical attacks.
      Note: The quality of the results heavily depends on the quality of the atomic charges.
      We recommend Hirshfeld charges.
      The relevance of the radical Fukui function is known to be limited. It is included here for completeness only.

      Parr, R. G.; Yang, W.; J. Am. Chem. Soc. 1984, 106 (14), 4049–4050. https://doi.org/10.1021/ja00326a036.

      :param: atomic_charges The atomic charges of the structure of interest
      :param: atomic_charges_plus The atomic charges for the same geometry with one additional electron
      :param: atomic_charges_minus The atomic charges for the same geometry with one electron less
      :return: The Fukui indices for radical attacks.
      )delim");

  conceptual_dft_submodule.def("calculate_dual_descriptor", &calculateDualDescriptor, pybind11::arg("atomic_charges"),
                               pybind11::arg("atomic_charges_plus"), pybind11::arg("atomic_charges_minus"), R"delim(
      Calculates the the condensed to atom dual descriptor.
      Note: The quality of the results heavily depends on the quality of the atomic charges.
      We recommend Hirshfeld charges.

      Morell, C.; Grand, A.; Toro-Labbé, A.; J. Phys. Chem. A 2005, 109 (1), 205–212. https://doi.org/10.1021/jp046577a.

      :param: atomic_charges The atomic charges of the structure of interest
      :param: atomic_charges_plus The atomic charges for the same geometry with one additional electron
      :param: atomic_charges_minus The atomic charges for the same geometry with one electron less
      :return: The condensed-to-atom dual descriptor.
      )delim");
}

max_stars_repo_name: qcscine/utilities

max_issues_repo_name: qcscine/utilities

max_forks_repo_name: qcscine/utilities


text:
#pragma once

#include <mutex>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>

#include "exception.hpp"
#include "utils/string.hpp"

namespace config
{
  DefineBaseException(ConfigException);
  DefineChildException(UnexistingFileError, ConfigException);
  DefineChildException(ParseError, ConfigException);
  DefineChildException(MissingValueException, ConfigException);
  DefineChildException(MissingListValueException, ConfigException);
  DefineChildException(InvalidVariableException, ConfigException);
  DefineChildException(InvalidReferenceException, ConfigException);

  static std::recursive_mutex mtx;

  std::string get_bar_path();
  void set_bar_path(std::string path);

  void load(std::string path);
  void load(const char *dir, std::string path);
  // void reload();

  boost::property_tree::ptree get_tree();

  std::string build_path(std::string section, std::string key);

  std::string get_file_path();

  template<typename T>
  T dereference_var(std::string ref_section, std::string ref_key, std::string var, const T ref_val)
  {
    std::lock_guard<std::recursive_mutex> lck(config::mtx);

    std::string::size_type n, m;

    if ((n = var.find("${")) != 0) return ref_val;
    if ((m = var.find("}")) != var.length()-1) return ref_val;

    auto path = var.substr(2, m-2);
    auto ref_path = build_path(ref_section, ref_key);

    if ((n = path.find(".")) == std::string::npos)
      throw InvalidVariableException("Invalid variable "+ ref_path +" => ${"+ path +"}");

    auto section = string::replace(path.substr(0, n), "BAR", get_bar_path());
    auto key = path.substr(n+1, path.length()-n-1);

    auto val = get_tree().get_optional<T>(build_path(section, key));

    if (val == boost::none)
      throw InvalidReferenceException("Variable defined at ["+ ref_path +"] points to a non existing parameter: ["+ build_path(section, key) +"]");

    auto str_val = get_tree().get<std::string>(build_path(section, key));

    return dereference_var<T>(section, key, str_val, val.get());
  }

  template<typename T>
  T get(std::string section, std::string key)
  {
    std::lock_guard<std::recursive_mutex> lck(config::mtx);

    auto val = get_tree().get_optional<T>(build_path(section, key));

    if (val == boost::none)
      throw MissingValueException("Missing property \""+ key +"\" in section ["+ section +"]");

    auto str_val = get_tree().get<std::string>(build_path(section, key));

    return dereference_var<T>(section, key, str_val, val.get());
  }

  template<typename T>
  T get(std::string section, std::string key, T default_value)
  {
    std::lock_guard<std::recursive_mutex> lck(config::mtx);

    auto val = get_tree().get_optional<T>(build_path(section, key));
    auto str_val = get_tree().get_optional<std::string>(build_path(section, key));

    return dereference_var<T>(section, key, str_val.get_value_or(""), val.get_value_or(default_value));
  }

  template<typename T>
  std::vector<T> get_list(std::string section, std::string key)
  {
    std::lock_guard<std::recursive_mutex> lck(config::mtx);

    std::vector<T> vec;
    boost::optional<T> value;

    while ((value = get_tree().get_optional<T>(build_path(section, key) + "-"+ std::to_string(vec.size()))) != boost::none) {
      auto str_val = get_tree().get<std::string>(build_path(section, key) + "-"+ std::to_string(vec.size()));
      vec.emplace_back(dereference_var<T>(section, key, str_val, value.get()));
    }

    if (vec.empty())
      throw MissingListValueException("Missing property \""+ key + "-0\" in section ["+ section +"]");

    return vec;
  }

  template<typename T>
  std::vector<T> get_list(std::string section, std::string key, std::vector<T> default_value)
  {
    std::lock_guard<std::recursive_mutex> lck(config::mtx);

    std::vector<T> vec;
    boost::optional<T> value;

    while ((value = get_tree().get_optional<T>(build_path(section, key) + "-"+ std::to_string(vec.size()))) != boost::none) {
      auto str_val = get_tree().get<std::string>(build_path(section, key) + "-"+ std::to_string(vec.size()));
      vec.emplace_back(dereference_var<T>(section, key, str_val, value.get()));
    }

    if (vec.empty())
      return default_value;
    else
      return vec;
  }
}

max_issues_repo_name: NateBrune/lemonbuddy

max_forks_repo_name: NateBrune/lemonbuddy


text:
// easylazy
//
// Copyright iorate 2019.
// 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)

#include <boost/core/lightweight_test.hpp>
#include "../easylazy.hpp"

using namespace easylazy;

int main() {
    // Postfix Expressions
    BOOST_TEST((list<int_>{23, 42}[1_d].get()) == 42);
    BOOST_TEST((EASYLAZY_FUNCTION(int_ x, int_ y) { return x + y; })(3_d, 4_d).get() == 7);
    BOOST_TEST(double_(10_d).get() == 10.0);

    // Unary Expressions
    BOOST_TEST((+4_d).get() == 4);
    BOOST_TEST((-2.5_lf).get() == -2.5);
    BOOST_TEST((!bool_(false)).get() == true);
    BOOST_TEST((!12_d).get() == false);
    BOOST_TEST((~0_d).get() == -1);

    // Explicit Type Conversion
    BOOST_TEST((float_)1_d == 1.0_f);

    // Multiplicative Operators
    BOOST_TEST((1.5_lf * 4_d).get() == 6.0);
    BOOST_TEST((19_d / 4_d).get() == 4);
    BOOST_TEST((19_d % 4_d).get() == 3);

    // Additive Operators
    BOOST_TEST((3_d + 4.5_lf).get() == 7.5);
    BOOST_TEST(('9'_c - '3'_c).get() == 6);

    // Shift Operators
    BOOST_TEST((18_d << 2_d).get() == 72);
    BOOST_TEST((18_d >> 2_d).get() == 4);

    // Relational Operators
    BOOST_TEST((1.5_f < 3.5_f).get() == true);
    BOOST_TEST((1.5_f < 1.5_f).get() == false);
    BOOST_TEST((35_d > 15_d).get() == true);
    BOOST_TEST((35_d > 35_d).get() == false);
    BOOST_TEST((1.5_f <= 1.5_f).get() == true);
    BOOST_TEST((1.5_f <= 0.5_f).get() == false);
    BOOST_TEST((15_d >= 15_d).get() == true);
    BOOST_TEST((5_d >= 15_d).get() == false);

    // Equality Operators
    BOOST_TEST((10_d == 10_d).get() == true);
    BOOST_TEST((8.0_f == 1.5_f).get() == false);
    BOOST_TEST((80_d != 15_d).get() == true);
    BOOST_TEST((1.0_f != 1.0_f).get() == false);

    // Bitwise Operators
    BOOST_TEST((12_d & 10_d).get() == 8);
    BOOST_TEST((12_d ^ 10_d).get() == 6);
    BOOST_TEST((12_d | 10_d).get() == 14);

    // Logical Operators
    BOOST_TEST((bool_(true) && bool_(true)).get() == true);
    BOOST_TEST((bool_(true) && 0_d).get() == false);
    BOOST_TEST((bool_(false) || bool_(true)).get() == true);
    BOOST_TEST((bool_(false) || 0_d).get() == false);

    // Implicit Type Conversion
    int_ n = ' '_c;
    BOOST_TEST(n.get() == 0x20);
    if ('\0'_c) {
        BOOST_ERROR("not reached");
    }

    return boost::report_errors();
}

max_stars_repo_name: iorate/easylazy

max_issues_repo_name: iorate/easylazy

max_forks_repo_name: iorate/easylazy


text:
//  Copyright (c) 2007-2012 Hartmut Kaiser
//  Copyright (c) 2017      Denis Blank
//
//  SPDX-License-Identifier: BSL-1.0
//  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)

#include <hpx/config.hpp>
#include <hpx/debugging/attach_debugger.hpp>

#include <iostream>

#if defined(HPX_HAVE_UNISTD_H)
#include <unistd.h>
#endif

#if defined(HPX_WINDOWS)
#include <Windows.h>
#endif    // HPX_WINDOWS

#if defined(_POSIX_VERSION)
#include <boost/asio/ip/host_name.hpp>
#endif

namespace hpx { namespace util {
    void attach_debugger()
    {
#if defined(_POSIX_VERSION)
        volatile int i = 0;
        std::cerr << "PID: " << getpid() << " on "
                  << boost::asio::ip::host_name()
                  << " ready for attaching debugger. Once attached set i = 1 "
                     "and continue"
                  << std::endl;
        while (i == 0)
        {
            sleep(1);
        }
#elif defined(HPX_WINDOWS)
        DebugBreak();
#endif
    }
}}    // namespace hpx::util

max_stars_repo_name: jokteur/hpx

max_issues_repo_name: jokteur/hpx

max_forks_repo_name: jokteur/hpx


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#ifndef MTL_VECTOR_PARAMETERS_INCLUDE
#define MTL_VECTOR_PARAMETERS_INCLUDE

#include <boost/mpl/bool.hpp>
#include <boost/numeric/mtl/utility/static_assert.hpp>
#include <boost/numeric/mtl/utility/tag.hpp>
#include <boost/numeric/mtl/vector/dimension.hpp>
#include <boost/numeric/mtl/utility/is_static.hpp>

namespace mtl { namespace vec {

/// This type exist only for bundling template parameters (to reduce typing)
/** OnStack = true can only be used with fixed::dimension.
    \sa \ref tuning_fsize
    \sa \ref tuning_sizetype **/
template <typename Orientation= col_major,
	  typename Dimension= non_fixed::dimension,
	  bool OnStack= mtl::traits::is_static<Dimension>::value,
	  typename SizeType= std::size_t>
struct parameters
{
    typedef Orientation orientation;
    typedef Dimension   dimension;
    static const bool   on_stack= OnStack;
    typedef SizeType    size_type;

    // Vector dimension must be known at compile time to be on the stack
    MTL_STATIC_ASSERT(( !on_stack || dimension::is_static ), "Types to be stored on stack must provide static size.");
};

}} // namespace mtl::vector

#endif // MTL_VECTOR_PARAMETERS_INCLUDE