<commit_before>#include <iostream>
#include <string>
#include <liboauthcpp/liboauthcpp.h>

/* These are input settings that make this demo actually work -- you need to get
 * these, e.g. by referring to the Twitter documentation and by registering an
 * application with them. Here we have examples from Twitter. If you
 * don't enter any, you'll be prompted to enter them at runtime.
 */
std::string consumer_key = ""; // Key from Twitter
std::string consumer_secret = ""; // Secret from Twitter
std::string request_token_url = "http://twitter.com/oauth/request_token";
std::string authorize_url = "http://twitter.com/oauth/authorize";
std::string access_token_url = "http://twitter.com/oauth/access_token";

std::string getUserString(std::string prompt) {
    std::cout << prompt << " ";

    std::string res;
    std::cin >> res;
    std::cout << std::endl;
    return res;
}

int main(int argc, char** argv) {

    // Initialization
    if (consumer_key.empty()) consumer_key = getUserString("Enter consumer key:");
    if (consumer_secret.empty()) consumer_secret = getUserString("Enter consumer secret:");
    OAuth::Consumer consumer(consumer_key, consumer_secret);
    OAuth::Client oauth(&consumer);

    // Step 1: Get a request token. This is a temporary token that is used for
    // having the user authorize an access token and to sign the request to
    // obtain said access token.
    std::string oAuthQueryString =
        oauth.getURLQueryString( OAuth::Http::Get, request_token_url);
    std::cout << "Enter the following in your browser to get the request token: " << std::endl;
    std::cout << request_token_url << "?" << oAuthQueryString << std::endl;
    std::cout << std::endl;

    // Extract the token and token_secret from the response
    std::string request_token_resp = getUserString("Enter the response:");
    // This time we pass the response directly and have the library do the
    // parsing (see next extractToken call for alternative)
    OAuth::Token request_token = OAuth::Token::extract( request_token_resp );

    // Get access token and secret from OAuth object
    std::cout << "Request Token:" << std::endl;
    std::cout << "    - oauth_token        = " << request_token.key() << std::endl;
    std::cout << "    - oauth_token_secret = " << request_token.secret() << std::endl;
    std::cout << std::endl;

    // Step 2: Redirect to the provider. Since this is a CLI script we
    // do not redirect. In a web application you would redirect the
    // user to the URL below.
    std::cout << "Go to the following link in your browser to authorize this application on a user's account:" << std::endl;
    std::cout << authorize_url << "?oauth_token=" << request_token.key() << std::endl;

    // After the user has granted access to you, the consumer, the
    // provider will redirect you to whatever URL you have told them
    // to redirect to. You can usually define this in the
    // oauth_callback argument as well.
    std::string pin = getUserString("What is the PIN?");
    request_token.setPin(pin);

    // Step 3: Once the consumer has redirected the user back to the
    // oauth_callback URL you can request the access token the user
    // has approved. You use the request token to sign this
    // request. After this is done you throw away the request token
    // and use the access token returned. You should store the oauth
    // token and token secret somewhere safe, like a database, for
    // future use.
    oauth = OAuth::Client(&consumer, &request_token);
    // Note that we explicitly specify an empty body here (it's a GET) so we can
    // also specify to include the oauth_verifier parameter
    oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, access_token_url, std::string( "" ), true );
    std::cout << "Enter the following in your browser to get the final access token & secret: " << std::endl;
    std::cout << access_token_url << "?" << oAuthQueryString;
    std::cout << std::endl;

    // Once they've come back from the browser, extract the token and token_secret from the response
    std::string access_token_resp = getUserString("Enter the response:");
    // On this extractToken, we do the parsing ourselves (via the library) so we
    // can extract additional keys that are sent back, in the case of twitter,
    // the screen_name
    OAuth::KeyValuePairs access_token_resp_data = OAuth::ParseKeyValuePairs(access_token_resp);
    OAuth::Token access_token = OAuth::Token::extract( access_token_resp_data );

    std::cout << "Access token:" << std::endl;
    std::cout << "    - oauth_token        = " << access_token.key() << std::endl;
    std::cout << "    - oauth_token_secret = " << access_token.secret() << std::endl;
    std::cout << std::endl;
    std::cout << "You may now access protected resources using the access tokens above." << std::endl;
    std::cout << std::endl;

    if (access_token_resp_data.find("screen_name") != access_token_resp_data.end())
        std::cout << "Also extracted screen name from access token response: " << access_token_resp_data["screen_name"] << std::endl;

    // E.g., to use the access token, you'd create a new OAuth using
    // it, discarding the request_token:
    // oauth = OAuth::Client(&consumer, &access_token);

    return 0;
}
<commit_msg>Update Twitter demo URLs in simple_auth.<commit_after>#include <iostream>
#include <string>
#include <liboauthcpp/liboauthcpp.h>

/* These are input settings that make this demo actually work -- you need to get
 * these, e.g. by referring to the Twitter documentation and by registering an
 * application with them. Here we have examples from Twitter. If you
 * don't enter any, you'll be prompted to enter them at runtime.
 */
std::string consumer_key = ""; // Key from Twitter
std::string consumer_secret = ""; // Secret from Twitter
std::string request_token_url = "https://api.twitter.com/oauth/request_token";
std::string authorize_url = "https://api.twitter.com/oauth/authorize";
std::string access_token_url = "https://api.twitter.com/oauth/access_token";

std::string getUserString(std::string prompt) {
    std::cout << prompt << " ";

    std::string res;
    std::cin >> res;
    std::cout << std::endl;
    return res;
}

int main(int argc, char** argv) {

    // Initialization
    if (consumer_key.empty()) consumer_key = getUserString("Enter consumer key:");
    if (consumer_secret.empty()) consumer_secret = getUserString("Enter consumer secret:");
    OAuth::Consumer consumer(consumer_key, consumer_secret);
    OAuth::Client oauth(&consumer);

    // Step 1: Get a request token. This is a temporary token that is used for
    // having the user authorize an access token and to sign the request to
    // obtain said access token.
    std::string oAuthQueryString =
        oauth.getURLQueryString( OAuth::Http::Get, request_token_url);
    std::cout << "Enter the following in your browser to get the request token: " << std::endl;
    std::cout << request_token_url << "?" << oAuthQueryString << std::endl;
    std::cout << std::endl;

    // Extract the token and token_secret from the response
    std::string request_token_resp = getUserString("Enter the response:");
    // This time we pass the response directly and have the library do the
    // parsing (see next extractToken call for alternative)
    OAuth::Token request_token = OAuth::Token::extract( request_token_resp );

    // Get access token and secret from OAuth object
    std::cout << "Request Token:" << std::endl;
    std::cout << "    - oauth_token        = " << request_token.key() << std::endl;
    std::cout << "    - oauth_token_secret = " << request_token.secret() << std::endl;
    std::cout << std::endl;

    // Step 2: Redirect to the provider. Since this is a CLI script we
    // do not redirect. In a web application you would redirect the
    // user to the URL below.
    std::cout << "Go to the following link in your browser to authorize this application on a user's account:" << std::endl;
    std::cout << authorize_url << "?oauth_token=" << request_token.key() << std::endl;

    // After the user has granted access to you, the consumer, the
    // provider will redirect you to whatever URL you have told them
    // to redirect to. You can usually define this in the
    // oauth_callback argument as well.
    std::string pin = getUserString("What is the PIN?");
    request_token.setPin(pin);

    // Step 3: Once the consumer has redirected the user back to the
    // oauth_callback URL you can request the access token the user
    // has approved. You use the request token to sign this
    // request. After this is done you throw away the request token
    // and use the access token returned. You should store the oauth
    // token and token secret somewhere safe, like a database, for
    // future use.
    oauth = OAuth::Client(&consumer, &request_token);
    // Note that we explicitly specify an empty body here (it's a GET) so we can
    // also specify to include the oauth_verifier parameter
    oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, access_token_url, std::string( "" ), true );
    std::cout << "Enter the following in your browser to get the final access token & secret: " << std::endl;
    std::cout << access_token_url << "?" << oAuthQueryString;
    std::cout << std::endl;

    // Once they've come back from the browser, extract the token and token_secret from the response
    std::string access_token_resp = getUserString("Enter the response:");
    // On this extractToken, we do the parsing ourselves (via the library) so we
    // can extract additional keys that are sent back, in the case of twitter,
    // the screen_name
    OAuth::KeyValuePairs access_token_resp_data = OAuth::ParseKeyValuePairs(access_token_resp);
    OAuth::Token access_token = OAuth::Token::extract( access_token_resp_data );

    std::cout << "Access token:" << std::endl;
    std::cout << "    - oauth_token        = " << access_token.key() << std::endl;
    std::cout << "    - oauth_token_secret = " << access_token.secret() << std::endl;
    std::cout << std::endl;
    std::cout << "You may now access protected resources using the access tokens above." << std::endl;
    std::cout << std::endl;

    if (access_token_resp_data.find("screen_name") != access_token_resp_data.end())
        std::cout << "Also extracted screen name from access token response: " << access_token_resp_data["screen_name"] << std::endl;

    // E.g., to use the access token, you'd create a new OAuth using
    // it, discarding the request_token:
    // oauth = OAuth::Client(&consumer, &access_token);

    return 0;
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <unsupported/Eigen/AlignedVector3>

namespace Eigen {

template<typename T,typename Derived>
T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b)
{
  return test_relative_error(a.coeffs().template head<3>(), b);
}

}

template<typename Scalar>
void alignedvector3()
{
  Scalar s1 = internal::random<Scalar>();
  Scalar s2 = internal::random<Scalar>();
  typedef Matrix<Scalar,3,1> RefType;
  typedef Matrix<Scalar,3,3> Mat33;
  typedef AlignedVector3<Scalar> FastType;
  RefType  r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),
           r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());
  FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);
  Mat33 m1(Mat33::Random());

  VERIFY_IS_APPROX(f1,r1);
  VERIFY_IS_APPROX(f4,r4);

  VERIFY_IS_APPROX(f4+f1,r4+r1);
  VERIFY_IS_APPROX(f4-f1,r4-r1);
  VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);
  VERIFY_IS_APPROX(f4+=f3,r4+=r3);
  VERIFY_IS_APPROX(f4-=f5,r4-=r5);
  VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);
  VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);
  VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2);

  VERIFY_IS_APPROX(m1*f4,m1*r4);
  VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);

  VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));
  VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));
  VERIFY_IS_APPROX(f2.norm(),r2.norm());

  VERIFY_IS_APPROX(f2.normalized(),r2.normalized());

  VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());

  f2.normalize();
  r2.normalize();
  VERIFY_IS_APPROX(f2,r2);

  std::stringstream ss1, ss2;
  ss1 << f1;
  ss2 << r1;
  VERIFY(ss1.str()==ss2.str());
}

void test_alignedvector3()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( alignedvector3<float>() );
  }
}
<commit_msg>add regression unit test for previous changeset<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"
#include <unsupported/Eigen/AlignedVector3>

namespace Eigen {

template<typename T,typename Derived>
T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b)
{
  return test_relative_error(a.coeffs().template head<3>(), b);
}

}

template<typename Scalar>
void alignedvector3()
{
  Scalar s1 = internal::random<Scalar>();
  Scalar s2 = internal::random<Scalar>();
  typedef Matrix<Scalar,3,1> RefType;
  typedef Matrix<Scalar,3,3> Mat33;
  typedef AlignedVector3<Scalar> FastType;
  RefType  r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),
           r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());
  FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);
  Mat33 m1(Mat33::Random());

  VERIFY_IS_APPROX(f1,r1);
  VERIFY_IS_APPROX(f4,r4);

  VERIFY_IS_APPROX(f4+f1,r4+r1);
  VERIFY_IS_APPROX(f4-f1,r4-r1);
  VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);
  VERIFY_IS_APPROX(f4+=f3,r4+=r3);
  VERIFY_IS_APPROX(f4-=f5,r4-=r5);
  VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);
  VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);
  VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2);

  VERIFY_IS_APPROX(m1*f4,m1*r4);
  VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);

  VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));
  VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));
  VERIFY_IS_APPROX(f2.norm(),r2.norm());

  VERIFY_IS_APPROX(f2.normalized(),r2.normalized());

  VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());

  f2.normalize();
  r2.normalize();
  VERIFY_IS_APPROX(f2,r2);

  {
    FastType f6 = RefType::Zero();
    FastType f7 = FastType::Zero();
    VERIFY_IS_APPROX(f6,f7);
    f6 = r4+r1;
    VERIFY_IS_APPROX(f6,r4+r1);
    f6 -= Scalar(2)*r4;
    VERIFY_IS_APPROX(f6,r1-r4);
  }

  std::stringstream ss1, ss2;
  ss1 << f1;
  ss2 << r1;
  VERIFY(ss1.str()==ss2.str());
}

void test_alignedvector3()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( alignedvector3<float>() );
  }
}
<|endoftext|>


<commit_before>#ifndef ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__
#define ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__

#include <aleph/geometry/distances/Traits.hh>

#include <aleph/math/Statistics.hh>

#include <algorithm>
#include <map>
#include <stdexcept>
#include <vector>

#include <cmath>

namespace aleph
{

namespace containers
{

/*
 Wrapper class for representing a sequence of correlation dimension
 integral values. I want the interface to be as clear as possible.
*/

struct CorrelationDimensionSequence
{
  std::vector<double> x;
  std::vector<double> y;
};

/**
  Calculates samples of the correlation dimension integral for a given
  point cloud. This does *not* yet result in a dimension estimate, but
  only produces a set of points.
*/

template <
  class Distance,
  class Container
> CorrelationDimensionSequence correlationDimensionIntegral(
  const Container& container,
  Distance dist = Distance() )
{
  auto n = container.size();
  auto d = container.dimension();

  std::map<double, unsigned> distances;

  aleph::geometry::distances::Traits<Distance> traits;

  for( decltype(n) i = 0; i < n; i++ )
  {
    auto&& p = container[i];

    for( decltype(n) j = i+1; j < n; j++ )
    {
      auto&& q      = container[j];
      auto distance = dist( p.begin(),
                            q.begin(),
                            d );

      distances[ traits.from( distance ) ] += 1;
    }
  }

  CorrelationDimensionSequence cds;
  cds.x.reserve( distances.size() );
  cds.y.reserve( distances.size() );

  // Determine the correlation dimension integral for all potential
  // values. This only requires counting how many *pairs* have been
  // seen by the algorithm.

  unsigned seen = 0;
  for( auto&& pair : distances )
  {
    auto&& distance = pair.first;
    auto&& count    = pair.second;

    seen += count;

    if( distance > 0 )
    {
      cds.x.push_back( distance );
      cds.y.push_back( seen / static_cast<double>( 0.5 * n * (n-1) ) );
    }
  }

  return cds;
}

/**
  Estimates the correlation dimension from a correlation dimension
  sequence, which involves calculating a log-log plot of the data,
  and determining the best coefficient for a linear fit.
*/

double correlationDimension( const CorrelationDimensionSequence& cds )
{
  if( cds.x.size() != cds.y.size() )
    throw std::runtime_error( "Inconsistent correlation dimension sequence" );

  std::vector<double> X;
  std::vector<double> Y;

  X.reserve( cds.x.size() );
  Y.reserve( cds.y.size() );

  auto log = [] ( double x )
  {
    return std::log( x );
  };

  std::transform( cds.x.begin(), cds.x.end(), std::back_inserter( X ), log );
  std::transform( cds.y.begin(), cds.y.end(), std::back_inserter( Y ), log );

  // This is a simple linear regression model. We are only interested in
  // the slope of the regression line, so this is sufficient.

  auto cov
    = aleph::math::sampleCovariance( X.begin(), X.end(),
                                     Y.begin(), Y.end() );

  auto var
    = aleph::math::sampleVariance( X.begin(), X.end() );

  return cov / var;
}

} // namespace containers

} // namespace aleph

#endif
<commit_msg>Fixed conversion error<commit_after>#ifndef ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__
#define ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__

#include <aleph/geometry/distances/Traits.hh>

#include <aleph/math/Statistics.hh>

#include <algorithm>
#include <map>
#include <stdexcept>
#include <vector>

#include <cmath>

namespace aleph
{

namespace containers
{

/*
 Wrapper class for representing a sequence of correlation dimension
 integral values. I want the interface to be as clear as possible.
*/

struct CorrelationDimensionSequence
{
  std::vector<double> x;
  std::vector<double> y;
};

/**
  Calculates samples of the correlation dimension integral for a given
  point cloud. This does *not* yet result in a dimension estimate, but
  only produces a set of points.
*/

template <
  class Distance,
  class Container
> CorrelationDimensionSequence correlationDimensionIntegral(
  const Container& container,
  Distance dist = Distance() )
{
  auto n = container.size();
  auto d = container.dimension();

  std::map<double, unsigned> distances;

  aleph::geometry::distances::Traits<Distance> traits;

  for( decltype(n) i = 0; i < n; i++ )
  {
    auto&& p = container[i];

    for( decltype(n) j = i+1; j < n; j++ )
    {
      auto&& q      = container[j];
      auto distance = dist( p.begin(),
                            q.begin(),
                            d );

      distances[ traits.from( distance ) ] += 1;
    }
  }

  CorrelationDimensionSequence cds;
  cds.x.reserve( distances.size() );
  cds.y.reserve( distances.size() );

  // Determine the correlation dimension integral for all potential
  // values. This only requires counting how many *pairs* have been
  // seen by the algorithm.

  unsigned seen = 0;
  for( auto&& pair : distances )
  {
    auto&& distance = pair.first;
    auto&& count    = pair.second;

    seen += count;

    if( distance > 0 )
    {
      cds.x.push_back( distance );
      cds.y.push_back( seen / ( static_cast<double>( n * (n-1) ) * 0.5 ) );
    }
  }

  return cds;
}

/**
  Estimates the correlation dimension from a correlation dimension
  sequence, which involves calculating a log-log plot of the data,
  and determining the best coefficient for a linear fit.
*/

double correlationDimension( const CorrelationDimensionSequence& cds )
{
  if( cds.x.size() != cds.y.size() )
    throw std::runtime_error( "Inconsistent correlation dimension sequence" );

  std::vector<double> X;
  std::vector<double> Y;

  X.reserve( cds.x.size() );
  Y.reserve( cds.y.size() );

  auto log = [] ( double x )
  {
    return std::log( x );
  };

  std::transform( cds.x.begin(), cds.x.end(), std::back_inserter( X ), log );
  std::transform( cds.y.begin(), cds.y.end(), std::back_inserter( Y ), log );

  // This is a simple linear regression model. We are only interested in
  // the slope of the regression line, so this is sufficient.

  auto cov
    = aleph::math::sampleCovariance( X.begin(), X.end(),
                                     Y.begin(), Y.end() );

  auto var
    = aleph::math::sampleVariance( X.begin(), X.end() );

  return cov / var;
}

} // namespace containers

} // namespace aleph

#endif
<|endoftext|>


<commit_before>#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_
#define CLOTHO_BIT_BLOCK_FITNESS_HPP_

#include <iostream>
#include "clotho/fitness/bit_block_genotyper.hpp"
#include "clotho/utility/bit_block_iterator.hpp"

namespace clotho {
namespace fitness {

struct no_fit {};

template < class HetFit, class AltHomFit, class RefHomFit, class Result = double >
class bit_block_fitness {
public:
    typedef Result result_type;

    bit_block_fitness() {}

    bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) :
        m_hets( hets )
        , m_ahoms(ahoms)
        , m_rhoms(rhoms) {
    }

    template < class Block, class ElementIterator >
    result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
        result_type res = f;

        typedef bit_block_genotyper< Block >                    genotyper;

        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms);
        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms);

        return res;
    }

    virtual ~bit_block_fitness() {}
protected:

    template < class Block, class ElementIterator, class FitOp >
    void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
        typedef clotho::utility::bit_block_iterator< Block >    iterator;

        iterator it( b ), end;
        while( it != end ) {
            (*op)( res, *(first + *it++));
        }
    }

    template < class Block, class ElementIterator, class SetOp, class FitOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
        Block bits = ( (*sop)(b0, b1) & keep );
        computeFitness( res, bits, first, op );
    }

    template < class Block, class ElementIterator, class SetOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }

    HetFit      m_hets;
    AltHomFit   m_ahoms;
    RefHomFit   m_rhoms;
};

template < class HetFit, class HomFit, class Result >
class bit_block_fitness< HetFit, HomFit, HomFit, Result > {
public:
    typedef Result result_type;

    bit_block_fitness( ) {}

    bit_block_fitness( const HetFit & hets, const HomFit & homs ) :
        m_hets( hets )
        , m_homs(homs) {
    }

    template < class Block, class ElementIterator >
    result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
        result_type res = f;

        typedef bit_block_genotyper< Block >                    genotyper;

        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs);

        return res;
    }

    virtual ~bit_block_fitness() {}
protected:
    template < class Block, class ElementIterator, class FitOp >
    inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
        typedef clotho::utility::bit_block_iterator< Block >    iterator;

        iterator it( b ), end;
        while( it != end ) {
            (*op)( res, *(first + *it++));
        }
    }

    template < class Block, class ElementIterator, class SetOp, class FitOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
        Block bits = ( (*sop)(b0, b1) & keep );
        computeFitness( res, bits, first, op );
    }

    template < class Block, class ElementIterator, class SetOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }

    HetFit   m_hets;
    HomFit   m_homs;
};

template < class Result >
class bit_block_fitness< no_fit, no_fit, no_fit, Result > {
public:
    typedef Result result_type;

    bit_block_fitness( ) {}

    template < class Block, class ElementIterator >
    result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
        return f;
    }

    virtual ~bit_block_fitness() {}
};

}   // namespace fitness {
}   // namespace clotho {

#endif  // CLOTHO_BIT_BLOCK_FITNESS_HPP_
<commit_msg>utilizing new bit walking based iterator<commit_after>#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_
#define CLOTHO_BIT_BLOCK_FITNESS_HPP_

#include <iostream>
#include "clotho/fitness/bit_block_genotyper.hpp"
#include "clotho/utility/bit_block_iterator.hpp"

namespace clotho {
namespace fitness {

struct no_fit {};

template < class HetFit, class AltHomFit, class RefHomFit, class Result = double >
class bit_block_fitness {
public:
    typedef Result result_type;

    bit_block_fitness() {}

    bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) :
        m_hets( hets )
        , m_ahoms(ahoms)
        , m_rhoms(rhoms) {
    }

    template < class Block, class ElementIterator >
    result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
        result_type res = f;

        typedef bit_block_genotyper< Block >                    genotyper;

        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms);
        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms);

        return res;
    }

    virtual ~bit_block_fitness() {}
protected:

    template < class Block, class ElementIterator, class FitOp >
    void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
        typedef clotho::utility::bit_block_iterator< Block, clotho::utility::walk_iterator_tag >    iterator;

        iterator it( b ), end;
        while( it != end ) {
            (*op)( res, *(first + *it++));
        }
    }

    template < class Block, class ElementIterator, class SetOp, class FitOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
        Block bits = ( (*sop)(b0, b1) & keep );
        computeFitness( res, bits, first, op );
    }

    template < class Block, class ElementIterator, class SetOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }

    HetFit      m_hets;
    AltHomFit   m_ahoms;
    RefHomFit   m_rhoms;
};

template < class HetFit, class HomFit, class Result >
class bit_block_fitness< HetFit, HomFit, HomFit, Result > {
public:
    typedef Result result_type;

    bit_block_fitness( ) {}

    bit_block_fitness( const HetFit & hets, const HomFit & homs ) :
        m_hets( hets )
        , m_homs(homs) {
    }

    template < class Block, class ElementIterator >
    result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
        result_type res = f;

        typedef bit_block_genotyper< Block >                    genotyper;

        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);
        computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs);

        return res;
    }

    virtual ~bit_block_fitness() {}
protected:
    template < class Block, class ElementIterator, class FitOp >
    inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {
        typedef clotho::utility::bit_block_iterator< Block >    iterator;

        iterator it( b ), end;
        while( it != end ) {
            (*op)( res, *(first + *it++));
        }
    }

    template < class Block, class ElementIterator, class SetOp, class FitOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {
        Block bits = ( (*sop)(b0, b1) & keep );
        computeFitness( res, bits, first, op );
    }

    template < class Block, class ElementIterator, class SetOp >
    inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }

    HetFit   m_hets;
    HomFit   m_homs;
};

template < class Result >
class bit_block_fitness< no_fit, no_fit, no_fit, Result > {
public:
    typedef Result result_type;

    bit_block_fitness( ) {}

    template < class Block, class ElementIterator >
    result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {
        return f;
    }

    virtual ~bit_block_fitness() {}
};

}   // namespace fitness {
}   // namespace clotho {

#endif  // CLOTHO_BIT_BLOCK_FITNESS_HPP_
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Pose.h>
#include <sensor_msgs/PointCloud.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib_msgs/GoalStatusArray.h>
#include <tf/transform_listener.h>
#include <stdlib.h>

double goal_tolerance, frontier_tolerance;
bool random_frontier;
std::string map_frame, base_frame, goal_topic;
sensor_msgs::PointCloud global_frontiers;
geometry_msgs::Point32 frontier, old_frontier;
tf::TransformListener* listener;
actionlib_msgs::GoalStatusArray global_status;
std::vector<geometry_msgs::Point32> reached_frontiers;
template <class T1, class T2>
double distance(T1 from, T2 to)
{
    return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2));
}

bool  my_pose(geometry_msgs::Pose *pose)
{
    tf::StampedTransform transform;
    try {
        listener->lookupTransform(map_frame, base_frame, ros::Time(0), transform);
      } catch(tf::TransformException ex) {
        //ROS_ERROR("TF %s - %s: %s", map_frame.c_str(), base_frame.c_str(), ex.what());
        return false;
      }
    pose->position.x =  transform.getOrigin().getX();
    pose->position.y =  transform.getOrigin().getY();
    pose->position.z =  transform.getOrigin().getZ();
    pose->orientation.x = transform.getRotation().getX();
    pose->orientation.y = transform.getRotation().getY();
    pose->orientation.z = transform.getRotation().getZ();
    return true;
}

void frontier_callback(const sensor_msgs::PointCloud::ConstPtr &msg)
{
    global_frontiers = *msg;
}

void status_callback(const actionlib_msgs::GoalStatusArray::ConstPtr &msg){
    global_status = *msg;
}

bool frontier_blacklisting( geometry_msgs::Point32 p)
{
    std::vector<geometry_msgs::Point32>::iterator it;

    for(it = reached_frontiers.begin(); it != reached_frontiers.end(); it++)
    {
        double dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(*it, p);
        if(dist < goal_tolerance) return false;
    }
    return true;
}

bool find_next_frontier()
{

    geometry_msgs::Pose pose;
    if(!my_pose(&pose))
    {
        //ROS_WARN("Cannot find my pose");
        return false;
    }

    double dist = distance<geometry_msgs::Point,  geometry_msgs::Point32>(pose.position, frontier);
    if(dist > goal_tolerance)
    {
        for (int i = 0; i < global_status.status_list.size(); i++)
        {
            int stat = global_status.status_list[i].status;
            if (stat == 1) return false;
        }

    } else {
        reached_frontiers.push_back(frontier);
    }

    if(global_frontiers.points.size() == 0)
    {
        ROS_WARN("No frontier to allocate at this time");
        return false;
    }

    if(random_frontier )
    {
        old_frontier = frontier;
        frontier = global_frontiers.points[ rand() % global_frontiers.points.size()];
        return true;
    }

    // nearest frontier allocation
    double mindist = 0, fr_dist;
    bool allocated = false;
    old_frontier = frontier;
    for (int i = 0; i < global_frontiers.points.size(); i++)
    {
        if(!frontier_blacklisting(global_frontiers.points[i])) continue;
        dist = distance<geometry_msgs::Point, geometry_msgs::Point32>(pose.position, global_frontiers.points[i]);
        fr_dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(old_frontier, global_frontiers.points[i]);
        if ( ( old_frontier.x == 0 && old_frontier.y == 0 ) ||( (mindist == 0 || dist < mindist) && dist > goal_tolerance && fr_dist > frontier_tolerance))
        {
            frontier = global_frontiers.points[i];
            mindist = dist;
            allocated = true;
        }
    }

    return allocated;
}

int main(int argc, char**argv)
{
    ros::init(argc, argv, "frontier_allocator");
    ros::NodeHandle private_nh("~");
    listener = new tf::TransformListener();
    private_nh.param<double>("goal_tolerance", goal_tolerance, 0.3);
    private_nh.param<double>("frontier_tolerance", frontier_tolerance, 0.3);
    private_nh.param<bool>("random_frontier", random_frontier, false);
    private_nh.param<std::string>("map_frame", map_frame, "map");
    private_nh.param<std::string>("base_frame", base_frame, "base_link");
    private_nh.param<std::string>("goal_topic", goal_topic, "/move_base_simple/goal");

    ros::Subscriber sub_ph = private_nh.subscribe<sensor_msgs::PointCloud>("/phrontier_global", 100, &frontier_callback);
    ros::Publisher  pub_goal = private_nh.advertise<geometry_msgs::PoseStamped>(goal_topic, 10);
    ros::Subscriber sub_status = private_nh.subscribe<actionlib_msgs::GoalStatusArray>("/move_base/status", 10, &status_callback);

    srand(time(NULL));

    ros::Rate loop_rate(3.0);
    while (ros::ok())
    {
        ros::spinOnce();
        if (find_next_frontier())
        {
            geometry_msgs::PoseStamped goal;
            goal.header.frame_id = map_frame;
            goal.pose.position.x = frontier.x;
            goal.pose.position.y = frontier.y;

            goal.pose.orientation.x = 0;
            goal.pose.orientation.y = 0;
            goal.pose.orientation.z = 0;
            goal.pose.orientation.w = 1;

            pub_goal.publish(goal);

        }
        loop_rate.sleep();
    }
}<commit_msg>fix frontier allocation<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Pose.h>
#include <sensor_msgs/PointCloud.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib_msgs/GoalStatusArray.h>
#include <tf/transform_listener.h>
#include <stdlib.h>

typedef struct {
    geometry_msgs::Point32 position;
    int weight;
} frontier_t;

double goal_tolerance, frontier_tolerance;
bool random_frontier;
std::string map_frame, base_frame, goal_topic;
sensor_msgs::PointCloud global_frontiers;
frontier_t frontier, old_frontier;
tf::TransformListener* listener;
actionlib_msgs::GoalStatusArray global_status;
std::vector<frontier_t> reached_frontiers;
template <class T1, class T2>

double distance(T1 from, T2 to)
{
    return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2));
}

bool  my_pose(geometry_msgs::Pose *pose)
{
    tf::StampedTransform transform;
    try {
        listener->lookupTransform(map_frame, base_frame, ros::Time(0), transform);
      } catch(tf::TransformException ex) {
        //ROS_ERROR("TF %s - %s: %s", map_frame.c_str(), base_frame.c_str(), ex.what());
        return false;
      }
    pose->position.x =  transform.getOrigin().getX();
    pose->position.y =  transform.getOrigin().getY();
    pose->position.z =  transform.getOrigin().getZ();
    pose->orientation.x = transform.getRotation().getX();
    pose->orientation.y = transform.getRotation().getY();
    pose->orientation.z = transform.getRotation().getZ();
    return true;
}

void frontier_callback(const sensor_msgs::PointCloud::ConstPtr &msg)
{
    global_frontiers = *msg;
}

void status_callback(const actionlib_msgs::GoalStatusArray::ConstPtr &msg){
    global_status = *msg;
}

frontier_t frontier_blacklisting( geometry_msgs::Point32 p)
{
    frontier_t fr;
    fr.weight = 0;
    fr.position = p;
    std::vector<frontier_t>::iterator it;

    for(it = reached_frontiers.begin(); it != reached_frontiers.end(); it++)
    {
        double dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(it->position, p);
        if(dist < goal_tolerance)
        {
            fr.weight++;
            return fr;
        }
    }
    return fr;
}

bool find_next_frontier()
{

    geometry_msgs::Pose pose;
    if(!my_pose(&pose))
    {
        //ROS_WARN("Cannot find my pose");
        return false;
    }

    double dist = distance<geometry_msgs::Point,  geometry_msgs::Point32>(pose.position, frontier.position);
    if(dist > goal_tolerance)
    {
        for (int i = 0; i < global_status.status_list.size(); i++)
        {
            int stat = global_status.status_list[i].status;
            if (stat == 1) return false;
        }

    } else {
        frontier.weight++;
        reached_frontiers.push_back(frontier);
    }

    if(global_frontiers.points.size() == 0)
    {
        ROS_WARN("No frontier to allocate at this time");
        return false;
    }

    if(random_frontier )
    {
        old_frontier = frontier;
        frontier.weight=0;
        frontier.position = global_frontiers.points[ rand() % global_frontiers.points.size()];
        return true;
    }

    // nearest frontier allocation
    double mindist = 0, fr_dist;
    bool allocated = false;
    old_frontier = frontier;
    frontier_t fr;
    for (int i = 0; i < global_frontiers.points.size(); i++)
    {
        dist = distance<geometry_msgs::Point, geometry_msgs::Point32>(pose.position, global_frontiers.points[i]);
        fr_dist = distance<geometry_msgs::Point32, geometry_msgs::Point32>(old_frontier.position, global_frontiers.points[i]);
        if ( ( old_frontier.position.x == 0 && old_frontier.position.y == 0 ) ||( (mindist == 0 || dist < mindist) && dist > goal_tolerance && fr_dist > frontier_tolerance))
        {
            fr = frontier_blacklisting(global_frontiers.points[i]);
            if(fr.weight <= frontier.weight)
            {
                frontier = fr;
                mindist = dist;
                allocated = true;
            }

        }
    }

    return allocated;
}

int main(int argc, char**argv)
{
    ros::init(argc, argv, "frontier_allocator");
    ros::NodeHandle private_nh("~");
    listener = new tf::TransformListener();
    private_nh.param<double>("goal_tolerance", goal_tolerance, 0.3);
    private_nh.param<double>("frontier_tolerance", frontier_tolerance, 0.3);
    private_nh.param<bool>("random_frontier", random_frontier, false);
    private_nh.param<std::string>("map_frame", map_frame, "map");
    private_nh.param<std::string>("base_frame", base_frame, "base_link");
    private_nh.param<std::string>("goal_topic", goal_topic, "/move_base_simple/goal");

    ros::Subscriber sub_ph = private_nh.subscribe<sensor_msgs::PointCloud>("/phrontier_global", 100, &frontier_callback);
    ros::Publisher  pub_goal = private_nh.advertise<geometry_msgs::PoseStamped>(goal_topic, 10);
    ros::Subscriber sub_status = private_nh.subscribe<actionlib_msgs::GoalStatusArray>("/move_base/status", 10, &status_callback);

    srand(time(NULL));

    ros::Rate loop_rate(3.0);
    while (ros::ok())
    {
        ros::spinOnce();
        if (find_next_frontier())
        {
            geometry_msgs::PoseStamped goal;
            goal.header.frame_id = map_frame;
            goal.pose.position.x = frontier.position.x;
            goal.pose.position.y = frontier.position.y;

            goal.pose.orientation.x = 0;
            goal.pose.orientation.y = 0;
            goal.pose.orientation.z = 0;
            goal.pose.orientation.w = 1;

            pub_goal.publish(goal);

        }
        loop_rate.sleep();
    }
}<|endoftext|>


<commit_before>#pragma once
#include <string>
#include <unordered_map>
#include <vector>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/CameraInfo.hpp"
#include "depthai-shared/common/Extrinsics.hpp"
#include "depthai-shared/common/Point3f.hpp"
#include "depthai-shared/common/StereoRectification.hpp"

// libraries
#include "nlohmann/json.hpp"

namespace dai {
/**
 * EepromData structure
 *
 * Contains the Calibration and Board data stored on device
 */
struct EepromData {
    uint32_t version = 6;
    bool swapLeftRightCam = false;
    std::string boardName, boardRev;
    std::unordered_map<CameraBoardSocket, CameraInfo> cameraData;
    StereoRectification stereoRectificationData;
    Extrinsics imuExtrinsics;
    std::vector<uint8_t> miscellaneousData;
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData);
};

}  // namespace dai
<commit_msg>remvoed swap<commit_after>#pragma once
#include <string>
#include <unordered_map>
#include <vector>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/CameraInfo.hpp"
#include "depthai-shared/common/Extrinsics.hpp"
#include "depthai-shared/common/Point3f.hpp"
#include "depthai-shared/common/StereoRectification.hpp"

// libraries
#include "nlohmann/json.hpp"

namespace dai {
/**
 * EepromData structure
 *
 * Contains the Calibration and Board data stored on device
 */
struct EepromData {
    uint32_t version = 6;
    std::string boardName, boardRev;
    std::unordered_map<CameraBoardSocket, CameraInfo> cameraData;
    StereoRectification stereoRectificationData;
    Extrinsics imuExtrinsics;
    std::vector<uint8_t> miscellaneousData;
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData);
};

}  // namespace dai
<|endoftext|>


<commit_before>// Copyright (c) 2014, Salesforce.com, Inc.  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 Salesforce.com nor the names of its contributors
//   may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/gzip_stream.h>
#include <distributions/common.hpp>

namespace distributions
{
namespace protobuf
{

inline bool startswith (const char * filename, const char * prefix)
{
    return strlen(filename) >= strlen(prefix) and
        strncmp(filename, prefix, strlen(prefix)) == 0;
}

inline bool endswith (const char * filename, const char * suffix)
{
    return strlen(filename) >= strlen(suffix) and
        strcmp(filename + strlen(filename) - strlen(suffix), suffix) == 0;
}

class InFile
{
public:

    InFile (const char * filename) : filename_(filename)
    {
        if (startswith(filename, "-")) {
            fid_ = -1;
            raw_ = new google::protobuf::io::IstreamInputStream(& std::cin);
        } else {
            fid_ = open(filename, O_RDONLY | O_NOATIME);
            DIST_ASSERT(fid_ != -1, "failed to open input file " << filename);
            raw_ = new google::protobuf::io::FileInputStream(fid_);
        }

        if (endswith(filename, ".gz")) {
            gzip_ = new google::protobuf::io::GzipInputStream(raw_);
            coded_ = new google::protobuf::io::CodedInputStream(gzip_);
        } else {
            gzip_ = nullptr;
            coded_ = new google::protobuf::io::CodedInputStream(raw_);
        }
    }

    ~InFile ()
    {
        delete coded_;
        delete gzip_;
        delete raw_;
        if (fid_ != -1) {
            close(fid_);
        }
    }

    template<class Message>
    void read (Message & message)
    {
        bool success = message.ParseFromCodedStream(coded_);
        DIST_ASSERT(success, "failed to parse message from " << filename_);
    }

    template<class Message>
    bool try_read_stream (Message & message)
    {
        uint32_t message_size = 0;
        if (DIST_LIKELY(coded_->ReadLittleEndian32(& message_size))) {
            auto old_limit = coded_->PushLimit(message_size);
            bool success = message.ParseFromCodedStream(coded_);
            DIST_ASSERT(success, "failed to parse message from " << filename_);
            coded_->PopLimit(old_limit);
            return true;
        } else {
            return false;
        }
    }

private:

    const std::string filename_;
    int fid_;
    google::protobuf::io::ZeroCopyInputStream * raw_;
    google::protobuf::io::GzipInputStream * gzip_;
    google::protobuf::io::CodedInputStream * coded_;
};

class OutFile
{
public:

    OutFile (const char * filename) : filename_(filename)
    {
        if (startswith(filename, "-")) {
            fid_ = -1;
            raw_ = new google::protobuf::io::OstreamOutputStream(& std::cout);
        } else {
            fid_ = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664);
            DIST_ASSERT(fid_ != -1, "failed to open output file " << filename);
            raw_ = new google::protobuf::io::FileOutputStream(fid_);
        }

        if (endswith(filename, ".gz")) {
            gzip_ = new google::protobuf::io::GzipOutputStream(raw_);
            coded_ = new google::protobuf::io::CodedOutputStream(gzip_);
        } else {
            gzip_ = nullptr;
            coded_ = new google::protobuf::io::CodedOutputStream(raw_);
        }
    }

    ~OutFile ()
    {
        delete coded_;
        delete gzip_;
        delete raw_;
        if (fid_ != -1) {
            close(fid_);
        }
    }

    template<class Message>
    void write (Message & message)
    {
        DIST_ASSERT1(message.IsInitialized(), "message not initialized");
        message.ByteSize();
        message.SerializeWithCachedSizes(coded_);
    }

    template<class Message>
    void write_stream (Message & message)
    {
        DIST_ASSERT1(message.IsInitialized(), "message not initialized");
        uint32_t message_size = message.ByteSize();
        DIST_ASSERT1(message_size > 0, "zero sized message");
        coded_->WriteLittleEndian32(message_size);
        message.SerializeWithCachedSizes(coded_);
    }

private:

    const std::string filename_;
    int fid_;
    google::protobuf::io::ZeroCopyOutputStream * raw_;
    google::protobuf::io::GzipOutputStream * gzip_;
    google::protobuf::io::CodedOutputStream * coded_;
};

} // namespace protobuf
} // namespace distributions
<commit_msg>Add assertion to protobuf::OutFile::write<commit_after>// Copyright (c) 2014, Salesforce.com, Inc.  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 Salesforce.com nor the names of its contributors
//   may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/gzip_stream.h>
#include <distributions/common.hpp>

namespace distributions
{
namespace protobuf
{

inline bool startswith (const char * filename, const char * prefix)
{
    return strlen(filename) >= strlen(prefix) and
        strncmp(filename, prefix, strlen(prefix)) == 0;
}

inline bool endswith (const char * filename, const char * suffix)
{
    return strlen(filename) >= strlen(suffix) and
        strcmp(filename + strlen(filename) - strlen(suffix), suffix) == 0;
}

class InFile
{
public:

    InFile (const char * filename) : filename_(filename)
    {
        if (startswith(filename, "-")) {
            fid_ = -1;
            raw_ = new google::protobuf::io::IstreamInputStream(& std::cin);
        } else {
            fid_ = open(filename, O_RDONLY | O_NOATIME);
            DIST_ASSERT(fid_ != -1, "failed to open input file " << filename);
            raw_ = new google::protobuf::io::FileInputStream(fid_);
        }

        if (endswith(filename, ".gz")) {
            gzip_ = new google::protobuf::io::GzipInputStream(raw_);
            coded_ = new google::protobuf::io::CodedInputStream(gzip_);
        } else {
            gzip_ = nullptr;
            coded_ = new google::protobuf::io::CodedInputStream(raw_);
        }
    }

    ~InFile ()
    {
        delete coded_;
        delete gzip_;
        delete raw_;
        if (fid_ != -1) {
            close(fid_);
        }
    }

    template<class Message>
    void read (Message & message)
    {
        bool success = message.ParseFromCodedStream(coded_);
        DIST_ASSERT(success, "failed to parse message from " << filename_);
    }

    template<class Message>
    bool try_read_stream (Message & message)
    {
        uint32_t message_size = 0;
        if (DIST_LIKELY(coded_->ReadLittleEndian32(& message_size))) {
            auto old_limit = coded_->PushLimit(message_size);
            bool success = message.ParseFromCodedStream(coded_);
            DIST_ASSERT(success, "failed to parse message from " << filename_);
            coded_->PopLimit(old_limit);
            return true;
        } else {
            return false;
        }
    }

private:

    const std::string filename_;
    int fid_;
    google::protobuf::io::ZeroCopyInputStream * raw_;
    google::protobuf::io::GzipInputStream * gzip_;
    google::protobuf::io::CodedInputStream * coded_;
};

class OutFile
{
public:

    OutFile (const char * filename) : filename_(filename)
    {
        if (startswith(filename, "-")) {
            fid_ = -1;
            raw_ = new google::protobuf::io::OstreamOutputStream(& std::cout);
        } else {
            fid_ = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664);
            DIST_ASSERT(fid_ != -1, "failed to open output file " << filename);
            raw_ = new google::protobuf::io::FileOutputStream(fid_);
        }

        if (endswith(filename, ".gz")) {
            gzip_ = new google::protobuf::io::GzipOutputStream(raw_);
            coded_ = new google::protobuf::io::CodedOutputStream(gzip_);
        } else {
            gzip_ = nullptr;
            coded_ = new google::protobuf::io::CodedOutputStream(raw_);
        }
    }

    ~OutFile ()
    {
        delete coded_;
        delete gzip_;
        delete raw_;
        if (fid_ != -1) {
            close(fid_);
        }
    }

    template<class Message>
    void write (Message & message)
    {
        DIST_ASSERT1(message.IsInitialized(), "message not initialized");
        bool success = message.SerializeToCodedStream(coded_);
        DIST_ASSERT(success, "failed to serialize message to " << filename_);
    }

    template<class Message>
    void write_stream (Message & message)
    {
        DIST_ASSERT1(message.IsInitialized(), "message not initialized");
        uint32_t message_size = message.ByteSize();
        DIST_ASSERT1(message_size > 0, "zero sized message");
        coded_->WriteLittleEndian32(message_size);
        message.SerializeWithCachedSizes(coded_);
    }

private:

    const std::string filename_;
    int fid_;
    google::protobuf::io::ZeroCopyOutputStream * raw_;
    google::protobuf::io::GzipOutputStream * gzip_;
    google::protobuf::io::CodedOutputStream * coded_;
};

} // namespace protobuf
} // namespace distributions
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "../../include/SQLiteDatabase.h"

#include <iostream>
#include <fstream>
#include <vector>

bool fexists(const std::string& filename) {
  std::ifstream ifile(filename.c_str());
  return ifile;
};

class SQLiteDatabaseTestFixture : public ::testing::Test {
public:
    SQLiteDatabaseTestFixture( ) {
        test_database_filename_ = "test.db";
    }

    void SetUp( ) {
        // code here will execute just before the test ensues
    }

    void TearDown( ) {
        // code here will be called just after the test completes
        // ok to through exceptions from here if need be
    }

    ~SQLiteDatabaseTestFixture( )  {
        remove("test.db");
    }

    // Test Member Variables
    std::string test_database_filename_;
};

TEST_F(SQLiteDatabaseTestFixture, create_database_test) {

    sqlite::SQLiteDatabase db;

    try{
        db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
        db.close();
    }
    catch (const std::exception & e) {
        std::cout << e.what() << std::endl;
    }

    ASSERT_TRUE(fexists(test_database_filename_));
}

TEST_F(SQLiteDatabaseTestFixture, database_version_test) {

    sqlite::SQLiteDatabase db;
    try{
        db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
    }
    catch (const std::exception & e){
        std::cout << e.what() << std::endl;
    }

    int expected_version = 1;
    db.setVersion(expected_version);
    auto version = db.getVersion();

    db.close();

    EXPECT_EQ(expected_version, version);
}

TEST_F(SQLiteDatabaseTestFixture, get_readonly_database_test) {

    sqlite::SQLiteDatabase db;

    int expected_version = 1;
    int version = 0;

    try{
        db.open(test_database_filename_, SQLITE_OPEN_READONLY);

        EXPECT_ANY_THROW(db.setVersion(expected_version));

        db.close();
    }
    catch (const std::exception & e){
        std::cout << e.what() << std::endl;
    }
}

TEST_F(SQLiteDatabaseTestFixture, query_test) {

    sqlite::SQLiteDatabase db;

    try{
        db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);

        // Create Cars table test data
        const std::string kCreateTable =
                "CREATE TABLE IF NOT EXISTS cars "
                        "(mpg text, "
                        "weight text)";

        db.execQuery(kCreateTable);

        db.execQuery("INSERT INTO cars "
                             "VALUES('34', '2000')");

        db.execQuery("INSERT INTO cars "
                             "VALUES('27', '25000')");

        db.execQuery("INSERT INTO cars "
                             "VALUES('16', '5000')");

        std::vector<std::string> columns;
        columns.push_back("mpg");
        columns.push_back("weight");

        std::string selection;

        std::vector<std::string> selectionArgs;

        auto c = db.query(true, "cars", columns, selection, selectionArgs, "", "", "");

        c.next();
        EXPECT_STREQ(c.getString(1).c_str(), "34");
        EXPECT_STREQ(c.getString(2).c_str(), "2000");
        c.next();
        EXPECT_STREQ(c.getString(1).c_str(), "27");
        EXPECT_STREQ(c.getString(2).c_str(), "25000");
        c.next();
        EXPECT_STREQ(c.getString(1).c_str(), "16");
        EXPECT_STREQ(c.getString(2).c_str(), "5000");

        db.close();
    }
    catch (const std::exception & e){
        std::cout << e.what() << std::endl;
    }
}

<commit_msg>added insert unit test<commit_after>#include <gtest/gtest.h>
#include "../../include/SQLiteDatabase.h"

#include <iostream>
#include <fstream>
#include <vector>

bool fexists(const std::string& filename) {
  std::ifstream ifile(filename.c_str());
  return ifile;
};

class SQLiteDatabaseTestFixture : public ::testing::Test {
public:
    SQLiteDatabaseTestFixture( ) {
        test_database_filename_ = "test.db";
    }

    void SetUp( ) {
        // code here will execute just before the test ensues
    }

    void TearDown( ) {
        // code here will be called just after the test completes
        // ok to through exceptions from here if need be
    }

    ~SQLiteDatabaseTestFixture( )  {
        remove("test.db");
    }

    // Test Member Variables
    std::string test_database_filename_;
};

TEST_F(SQLiteDatabaseTestFixture, create_database_test) {

    sqlite::SQLiteDatabase db;

    try{
        db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
        db.close();
    }
    catch (const std::exception & e) {
        std::cout << e.what() << std::endl;
    }

    ASSERT_TRUE(fexists(test_database_filename_));
}

TEST_F(SQLiteDatabaseTestFixture, database_version_test) {

    sqlite::SQLiteDatabase db;
    try{
        db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
    }
    catch (const std::exception & e){
        std::cout << e.what() << std::endl;
    }

    int expected_version = 1;
    db.setVersion(expected_version);
    auto version = db.getVersion();

    db.close();

    EXPECT_EQ(expected_version, version);
}

TEST_F(SQLiteDatabaseTestFixture, get_readonly_database_test) {

    sqlite::SQLiteDatabase db;

    int expected_version = 1;
    int version = 0;

    try{
        db.open(test_database_filename_, SQLITE_OPEN_READONLY);

        EXPECT_ANY_THROW(db.setVersion(expected_version));

        db.close();
    }
    catch (const std::exception & e){
        std::cout << e.what() << std::endl;
    }
}

TEST_F(SQLiteDatabaseTestFixture, query_test) {

    sqlite::SQLiteDatabase db;

    try{
        db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);

        // Create Cars table test data
        const std::string kCreateTable =
                "CREATE TABLE IF NOT EXISTS cars "
                        "(mpg text, "
                        "weight text)";

        db.execQuery(kCreateTable);

        db.execQuery("INSERT INTO cars "
                             "VALUES('34', '2000')");

        db.execQuery("INSERT INTO cars "
                             "VALUES('27', '25000')");

        db.execQuery("INSERT INTO cars "
                             "VALUES('16', '5000')");

        std::vector<std::string> columns;
        columns.push_back("mpg");
        columns.push_back("weight");

        std::string selection;

        std::vector<std::string> selectionArgs;

        auto c = db.query(true, "cars", columns, selection, selectionArgs, "", "", "");

        c.next();
        EXPECT_STREQ(c.getString(1).c_str(), "34");
        EXPECT_STREQ(c.getString(2).c_str(), "2000");
        c.next();
        EXPECT_STREQ(c.getString(1).c_str(), "27");
        EXPECT_STREQ(c.getString(2).c_str(), "25000");
        c.next();
        EXPECT_STREQ(c.getString(1).c_str(), "16");
        EXPECT_STREQ(c.getString(2).c_str(), "5000");

        db.close();
    }
    catch (const std::exception & e){
        std::cout << e.what() << std::endl;
    }
}

TEST_F(SQLiteDatabaseTestFixture, insert_test) {

    sqlite::SQLiteDatabase db;

    try{
        db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);

        // Create Cars table test data
        const std::string kCreateTable =
                "CREATE TABLE IF NOT EXISTS cars "
                        "(mpg text, "
                        "weight text)";

        db.execQuery(kCreateTable);

        const std::string table = "cars";
        long id = db.insert(table, std::vector<std::string>{"mpg", "weight"}, std::vector<std::string>{"34", "2000"}, "", std::vector<std::string>{});
        long id2 = db.insert(table, std::vector<std::string>{"mpg", "weight"}, std::vector<std::string>{"20", "1500"}, "", std::vector<std::string>{});

        EXPECT_EQ(id, 1);
        EXPECT_EQ(id2, 2);

        db.close();
    }
        catch (const std::exception & e){
        std::cout << e.what() << std::endl;
    }
}

<|endoftext|>


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

#include <chrono>
#include <iostream>

#include "gtest/gtest.h"

#include "rclcpp/rclcpp.hpp"

#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif

TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete) {
  auto node = rclcpp::Node::make_shared("test_spin");

  // Construct a fake future to wait on
  std::promise<bool> promise;
  std::shared_future<bool> future(promise.get_future());

  // Make a timer to complete the promise in the future
  int i = 0;
  auto callback = [&promise, &i]() {
      if (i > 0) {
        promise.set_value(true);
      }
      ++i;
    };
  auto timer = node->create_wall_timer(std::chrono::milliseconds(25), callback);

  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future),
    rclcpp::executors::FutureReturnCode::SUCCESS);
  EXPECT_EQ(future.get(), true);
}

TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_timeout) {
  auto node = rclcpp::Node::make_shared("test_spin");

  // Construct a fake future to wait on
  std::promise<bool> promise;
  std::shared_future<bool> future(promise.get_future());

  // Make a timer to complete the promise in the future
  int i = 0;
  auto callback = [&promise, &i]() {
      if (i > 0) {
        promise.set_value(true);
      }
      ++i;
    };
  auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);

  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(25)),
    rclcpp::executors::FutureReturnCode::TIMEOUT);

  // If we wait a little longer, we should complete the future
  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),
    rclcpp::executors::FutureReturnCode::SUCCESS);

  EXPECT_EQ(future.get(), true);
}

TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_interrupted) {
  auto node = rclcpp::Node::make_shared("test_spin");

  // Construct a fake future to wait on
  std::promise<bool> promise;
  std::shared_future<bool> future(promise.get_future());

  // Make a timer to complete the promise in the future
  int i = 0;
  auto callback = [&promise, &i]() {
      if (i > 0) {
        promise.set_value(true);
      }
      ++i;
    };
  auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);

  // Create a timer that will shut down rclcpp before
  auto shutdown_callback = []() {
      rclcpp::utilities::shutdown();
    };
  auto shutdown_timer = node->create_wall_timer(std::chrono::milliseconds(25), shutdown_callback);

  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),
    rclcpp::executors::FutureReturnCode::INTERRUPTED);
}

int main(int argc, char ** argv)
{
  // NOTE: use custom main to ensure that rclcpp::init is called only once
  rclcpp::init(0, nullptr);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>fix timer behavior in test_spin<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <chrono>
#include <iostream>

#include "gtest/gtest.h"

#include "rclcpp/rclcpp.hpp"

#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif

TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete) {
  auto node = rclcpp::Node::make_shared("test_spin");

  // Construct a fake future to wait on
  std::promise<bool> promise;
  std::shared_future<bool> future(promise.get_future());

  // Make a timer to complete the promise in the future
  auto callback = [&promise]() {
      promise.set_value(true);
    };
  auto timer = node->create_wall_timer(std::chrono::milliseconds(25), callback);

  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future),
    rclcpp::executors::FutureReturnCode::SUCCESS);
  EXPECT_EQ(future.get(), true);
}

TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_timeout) {
  auto node = rclcpp::Node::make_shared("test_spin");

  // Construct a fake future to wait on
  std::promise<bool> promise;
  std::shared_future<bool> future(promise.get_future());

  // Make a timer to complete the promise in the future
  auto callback = [&promise]() {
      promise.set_value(true);
    };
  auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);

  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(25)),
    rclcpp::executors::FutureReturnCode::TIMEOUT);

  // If we wait a little longer, we should complete the future
  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),
    rclcpp::executors::FutureReturnCode::SUCCESS);

  EXPECT_EQ(future.get(), true);
}

TEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_interrupted) {
  auto node = rclcpp::Node::make_shared("test_spin");

  // Construct a fake future to wait on
  std::promise<bool> promise;
  std::shared_future<bool> future(promise.get_future());

  // Make a timer to complete the promise in the future
  auto callback = [&promise]() {
      promise.set_value(true);
    };
  auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);

  // Create a timer that will shut down rclcpp before
  auto shutdown_callback = []() {
      rclcpp::utilities::shutdown();
    };
  auto shutdown_timer = node->create_wall_timer(std::chrono::milliseconds(25), shutdown_callback);

  ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),
    rclcpp::executors::FutureReturnCode::INTERRUPTED);
}

int main(int argc, char ** argv)
{
  // NOTE: use custom main to ensure that rclcpp::init is called only once
  rclcpp::init(0, nullptr);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "mocca/base/ByteArray.h"

#include <limits>
#include <algorithm>

static_assert(std::numeric_limits<float>::is_iec559 == true, "Unsupported floating point type");
static_assert(std::numeric_limits<double>::is_iec559 == true, "Unsupported floating point type");

namespace mocca {

const unsigned char ByteArray::trueConst;
const unsigned char ByteArray::falseConst;

ByteArray::ByteArray(uint32_t capacity)
    : data_(new unsigned char[capacity])
    , capacity_(capacity)
    , size_(0)
    , readPos_(0) {}

ByteArray::ByteArray(const ByteArray& other)
    : data_(new unsigned char[other.capacity_])
    , capacity_(other.capacity_)
    , size_(other.size_)
    , readPos_(other.readPos_) {
    memcpy(data_.get(), other.data_.get(), other.size_);
}

ByteArray::ByteArray(ByteArray&& other)
    : data_(std::move(other.data_))
    , capacity_(other.capacity_)
    , size_(other.size_)
    , readPos_(other.readPos_) {
    other.capacity_ = 0;
    other.size_ = 0;
    other.readPos_ = 0;
}

ByteArray& ByteArray::operator=(ByteArray other) {
    swap(other, *this);
    return *this;
}

void swap(ByteArray& lhs, ByteArray& rhs) {
    using std::swap;
    swap(lhs.data_, rhs.data_);
    swap(lhs.capacity_, rhs.capacity_);
    swap(lhs.size_, rhs.size_);
    swap(lhs.readPos_, rhs.readPos_);
}

unsigned char* ByteArray::data() {
    return data_.get();
}

const unsigned char* ByteArray::data() const {
    return data_.get();
}

uint32_t ByteArray::size() const {
    return size_;
}

void ByteArray::setSize(uint32_t size) {
    if (size > capacity_) {
        throw Error("Size exceeds capacity of the byte array", __FILE__, __LINE__);
    }
    size_ = size;
}

bool ByteArray::isEmpty() const {
    return size_ == 0;
}

uint32_t ByteArray::capacity() const {
    return capacity_;
}

void ByteArray::resize(uint32_t newCapacity) {
    auto newData = std::unique_ptr<unsigned char[]>(new unsigned char[newCapacity]);
    memcpy(newData.get(), data_.get(), size_);
    data_ = std::move(newData);
    capacity_ = newCapacity;
}

void ByteArray::append(const void* data, uint32_t size) {
    if (capacity_ < size_ + size) {
        resize(size_ + std::max(2 * size, 256u));
    }
    memcpy(data_.get() + size_, data, size);
    size_ += size;
}

void mocca::ByteArray::append(const ByteArray& byteArray) {
    append(byteArray.data(), byteArray.size());
}

ByteArray ByteArray::createFromRaw(const void* raw, uint32_t size) {
    auto byteArray = ByteArray(size);
    memcpy(byteArray.data_.get(), raw, size);
    byteArray.size_ = size;
    return byteArray;
}

ByteArray& ByteArray::operator<<(int32_t val) {
    append(&val, sizeof(int32_t));
    return *this;
}

ByteArray& ByteArray::operator>>(int32_t& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(int32_t) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(int32_t));
    readPos_ += sizeof(int32_t);
    return *this;
}

ByteArray& ByteArray::operator<<(uint32_t val) {
    return (*this << (int32_t)val);
}

ByteArray& ByteArray::operator>>(uint32_t& val) {
    return (*this >> (int32_t&)val);
}

ByteArray& ByteArray::operator<<(int64_t val) {
    append(&val, sizeof(int64_t));
    return *this;
}

ByteArray& ByteArray::operator>>(int64_t& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(int64_t) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(int64_t));
    readPos_ += sizeof(int64_t);
    return *this;
}

ByteArray& ByteArray::operator<<(uint64_t val) {
    return (*this << (int64_t)val);
}

ByteArray& ByteArray::operator>>(uint64_t& val) {
    return (*this >> (int64_t&)val);
}

ByteArray& ByteArray::operator<<(bool val) {
    if (val) {
        append(&trueConst, sizeof(unsigned char));
    } else {
        append(&falseConst, sizeof(unsigned char));
    }
    return *this;
}

ByteArray& ByteArray::operator>>(bool& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(unsigned char) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    unsigned char code;
    memcpy(&code, data_.get() + readPos_, sizeof(unsigned char));
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (code != trueConst && code != falseConst) {
        throw Error("Package corrupted", __FILE__, __LINE__);
    }
#endif
    val = (code & trueConst) != 0;
    readPos_ += sizeof(unsigned char);
    return *this;
}

ByteArray& ByteArray::operator<<(float val) {
    append(&val, sizeof(float));
    return *this;
}

ByteArray& ByteArray::operator>>(float& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(float) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(float));
    readPos_ += sizeof(float);
    return *this;
}

ByteArray& ByteArray::operator<<(double val) {
    append(&val, sizeof(double));
    return *this;
}

ByteArray& ByteArray::operator>>(double& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(double) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(double));
    readPos_ += sizeof(double);
    return *this;
}

ByteArray& ByteArray::operator<<(const std::string& val) {
    *this << (uint32_t)val.size();
    append(val.c_str(), (uint32_t)val.size());
    return *this;
}

ByteArray& ByteArray::operator>>(std::string& val) {
    uint32_t strSize;
    *this >> strSize;
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + strSize > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    val.reserve(strSize);
    val = std::string((char*)data_.get() + readPos_, strSize);
    readPos_ += strSize;
    return *this;
}

ByteArray& ByteArray::operator<<(const char* val) {
    return (*this << std::string(val));
}

ByteArray& ByteArray::operator<<(const ByteArray& val) {
    *this << (int32_t)val.size();
    append(val.data(), val.size());
    return *this;
}

ByteArray& ByteArray::operator>>(ByteArray& val) {
    int32_t innerSize;
    *this >> innerSize;
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + innerSize > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    val.append(data_.get() + readPos_, innerSize);
    readPos_ += innerSize;
    return *this;
}

unsigned char& mocca::ByteArray::operator[](uint32_t index) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (index < 0 || index >= size_) {
        throw Error("Index out of bounds", __FILE__, __LINE__);
    }
#endif
    return data_[index];
}

const unsigned char& mocca::ByteArray::operator[](uint32_t index) const {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (index < 0 || index >= size_) {
        throw Error("Index out of bounds", __FILE__, __LINE__);
    }
#endif
    return data_[index];
}

void ByteArray::resetReadPos() {
    readPos_ = 0;
}
}<commit_msg>fixed clang warning <commit_after>#include "mocca/base/ByteArray.h"

#include <limits>
#include <algorithm>

static_assert(std::numeric_limits<float>::is_iec559 == true, "Unsupported floating point type");
static_assert(std::numeric_limits<double>::is_iec559 == true, "Unsupported floating point type");

namespace mocca {

const unsigned char ByteArray::trueConst;
const unsigned char ByteArray::falseConst;

ByteArray::ByteArray(uint32_t capacity)
    : data_(new unsigned char[capacity])
    , capacity_(capacity)
    , size_(0)
    , readPos_(0) {}

ByteArray::ByteArray(const ByteArray& other)
    : data_(new unsigned char[other.capacity_])
    , capacity_(other.capacity_)
    , size_(other.size_)
    , readPos_(other.readPos_) {
    memcpy(data_.get(), other.data_.get(), other.size_);
}

ByteArray::ByteArray(ByteArray&& other)
    : data_(std::move(other.data_))
    , capacity_(other.capacity_)
    , size_(other.size_)
    , readPos_(other.readPos_) {
    other.capacity_ = 0;
    other.size_ = 0;
    other.readPos_ = 0;
}

ByteArray& ByteArray::operator=(ByteArray other) {
    swap(other, *this);
    return *this;
}

void swap(ByteArray& lhs, ByteArray& rhs) {
    using std::swap;
    swap(lhs.data_, rhs.data_);
    swap(lhs.capacity_, rhs.capacity_);
    swap(lhs.size_, rhs.size_);
    swap(lhs.readPos_, rhs.readPos_);
}

unsigned char* ByteArray::data() {
    return data_.get();
}

const unsigned char* ByteArray::data() const {
    return data_.get();
}

uint32_t ByteArray::size() const {
    return size_;
}

void ByteArray::setSize(uint32_t size) {
    if (size > capacity_) {
        throw Error("Size exceeds capacity of the byte array", __FILE__, __LINE__);
    }
    size_ = size;
}

bool ByteArray::isEmpty() const {
    return size_ == 0;
}

uint32_t ByteArray::capacity() const {
    return capacity_;
}

void ByteArray::resize(uint32_t newCapacity) {
    auto newData = std::unique_ptr<unsigned char[]>(new unsigned char[newCapacity]);
    memcpy(newData.get(), data_.get(), size_);
    data_ = std::move(newData);
    capacity_ = newCapacity;
}

void ByteArray::append(const void* data, uint32_t size) {
    if (capacity_ < size_ + size) {
        resize(size_ + std::max(2 * size, 256u));
    }
    memcpy(data_.get() + size_, data, size);
    size_ += size;
}

void mocca::ByteArray::append(const ByteArray& byteArray) {
    append(byteArray.data(), byteArray.size());
}

ByteArray ByteArray::createFromRaw(const void* raw, uint32_t size) {
    auto byteArray = ByteArray(size);
    memcpy(byteArray.data_.get(), raw, size);
    byteArray.size_ = size;
    return byteArray;
}

ByteArray& ByteArray::operator<<(int32_t val) {
    append(&val, sizeof(int32_t));
    return *this;
}

ByteArray& ByteArray::operator>>(int32_t& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(int32_t) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(int32_t));
    readPos_ += sizeof(int32_t);
    return *this;
}

ByteArray& ByteArray::operator<<(uint32_t val) {
    return (*this << (int32_t)val);
}

ByteArray& ByteArray::operator>>(uint32_t& val) {
    return (*this >> (int32_t&)val);
}

ByteArray& ByteArray::operator<<(int64_t val) {
    append(&val, sizeof(int64_t));
    return *this;
}

ByteArray& ByteArray::operator>>(int64_t& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(int64_t) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(int64_t));
    readPos_ += sizeof(int64_t);
    return *this;
}

ByteArray& ByteArray::operator<<(uint64_t val) {
    return (*this << (int64_t)val);
}

ByteArray& ByteArray::operator>>(uint64_t& val) {
    return (*this >> (int64_t&)val);
}

ByteArray& ByteArray::operator<<(bool val) {
    if (val) {
        append(&trueConst, sizeof(unsigned char));
    } else {
        append(&falseConst, sizeof(unsigned char));
    }
    return *this;
}

ByteArray& ByteArray::operator>>(bool& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(unsigned char) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    unsigned char code;
    memcpy(&code, data_.get() + readPos_, sizeof(unsigned char));
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (code != trueConst && code != falseConst) {
        throw Error("Package corrupted", __FILE__, __LINE__);
    }
#endif
    val = (code & trueConst) != 0;
    readPos_ += sizeof(unsigned char);
    return *this;
}

ByteArray& ByteArray::operator<<(float val) {
    append(&val, sizeof(float));
    return *this;
}

ByteArray& ByteArray::operator>>(float& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(float) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(float));
    readPos_ += sizeof(float);
    return *this;
}

ByteArray& ByteArray::operator<<(double val) {
    append(&val, sizeof(double));
    return *this;
}

ByteArray& ByteArray::operator>>(double& val) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + sizeof(double) > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    memcpy(&val, data_.get() + readPos_, sizeof(double));
    readPos_ += sizeof(double);
    return *this;
}

ByteArray& ByteArray::operator<<(const std::string& val) {
    *this << (uint32_t)val.size();
    append(val.c_str(), (uint32_t)val.size());
    return *this;
}

ByteArray& ByteArray::operator>>(std::string& val) {
    uint32_t strSize;
    *this >> strSize;
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + strSize > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    val.reserve(strSize);
    val = std::string((char*)data_.get() + readPos_, strSize);
    readPos_ += strSize;
    return *this;
}

ByteArray& ByteArray::operator<<(const char* val) {
    return (*this << std::string(val));
}

ByteArray& ByteArray::operator<<(const ByteArray& val) {
    *this << (int32_t)val.size();
    append(val.data(), val.size());
    return *this;
}

ByteArray& ByteArray::operator>>(ByteArray& val) {
    int32_t innerSize;
    *this >> innerSize;
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (readPos_ + innerSize > size_) {
        throw Error("Reading beyond end of packet", __FILE__, __LINE__);
    }
#endif
    val.append(data_.get() + readPos_, innerSize);
    readPos_ += innerSize;
    return *this;
}

unsigned char& mocca::ByteArray::operator[](uint32_t index) {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (index >= size_) {
        throw Error("Index out of bounds", __FILE__, __LINE__);
    }
#endif
    return data_[index];
}

const unsigned char& mocca::ByteArray::operator[](uint32_t index) const {
#ifdef MOCCA_BYTEARRAY_CHECKS
    if (index >= size_) {
        throw Error("Index out of bounds", __FILE__, __LINE__);
    }
#endif
    return data_[index];
}

void ByteArray::resetReadPos() {
    readPos_ = 0;
}
}<|endoftext|>