text:
// -----------------------------------------------------------------------------
/**
 *  @brief Visual object tracker interface definition
 *  @author Jose M. Buenaposada
 *  @date 2012/07/10
 *  @version $revision$
 *
 *  $id$
 *
 *  Grupo de investigación en Percepción Computacional y Robótica)
 *  (Perception for Computers & Robots research Group)
 *  Facultad de Informática (Computer Science School)
 *  Universidad Politécnica de Madrid (UPM) (Madrid Technical University)
 *  http://www.dia.fi.upm.es/~pcr
 *
 */
// -----------------------------------------------------------------------------

// ------------------ RECURSION PROTECTION -------------------------------------
#ifndef TRACKER_HPP
#define TRACKER_HPP

// ----------------------- INCLUDES --------------------------------------------
#include <boost/shared_ptr.hpp>
#include "viewer.hpp"
#include "optimizer.hpp"
#include "motion_model.hpp"
#include <vector>
#include <exception>
#include "img_align_lib.hpp"

namespace upm { namespace pcr
{
// ----------------------------------------------------------------------------
/**
 *  Definition of exceptions
 */
// -----------------------------------------------------------------------------
class params_incorrect: public std::exception {};

// ----------------------------------------------------------------------------
/**
 *  Definition of an smart pointer to Tracker type
 */
// -----------------------------------------------------------------------------
class Tracker;
typedef boost::shared_ptr<Tracker> TrackerPtr;

// -----------------------------------------------------------------------------
/**
 *  Definition of a container of smart pointers to trackers
 */
// -----------------------------------------------------------------------------
typedef std::vector<Tracker> Trackers;

// ----------------------------------------------------------------------------
/**
 * @class Tracker
 * @brief A class that defines the interface for a visual tracker.
 */
// -----------------------------------------------------------------------------
class Tracker
{
public:

  Tracker
    (
    OptimizerPtr optim
    );

  virtual ~Tracker
    ();

  /**
   * @brief Track the target object to the current frame.
   *
   * @param frame Image comming from the camera.
   */
  virtual void
  processFrame
   (
   cv::Mat& frame
   );

  /**
   * @brief Shows the tracking resultis on a given Viewer.
   *
   * @param viewer The viewer over to which display results.
   * @param frame Last processed camera frame.
   */
  virtual void
  showResults
   (
   Viewer& viewer,
   cv::Mat& frame
   );

  void
  setInitialParams
    (
    cv::Mat initial_params
    );

  void
  setNumPyramidLevels
    (
    uint num_pyramid_levels
    ) { if (num_pyramid_levels > 0) m_num_pyramid_levels = num_pyramid_levels; };

  cv::Mat
  getMotionParams
    ();

  MotionModelPtr
  getMotionModel
    ();

  /**
   * @brief Sets the maximal cost function value for declare sucess in tracking.
   */
  void
  setMaximalCostFunctionValue
    (
    double max_cost
    ) { m_max_cost = max_cost; }

  bool
  isLost
    ();

protected:
  cv::Mat m_motion_params;
  double m_max_cost;
  uint m_num_pyramid_levels;
  OptimizerPtr m_optimizer;
  MotionModelPtr m_motion_model;
  cv::Mat m_params;
  cv::Mat m_template_coords;
  std::vector<int> m_ctrl_points_indices;
  std::vector<LineIndices> m_ctrl_points_lines;
};

} } // namespace

#endif


text:
/*!
 * *****************************************************************************
 *   \file depthMapCreationHSBS_main.cpp
 *   \author moennen
 *   \brief
 *   \date 2018-02-19
 *   *****************************************************************************/

#include "utils/gl_utils.h"
#include "utils/gl_utils.inline.h"
#include "utils/imgFileLst.h"

// opencv
#include "utils/cv_utils.h"

// optical flow
#include <libopticalFlow/oclVarOpticalFlow.h>

// SDL
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>

// opengl
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;

#include <boost/filesystem.hpp>

#include <iostream>

using namespace std;
using namespace cv;
using namespace glm;
using namespace boost;

//------------------------------------------------------------------------------------------------------------
//
template <class Tex>
void draw( Tex& tex, uvec2 wSz, const bool error )
{
   static const float TexCoord[] = {0.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f};
   static const GLubyte indices[] = {0, 1, 2, 0, 2, 3};

   // clear the buffer according to the error state
   glClearColor( error ? 1.0 : 0.0, error ? 0.0 : 1.0, 0.0, 1.0 );
   glClear( GL_COLOR_BUFFER_BIT );

   // set the coords
   const vec2 sz = vec2( tex.sz ) * std::min(
                                        std::min( 1.0f, (float)wSz.x / tex.sz.x ),
                                        std::min( 1.0f, (float)wSz.y / tex.sz.y ) );
   const vec2 off = 0.5f * ( vec2( wSz.x, wSz.y ) - sz );

   // Bind Texture
   glBindTexture( GL_TEXTURE_2D, tex.id );

   const vec3 Vertices[] = {vec3( off.x, off.y, 0.f ),
                            vec3( off.x + sz.x, off.y, 0.f ),
                            vec3( off.x + sz.x, off.y + sz.y, 0.f ),
                            vec3( off.x, off.y + sz.y, 0.f )};

   glEnableClientState( GL_VERTEX_ARRAY );
   glVertexPointer( 3, GL_FLOAT, 0, value_ptr( Vertices[0] ) );
   glEnableClientState( GL_TEXTURE_COORD_ARRAY );
   glTexCoordPointer( 2, GL_FLOAT, 0, TexCoord );
   glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices );
   glDisableClientState( GL_TEXTURE_COORD_ARRAY );
   glDisableClientState( GL_VERTEX_ARRAY );

   glBindTexture( GL_TEXTURE_2D, 0 );
}

template <class Tex>
void draw( Tex& texR, Tex& texL, uvec2 wSz, const bool error )
{
   assert( texR.sz == texL.sz );

   static const float TexCoord[] = {0.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f};
   static const GLubyte indices[] = {0, 1, 2, 0, 2, 3};

   // clear the buffer according to the error state
   glClearColor( error ? 1.0 : 0.0, error ? 0.0 : 1.0, 0.0, 1.0 );
   glClear( GL_COLOR_BUFFER_BIT );

   // set the coords
   vec2 sz = vec2( texR.sz.x * 2.f, texR.sz.y );
   const float sf =
       std::min( std::min( 1.0f, (float)sz.x / wSz.x ), std::min( 1.0f, (float)sz.y / wSz.y ) );
   sz *= sf;
   vec2 off = 0.5f * ( vec2( wSz.x, wSz.y ) - sz );

   // Draw right
   glBindTexture( GL_TEXTURE_2D, texR.id );

   const vec3 VerticesR[] = {vec3( off.x, off.y, 0.f ),
                             vec3( off.x + sz.x, off.y, 0.f ),
                             vec3( off.x + sz.x, off.y + sz.y, 0.f ),
                             vec3( off.x, off.y + sz.y, 0.f )};

   glEnableClientState( GL_VERTEX_ARRAY );
   glVertexPointer( 3, GL_FLOAT, 0, value_ptr( VerticesR[0] ) );
   glEnableClientState( GL_TEXTURE_COORD_ARRAY );
   glTexCoordPointer( 2, GL_FLOAT, 0, TexCoord );
   glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices );
   glDisableClientState( GL_TEXTURE_COORD_ARRAY );
   glDisableClientState( GL_VERTEX_ARRAY );

   glBindTexture( GL_TEXTURE_2D, 0 );

   // Draw left
   glBindTexture( GL_TEXTURE_2D, texL.id );

   off.x += texR.sz.x * sf;

   const vec3 VerticesL[] = {vec3( off.x + sz.x, off.y, 0.f ),
                             vec3( off.x + 2.0 * sz.x, off.y, 0.f ),
                             vec3( off.x + 2.0 * sz.x, off.y + sz.y, 0.f ),
                             vec3( off.x + sz.x, off.y + sz.y, 0.f )};

   glEnableClientState( GL_VERTEX_ARRAY );
   glVertexPointer( 3, GL_FLOAT, 0, value_ptr( VerticesL[0] ) );
   glEnableClientState( GL_TEXTURE_COORD_ARRAY );
   glTexCoordPointer( 2, GL_FLOAT, 0, TexCoord );
   glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices );
   glDisableClientState( GL_TEXTURE_COORD_ARRAY );
   glDisableClientState( GL_VERTEX_ARRAY );

   glBindTexture( GL_TEXTURE_2D, 0 );
}

void drawQuad( size_t w, size_t h )
{
   const vec3 Vertices[] = {vec3( 0.f, 0.f, 0.f ),
                            vec3( (float)w, 0.f, 0.f ),
                            vec3( (float)w, (float)h, 0.f ),
                            vec3( 0.f, (float)h, 0.f )};
   static const GLfloat TexCoord[] = {0.f, 1.f, 1.f, 1.f, 1.f, 0.f, 0.f, 0.f};
   static const GLubyte indices[] = {0, 1, 2, 0, 2, 3};

   glEnableClientState( GL_VERTEX_ARRAY );
   glVertexPointer( 3, GL_FLOAT, 0, value_ptr( Vertices[0] ) );

   glEnableClientState( GL_TEXTURE_COORD_ARRAY );
   glTexCoordPointer( 2, GL_FLOAT, 0, TexCoord );

   glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices );

   glDisableClientState( GL_TEXTURE_COORD_ARRAY );
   glDisableClientState( GL_VERTEX_ARRAY );
}

template <class Tex>
void splitTexHSBS( Tex& currTex, Tex& currLeftTex, Tex& currRightTex )
{
   static gl_utils::RenderProgram splitShader;

   if ( splitShader._id == -1 )
   {
      splitShader.load( "shaders/splitHSBS.glsl" );
   }

   splitShader.activate();

   gl_utils::RenderTarget renderTarget( currLeftTex.sz );
   GLuint lrTex[2] = {currLeftTex.id, currRightTex.id};
   renderTarget.bind( 2, &lrTex[0] );

   glActiveTexture( GL_TEXTURE0 );
   glBindTexture( GL_TEXTURE_2D, currTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

   drawQuad( currLeftTex.sz.x, currLeftTex.sz.y );

   renderTarget.unbind();

   glBindTexture( GL_TEXTURE_2D, 0 );

   splitShader.deactivate();
}

void ofColorTransform( GLuint inTex, GLuint outTex, size_t w, size_t h )
{
   /*static*/ gl_utils::RenderProgram ofCtShader;
   if ( ofCtShader._id == -1 )
   {
      ofCtShader.load( "shaders/ofColourTransform.glsl" );
   }

   ofCtShader.activate();

   gl_utils::RenderTarget renderTarget( uvec2( w, h ) );
   renderTarget.bind( 1, &outTex );

   glActiveTexture( GL_TEXTURE0 );

   glBindTexture( GL_TEXTURE_2D, inTex );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

   drawQuad( w, h );

   glBindTexture( GL_TEXTURE_2D, 0 );

   renderTarget.unbind();

   ofCtShader.deactivate();
}

template <class Tex>
vec4 getTextureMean( Tex& tex )
{
   tex.generateMipmap();
   glm::vec4 toMt;
   gl_utils::readbackTexture( tex, (unsigned char*)value_ptr( toMt ), 100000 );
   return toMt;
}

template <class Tex>
void copyTexture( Tex& srcTex, Tex& dstTex )
{
   gl_utils::RenderTarget renderTarget( dstTex.sz );
   renderTarget.bind( 1, &dstTex.id );

   glActiveTexture( GL_TEXTURE0 );

   glBindTexture( GL_TEXTURE_2D, srcTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

   drawQuad( dstTex.sz.x, dstTex.sz.y );

   glBindTexture( GL_TEXTURE_2D, 0 );

   renderTarget.unbind();
}

template <class Tex>
void computeDisparity( Tex& rlOfTex, Tex& lrOfTex, Tex& dispTex )
{
   /*static*/ gl_utils::RenderProgram sh;

   static GLint scaleMtLoc = -1;
   static GLint rightOfTexLoc = -1;
   static GLint leftOfTexLoc = -1;

   if ( sh._id == -1 )
   {
      sh.load( "shaders/disp_fwdbwd.glsl" );
      scaleMtLoc = sh.getUniform( "mtScale" );
      rightOfTexLoc = sh.getUniform( "rightOfTex" );
      leftOfTexLoc = sh.getUniform( "leftOfTex" );
   }

   sh.activate();

   gl_utils::RenderTarget renderTarget( dispTex.sz );
   renderTarget.bind( 1, &dispTex.id );

   glUniform2f( scaleMtLoc, 1.0f / dispTex.sz.x, 1.0f / dispTex.sz.y );

   glActiveTexture( GL_TEXTURE0 );
   glBindTexture( GL_TEXTURE_2D, rlOfTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( rightOfTexLoc, 0 );

   glActiveTexture( GL_TEXTURE0 + 1 );
   glBindTexture( GL_TEXTURE_2D, lrOfTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( leftOfTexLoc, 1 );

   drawQuad( dispTex.sz.x, dispTex.sz.y );

   glBindTexture( GL_TEXTURE_2D, 0 );
   glActiveTexture( GL_TEXTURE0 );
   glBindTexture( GL_TEXTURE_2D, 0 );

   renderTarget.unbind();

   sh.deactivate();
}

template <class Tex>
float computeMotionDisparity(
    OclVarOpticalFlow& ofEngine,
    Tex& rightTex,
    Tex& leftTex,
    Tex& rlOfTex,
    Tex& lrOfTex,
    Tex& dispTex )
{
   // compute right -> left motion
   ofEngine.setOpt( OclVarOpticalFlow::OptsDoRightDisparity, true );
   ofEngine.setOpt( OclVarOpticalFlow::OptsDoLeftDisparity, false );

   ofEngine.compute(
       rightTex.id, leftTex.id, rightTex.sz.x, rightTex.sz.y, rlOfTex.id, -1, 1.0, 1.0 );

   // compute left -> right motion
   ofEngine.setOpt( OclVarOpticalFlow::OptsDoRightDisparity, false );
   ofEngine.setOpt( OclVarOpticalFlow::OptsDoLeftDisparity, true );

   ofEngine.compute(
       leftTex.id, rightTex.id, leftTex.sz.x, leftTex.sz.y, lrOfTex.id, -1, 1.0, 1.0 );

   // compute the disparity
   computeDisparity( rlOfTex, lrOfTex, dispTex );

   return getTextureMean( dispTex ).x;
}

template <class Tex>
void computeFrameDivergence( Tex& frameA, Tex& frameB, Tex& mtABTex, Tex& divTex )
{
   /*static*/ gl_utils::RenderProgram sh;

   static GLint invFrameSz = -1;
   static GLint frameATexLoc = -1;
   static GLint frameBTexLoc = -1;
   static GLint mtABTexLoc = -1;

   if ( sh._id == -1 )
   {
      sh.load( "shaders/frame_divergence.glsl" );
      invFrameSz = sh.getUniform( "invFrameSz" );
      frameATexLoc = sh.getUniform( "frameA" );
      frameBTexLoc = sh.getUniform( "frameB" );
      mtABTexLoc = sh.getUniform( "mtAB" );
   }

   sh.activate();

   gl_utils::RenderTarget renderTarget( divTex.sz );
   renderTarget.bind( 1, &divTex.id );

   glUniform2f( invFrameSz, 1.0f / divTex.sz.x, 1.0f / divTex.sz.y );

   glActiveTexture( GL_TEXTURE0 );
   glBindTexture( GL_TEXTURE_2D, frameA.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( frameATexLoc, 0 );

   glActiveTexture( GL_TEXTURE0 + 1 );
   glBindTexture( GL_TEXTURE_2D, frameB.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( frameBTexLoc, 1 );

   glActiveTexture( GL_TEXTURE0 + 2 );
   glBindTexture( GL_TEXTURE_2D, mtABTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( mtABTexLoc, 1 );

   drawQuad( divTex.sz.x, divTex.sz.y );

   glBindTexture( GL_TEXTURE_2D, 0 );
   glActiveTexture( GL_TEXTURE0 + 1 );
   glBindTexture( GL_TEXTURE_2D, 0 );
   glActiveTexture( GL_TEXTURE0 );
   glBindTexture( GL_TEXTURE_2D, 0 );

   renderTarget.unbind();

   sh.deactivate();
}

template <class Tex>
float computeFrameMotionDivergence(
    OclVarOpticalFlow& ofEngine,
    Tex& fromFrame,
    Tex& toFrame,
    Tex& ofTex,
    Tex& divTex )
{
   ofEngine.compute(
       fromFrame.id, toFrame.id, fromFrame.sz.x, fromFrame.sz.y, ofTex.id, -1, 1.0, 1.0 );

   computeFrameDivergence( fromFrame, toFrame, ofTex, divTex );

   return getTextureMean( divTex ).w;
}

template <class Tex>
float updateDisparity(
    Tex& currDispTex,
    Tex& prevDispTex,
    Tex& nextDispTex,
    Tex& prevMtTex,
    Tex& nextMtTex,
    Tex& dispTex )
{
   /*static*/ gl_utils::RenderProgram sh;

   static GLint invFrameSz = -1;
   static GLint currDispTexLoc = -1;
   static GLint prevDispTexLoc = -1;
   static GLint nextDispTexLoc = -1;
   static GLint prevMtTexLoc = -1;
   static GLint nextMtTexLoc = -1;

   if ( sh._id == -1 )
   {
      sh.load( "shaders/update_disparity.glsl" );
      invFrameSz = sh.getUniform( "invFrameSz" );
      currDispTexLoc = sh.getUniform( "currDisp" );
      prevDispTexLoc = sh.getUniform( "prevDisp" );
      nextDispTexLoc = sh.getUniform( "nextDisp" );
      prevMtTexLoc = sh.getUniform( "prevMt" );
      nextMtTexLoc = sh.getUniform( "nextMt" );
   }

   sh.activate();

   gl_utils::RenderTarget renderTarget( dispTex.sz );
   renderTarget.bind( 1, &dispTex.id );

   glUniform2f( invFrameSz, 1.0f / currDispTex.sz.x, 1.0f / currDispTex.sz.y );

   glActiveTexture( GL_TEXTURE0 );
   glBindTexture( GL_TEXTURE_2D, currDispTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( currDispTexLoc, 0 );

   glActiveTexture( GL_TEXTURE0 + 1 );
   glBindTexture( GL_TEXTURE_2D, prevDispTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( prevDispTexLoc, 1 );

   glActiveTexture( GL_TEXTURE0 + 2 );
   glBindTexture( GL_TEXTURE_2D, nextDispTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( nextDispTexLoc, 2 );

   glActiveTexture( GL_TEXTURE0 + 3 );
   glBindTexture( GL_TEXTURE_2D, prevMtTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( prevMtTexLoc, 3 );

   glActiveTexture( GL_TEXTURE0 + 4 );
   glBindTexture( GL_TEXTURE_2D, nextMtTex.id );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glUniform1i( nextMtTexLoc, 4 );

   drawQuad( dispTex.sz.x, dispTex.sz.y );

   glBindTexture( GL_TEXTURE_2D, 0 );
   glActiveTexture( GL_TEXTURE0 + 3 );
   glBindTexture( GL_TEXTURE_2D, 0 );
   glActiveTexture( GL_TEXTURE0 + 2 );
   glBindTexture( GL_TEXTURE_2D, 0 );
   glActiveTexture( GL_TEXTURE0 + 1 );
   glBindTexture( GL_TEXTURE_2D, 0 );
   glActiveTexture( GL_TEXTURE0 );
   glBindTexture( GL_TEXTURE_2D, 0 );

   renderTarget.unbind();

   sh.deactivate();

   return getTextureMean( dispTex ).w;
}

enum class Errors
{
   Success,
   BadDisparity,
   FrameDivergence,
   DisparityDivergence,
   UploadTexture
};

void processError( Errors& err, const float delay )
{
   if ( err == Errors::Success ) return;
   std::string errorMsg;
   switch ( err )
   {
      case Errors::BadDisparity:
         errorMsg = "Bad Disparity";
         break;
      case Errors::DisparityDivergence:
         errorMsg = "Disparity Divergence";
         break;
      case Errors::FrameDivergence:
         errorMsg = "Frame Divergence";
         break;
      case Errors::UploadTexture:
         errorMsg = "Upload Texture";
         break;
      default:
         errorMsg = "Error";
   }

   cerr << "Error : " << errorMsg << flush << endl;
   err = Errors::Success;
   SDL_Delay( delay );
}

const string keys =
    "{help h usage ? |         | print this message   }"
    "{@imgFileLst      |         | images list   }"
    "{@imgRootDir    |         | images root dir   }"
    "{@imgOutDir    |         | images output dir   }";

int main( int argc, char* argv[] )
{
   CommandLineParser parser( argc, argv, keys );
   if ( parser.has( "help" ) )
   {
      parser.printMessage();
      return ( 0 );
   }

   // Parameters
   uvec2 windowSz( 1920, 1200 );

   const bool toLinear = false;
   const float delayOnError = 100;

   const float gammaForDisparity = 50.0;
   const float lambdaForDisparity = 0.05;

   const float gammaForMotion = 50.0;
   const float lambdaForMotion = 0.197;

   const float minDispAmount = 0.0;
   const float maxFrameDivAmount = 1.0;
   const float maxDispDivAmount = 1.0;

   const filesystem::path outRootPath( parser.get<string>( "@imgOutDir" ) );

   // Create the list of image triplets

   ImgTripletsFileLst imgLst(
       parser.get<string>( "@imgFileLst" ).c_str(), parser.get<string>( "@imgRootDir" ).c_str() );
   if ( imgLst.size() == 0 )
   {
      cerr << "Invalid dataset : " << parser.get<string>( "@imgFileLst" ) << endl;
      return -1;
   }

   // SDL init

   SDL_Init( SDL_INIT_EVERYTHING );
   SDL_Window* window = SDL_CreateWindow(
       argv[0],
       SDL_WINDOWPOS_CENTERED,
       SDL_WINDOWPOS_CENTERED,
       windowSz.x,
       windowSz.y,
       SDL_WINDOW_OPENGL );
   SDL_GLContext glCtx = SDL_GL_CreateContext( window );

   // Controls

   enum
   {
      DisplayMode_Right,
      DisplayMode_Left,
      DisplayMode_RightLeft_Right,
      DisplayMode_RightLeft_Left,
      DisplayMode_Disparity,
      DisplayMode_Motion,
      DisplayMode_Num
   };
   int displayMode = DisplayMode_Disparity;
   bool rightDisparity = true;
   bool running = true;
   Uint32 start;
   SDL_Event event;

   // Init

   GLenum err = glewInit();
   if ( GLEW_OK != err )
   {
      fprintf( stderr, "Error: %s\n", glewGetErrorString( err ) );
      return -1;
   }

   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
   glOrtho( 0.0, windowSz.x, windowSz.y, 1.0, -1.0, 1.0 );
   glEnable( GL_TEXTURE_2D );

   // Create the data
   using Img = Mat;
   using Tex = gl_utils::Texture<gl_utils::RGBA_32FP>;
   enum
   {
      WkFullTex = 0,

      FirstHalfTex = 1,
      PrevTex = 1,
      NextTex = 4,
      CurrTex = 7,

      OfRLTex = 10,
      OfLRTex = 11,

      WkHalfTex = 12,

      LastHalfTex = 12,

      DispTex = 0,
      RightTex = 1,
      LeftTex = 2,

      NumTex = 13

   };
   Tex texs[NumTex];

   // Create the optical flow estimator
   OclVarOpticalFlow::params_t ofParams = OclVarOpticalFlow::getDefaultParams();
   ofParams.nonLinearIter = 9;
   ofParams.robustIter = 4;
   ofParams.solverIter = 7;

   OclVarOpticalFlow ofEstimator( windowSz.x / 2, windowSz.y, false, ofParams );

   Errors lastError = Errors::Success;

   // Loop through the data
   for ( size_t i = 0; i < imgLst.size(); ++i )
   {
      SDL_GL_SwapWindow( window );
      processError( lastError, delayOnError );

      const auto& data = imgLst[i];

      Img img[3] = {cv_utils::imread32FC4( data._pathA, toLinear, true ),
                    cv_utils::imread32FC4( data._pathC, toLinear, true ),
                    cv_utils::imread32FC4( data._pathB, toLinear, true )};

      const uvec2 imgSz( img[0].cols, img[0].rows );
      const uvec2 hImgSz( imgSz.x / 2, imgSz.y );

      ofEstimator.setImgSize( hImgSz.x, hImgSz.y );

      // -------------- create resources

      texs[WkFullTex].create( imgSz );
      for ( size_t j = FirstHalfTex; j <= LastHalfTex; ++j ) texs[j].create( hImgSz );

      // -------------- compute disparities

      ofEstimator.setLambda( lambdaForDisparity );
      ofEstimator.setGamma( gammaForDisparity );

      for ( size_t j = PrevTex; j <= CurrTex; ++j )
      {
         gl_utils::uploadToTexture( texs[WkFullTex], img[j-1].ptr() );
         splitTexHSBS( texs[WkFullTex], texs[j + RightTex], texs[j + LeftTex] );

         Img iLeft( imgSz.y, imgSz.x/2, CV_32FC4 );
         gl_utils::readbackTexture( texs[j + LeftTex], iLeft.data );
         cvtColor( iLeft, iLeft, cv::COLOR_RGBA2BGR );
         imshow("elft",iLeft);
         waitKey();

         //draw( texs[WkFullTex], windowSz, false );
         //draw( texs[j + LeftTex], windowSz, false );
         lastError = Errors::BadDisparity;
         break;

         float valid = computeMotionDisparity(
             ofEstimator,
             texs[j + RightTex],
             texs[j + LeftTex],
             texs[OfRLTex],
             texs[OfLRTex],
             texs[j + DispTex] );

         draw( texs[j + RightTex], texs[j + LeftTex], windowSz, false );
         lastError = Errors::BadDisparity;
         break;

         if ( valid < minDispAmount )
         {
            lastError = Errors::BadDisparity;
            draw( texs[WkFullTex], windowSz, true );
            break;
         }
      }
      if ( lastError != Errors::Success ) continue;

      // -------------- estimate flows

      ofEstimator.setOpt( OclVarOpticalFlow::OptsDoRightDisparity, false );
      ofEstimator.setOpt( OclVarOpticalFlow::OptsDoLeftDisparity, false );
      ofEstimator.setLambda( lambdaForMotion );
      ofEstimator.setGamma( gammaForMotion );

      for ( size_t j = PrevTex; j <= NextTex; j += 3 )
      {
         const bool bwd( j == PrevTex );
         const float div = computeFrameMotionDivergence(
             ofEstimator,
             texs[CurrTex + RightTex],
             texs[j + RightTex],
             texs[WkHalfTex],
             texs[bwd ? OfLRTex : OfRLTex] );
         if ( div > maxFrameDivAmount )
         {
            lastError = Errors::FrameDivergence;
            draw( texs[CurrTex + RightTex], texs[j + RightTex], windowSz, true );
            break;
         }
      }
      if ( lastError != Errors::Success ) continue;

      // ------------ compute filtered disparity

      {
         float valid = updateDisparity(
             texs[CurrTex + DispTex],
             texs[PrevTex + DispTex],
             texs[NextTex + DispTex],
             texs[OfRLTex],
             texs[OfLRTex],
             texs[WkHalfTex] );
         if ( valid > maxDispDivAmount )
         {
            lastError = Errors::DisparityDivergence;
            draw( texs[PrevTex + DispTex], texs[NextTex + DispTex], windowSz, true );
         }
      }
      if ( lastError != Errors::Success ) continue;

      // ------------ output
      const string outBasename = filesystem::path( data._pathB ).stem().string();
      Mat imgOut( imgSz.y, imgSz.x, CV_32FC4 );
      for ( size_t j = DispTex; j <= RightTex; ++j )
      {
         copyTexture( texs[CurrTex + j], texs[WkFullTex] );
         if ( !gl_utils::readbackTexture( texs[WkFullTex], imgOut.data ) )
         {
            lastError = Errors::UploadTexture;
            draw( texs[CurrTex + j], windowSz, true );
            break;
         }
         cvtColor( imgOut, imgOut, cv::COLOR_RGBA2BGR );
         const filesystem::path f(
             outRootPath /
             filesystem::path( outBasename + string( j == RightTex ? "_i" : "_d" ) + ".exr" ) );
         imwrite( f.string().c_str(), imgOut );
      }
      if ( lastError != Errors::Success ) continue;

      // --------------- draw

      draw( texs[CurrTex + RightTex], texs[CurrTex + DispTex], windowSz, false );
   }

   SDL_Quit();

   return ( 0 );
}

ext: cpp

max_stars_repo_name: moennen/sceneIllEst

max_issues_repo_name: moennen/sceneIllEst

max_forks_repo_name: moennen/sceneIllEst


text:
// Copyright (C) 2015, Pawel Tomulik <ptomulik@meil.pw.edu.pl>
//
// 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)
#define BOOST_TEST_MODULE test_txpl_parser_parse_impl_unary_expr

#include <txpl/test_config.hpp>
#include <boost/test/unit_test.hpp>

#ifndef TXPL_TEST_SKIP_PARSER_PARSE_IMPL_UNARY_EXPR

#include <txpl/parser/parse_impl_unary_expr.hpp>
#include <txpl/vm/basic_types.hpp>
#include <txpl/lexer/token.hpp>
#include <txpl/ast/squash_heads.hpp>
#include <boost/variant/get.hpp>

BOOST_AUTO_TEST_CASE(test__parse_impl_unary_expr)
{
  using namespace txpl::parser;
  using namespace txpl;
  using boost::get;

  typedef lexer::token<> const* token_iterator;

  ast::unary_expr<token_iterator> u;
  {
    lexer::token<> tok;
    lexer::token<> const *first = &tok, *last = first;
    BOOST_CHECK(!parse(first, last, u));
    BOOST_CHECK(first == last);
  }
  {
    const char *beg[] = { "z" };
    const char *end[] = { beg[0]+1 };
    lexer::token<> tok[] = {
      lexer::token<>(lexer::token_t::word_, beg[0], end[0])
    };
    lexer::token<> const* first = tok, *last = first + 1;
    BOOST_CHECK(!parse(first, last, u));
    BOOST_CHECK((first+1) == last);
  }
  {
    typedef vm::basic_types<>::real_type real_type;
    const char *beg[] = { "-",      ".123" };
    const char *end[] = { beg[0]+1, beg[1]+4 };
    lexer::token<> tok[] = {
      lexer::token<>(lexer::token_t::minus_, beg[0], end[0]),
      lexer::token<>(lexer::token_t::real_, beg[1], end[1]),
    };
    lexer::token<> const* first = tok, *last = first + 2;

    ast::literal<token_iterator> l;
    real_type x = real_type{.456};
    BOOST_CHECK(parse(first, last, u));
    BOOST_CHECK(u.operator_ == '-');
    BOOST_CHECK_NO_THROW(l = get<ast::literal<token_iterator> >(ast::squash_heads(u.expr)));
    BOOST_CHECK_NO_THROW(x = get<real_type>(l.value));
    BOOST_CHECK_EQUAL(x, real_type{.123});
    BOOST_CHECK(first == last);
  }
  {
    typedef vm::basic_types<>::real_type real_type;
    const char *beg[] = { "+",      ".123" };
    const char *end[] = { beg[0]+1, beg[1]+4 };
    lexer::token<> tok[] = {
      lexer::token<>(lexer::token_t::plus_, beg[0], end[0]),
      lexer::token<>(lexer::token_t::real_, beg[1], end[1]),
    };
    lexer::token<> const* first = tok, *last = first + 2;

    ast::literal<token_iterator> l;
    real_type x = real_type{.456};
    BOOST_CHECK(parse(first, last, u));
    BOOST_CHECK(u.operator_ == '+');
    BOOST_CHECK_NO_THROW(l = get<ast::literal<token_iterator> >(ast::squash_heads(u.expr)));
    BOOST_CHECK_NO_THROW(x = get<real_type>(l.value));
    BOOST_CHECK_EQUAL(x, real_type{.123});
    BOOST_CHECK(first == last);
  }
  {
    typedef vm::basic_types<>::char_type char_type;
    const char *beg[] = { "!",      "'a'" };
    const char *end[] = { beg[0]+1, beg[1] + 3 };
    lexer::token<> tok[] = {
      lexer::token<>(lexer::token_t::not_, beg[0], end[0]),
      lexer::token<>(lexer::token_t::qchar_, beg[1], end[1]),
    };
    lexer::token<> const* first = tok, *last = first + 2;

    ast::literal<token_iterator> l;
    char_type x = char_type{'z'};
    BOOST_CHECK(parse(first, last, u));
    BOOST_CHECK(u.operator_ == '!');
    BOOST_CHECK_NO_THROW(l = get<ast::literal<token_iterator> >(ast::squash_heads(u.expr)));
    BOOST_CHECK_NO_THROW(x = get<char_type>(l.value));
    BOOST_CHECK_EQUAL(x, 'a');
    BOOST_CHECK(first == last);
  }
  {
    typedef vm::basic_types<>::int_type int_type;
    const char *beg[] = { "~",      "123" };
    const char *end[] = { beg[0]+1, beg[1] + 3 };
    lexer::token<> tok[] = {
      lexer::token<>(lexer::token_t::neg_, beg[0], end[0]),
      lexer::token<>(lexer::token_t::int_, beg[1], end[1]),
    };
    lexer::token<> const* first = tok, *last = first + 2;

    ast::literal<token_iterator> l;
    int_type x = int_type{456};
    BOOST_CHECK(parse(first, last, u));
    BOOST_CHECK(u.operator_ == '~');
    BOOST_CHECK_NO_THROW(l = get<ast::literal<token_iterator> >(ast::squash_heads(u.expr)));
    BOOST_CHECK_NO_THROW(x = get<int_type>(l.value));
    BOOST_CHECK_EQUAL(x, 123);
    BOOST_CHECK(first == last);
  }
}

#else
BOOST_AUTO_TEST_CASE(dummy)
{
  BOOST_CHECK(true);
}
#endif

max_stars_repo_name: ptomulik/txpl

max_issues_repo_name: ptomulik/txpl

max_forks_repo_name: ptomulik/txpl


text:
/*
 * Copyright (c) 2019–2021 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#include <boost/format.hpp>
#include <cstdlib>
#include <iostream>
#include <libbio/assert.hh>
#include <libbio/dispatch.hh>
#include <unistd.h>
#include <vcf2multialign/utility/dispatch_exit_guard.hh>
#include <vcf2multialign/utility/log_assertion_failure.hh>
#include <vcf2multialign/variant_graph/variant_graph.hh>
#include "cmdline.h"
#include "founder_sequence_greedy_generator.hh"
#include "sequence_generator_base.hh"

namespace lb	= libbio;
namespace v2m	= vcf2multialign;
namespace vgs	= vcf2multialign::variant_graphs;

namespace {

	class founder_alt_edge_handler final : public v2m::alt_edge_handler_base
	{
	public:
		typedef v2m::alt_edge_handler_base::stream_position_list	stream_position_list;

		using v2m::alt_edge_handler_base::alt_edge_handler_base;

		void handle_node_with_alt_edges(stream_position_list &files_waiting, std::size_t const subgraph_variant_idx) const override
		{
			// Associate the path numbers with stream numbers directly (i.e. no weight-based matching).
			auto const subgraph_paths(m_edges_by_path_and_variant->number_of_columns());
			for (auto &sp : files_waiting)
			{
				std::size_t const edge_number(sp.stream_number < subgraph_paths ? (*m_edges_by_path_and_variant)(subgraph_variant_idx, sp.stream_number) : 0);
				this->handle_edge(sp, edge_number);
			}
		}
	};

	class haplotype_alt_edge_handler final : public v2m::alt_edge_handler_base
	{
	public:
		typedef v2m::alt_edge_handler_base::stream_position_list	stream_position_list;

		using v2m::alt_edge_handler_base::alt_edge_handler_base;

		void handle_node_with_alt_edges(stream_position_list &files_waiting, std::size_t const subgraph_variant_idx) const override
		{
			this->handle_edge(files_waiting.back(), 0); // REF
			for (auto &sp : files_waiting | ranges::view::drop_last(1))
			{
				auto const path_number((*m_sample_paths)[sp.stream_number]);
				auto const edge_number((*m_edges_by_path_and_variant)(subgraph_variant_idx, path_number));
				this->handle_edge(sp, edge_number);
			}
		}
	};

	class founder_sequence_generator final : public v2m::direct_matching_sequence_generator
	{
	public:
		typedef v2m::direct_matching_sequence_generator::output_stream_vector	output_stream_vector;

		using v2m::direct_matching_sequence_generator::direct_matching_sequence_generator;

		std::unique_ptr <v2m::alt_edge_handler_base> make_alt_edge_handler(
			std::string_view const &reference_sv,
			vgs::variant_graph const &graph,
			output_stream_vector &output_files
		) const override
		{
			return std::unique_ptr <v2m::alt_edge_handler_base>(new founder_alt_edge_handler(reference_sv, graph, output_files));
		}

		std::size_t const get_stream_count() const override
		{
			auto const max_paths(m_graph.max_paths_in_subgraph());
			return (m_output_reference ? 1 : 0) + max_paths;
		}

	protected:
		void open_output_file(std::size_t const idx, output_stream_type &of, lb::writing_open_mode const mode) const override
		{
			v2m::open_founder_output_file(idx, of, mode);
		}
	};

	class sample_sequence_generator final : public v2m::direct_matching_sequence_generator
	{
	protected:
		// FIXME: We currently assume that all samples (and records) have the same ploidy.
		std::size_t m_sample_count{};	// Not taking REF into account.
		std::size_t m_ploidy{};

	public:
		typedef v2m::direct_matching_sequence_generator::output_stream_vector	output_stream_vector;

		using v2m::direct_matching_sequence_generator::direct_matching_sequence_generator;

		void prepare_variant_graph() override
		{
			auto const &sample_paths_by_subgraph(m_graph.sample_paths());
			m_sample_count = sample_paths_by_subgraph.empty() ? 0 : (sample_paths_by_subgraph.front().size());
			m_ploidy = m_sample_count / m_graph.sample_names().size();
		}

		std::unique_ptr <v2m::alt_edge_handler_base> make_alt_edge_handler(
			std::string_view const &reference_sv,
			vgs::variant_graph const &graph,
			output_stream_vector &output_files
		) const override
		{
			return std::unique_ptr <v2m::alt_edge_handler_base>(new haplotype_alt_edge_handler(reference_sv, graph, output_files));
		}

		std::size_t const get_stream_count() const override
		{
			return (m_output_reference ? 1 : 0) + m_sample_count;
		}

	protected:
		void open_output_file(std::size_t const idx, output_stream_type &of, lb::writing_open_mode const mode) const override
		{
			auto const name_idx(idx / m_ploidy);
			auto const chr_idx(idx % m_ploidy + 1);
			auto const &name(m_graph.sample_names()[name_idx]);
			v2m::open_output_file(boost::str(boost::format("%s-%d") % name % chr_idx), of, mode);
		}
	};

	template <typename t_generator>
	std::unique_ptr <v2m::dispatch_exit_guard_helper <t_generator>> instantiate_generator(gengetopt_args_info const &args_info)
	{
		return std::make_unique <v2m::dispatch_exit_guard_helper <t_generator>>(
			args_info.chunk_size_arg,
			(args_info.omit_reference_output_flag ? false : true),
			args_info.overwrite_flag
		);
	}

	void prepare(v2m::sequence_generator_base &gen, gengetopt_args_info const &args_info)
	{
		gen.read_reference(
			args_info.reference_arg,
			(args_info.reference_sequence_given ? args_info.reference_sequence_arg : nullptr)
		);

		lb::log_time(std::cerr);
		std::cerr << "Reading the variant graph…\n";
		gen.read_variant_graph(args_info.variants_arg);
		gen.prepare_variant_graph();
	}

	template <typename t_generator>
	void output_sequences(std::unique_ptr <v2m::dispatch_exit_guard_helper <t_generator>> &&gen_ptr)
	{
		// Run in background in order to be able to update a progress bar.
		lb::log_time(std::cerr);
		std::cerr << "Outputting the sequences.\n";
		lb::dispatch_async_fn(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
			[
				gen_ptr = std::move(gen_ptr)
			](){
				gen_ptr->value.run(true);
			}
		);
	}
}

void process(gengetopt_args_info &args_info)
{
	try
	{
		if (args_info.output_founders_given)
		{
			auto gen_ptr(instantiate_generator <founder_sequence_generator>(args_info));
			prepare(gen_ptr->value, args_info);
			output_sequences(std::move(gen_ptr));
		}
		else if (args_info.output_founders_greedy_given)
		{
			typedef v2m::dispatch_exit_guard_helper <v2m::founder_sequence_greedy_generator> wrapped_generator_type;
			auto gen_ptr(std::make_unique <wrapped_generator_type>(
				args_info.founder_count_arg,
				args_info.tail_length_arg,
				(args_info.omit_reference_output_flag ? false : true),
				args_info.fill_unassigned_with_ref_flag,
				args_info.remove_mid_from_duplicates_flag,
				args_info.overwrite_flag
			));

			auto &generator(gen_ptr->value);
			prepare(generator, args_info);

			{
				auto const max_paths_in_subgraph(generator.variant_graph().max_paths_in_subgraph());
				if (args_info.founder_count_arg < max_paths_in_subgraph)
				{
					std::cerr
						<< "NOTE: There are at most "
						<< max_paths_in_subgraph
						<< " paths in a subgraph, which is more than the specified number of founder sequences to be generated, "
						<< args_info.founder_count_arg
						<< ".\n";
				}
			}

			output_sequences(std::move(gen_ptr));
		}
		else if (args_info.output_samples_given)
		{
			auto gen_ptr(instantiate_generator <sample_sequence_generator>(args_info));
			prepare(gen_ptr->value, args_info);
			output_sequences(std::move(gen_ptr));
		}
	}
	catch (lb::assertion_failure_exception const &exc)
	{
		v2m::log_assertion_failure_exception(exc);
		throw exc;
	}
}

int main(int argc, char **argv)
{
#ifndef NDEBUG
	std::cerr << "Assertions have been enabled." << std::endl;
#endif

	gengetopt_args_info args_info;
	if (0 != cmdline_parser(argc, argv, &args_info))
		std::exit(EXIT_FAILURE);

	std::ios_base::sync_with_stdio(false);	// Don't use C style IO after calling cmdline_parser.
	std::cin.tie(nullptr);					// We don't require any input from the user.

	if (args_info.chunk_size_arg <= 0)
	{
		std::cerr << "Chunk size must be positive." << std::endl;
		std::exit(EXIT_FAILURE);
	}

	if (args_info.founder_count_arg < 1)
	{
		std::cerr << "Founder count must be positive." << std::endl;
		std::exit(EXIT_FAILURE);
	}

	if (args_info.tail_length_arg < 0)
	{
		std::cerr << "Tail length must be non-negative." << std::endl;
		std::exit(EXIT_FAILURE);
	}

	if (args_info.founder_count_given && args_info.chunk_size_given)
	{
		std::cerr << "WARNING: Ignoring chunk size when using greedy matching.\n";
	}

	{
		auto const mode_count(args_info.output_samples_given + args_info.output_founders_given + args_info.output_founders_greedy_given);
		if (0 == mode_count)
		{
			std::cerr << "No mode given." << std::endl;
			std::exit(EXIT_FAILURE);
		}
	}

	process(args_info);

	// Needs to be outside the try block in process().
	// Also it seemed that the compiler attempted to optimize the block somehow when
	// it was located in the same function as the call to dispatch_main().
	dispatch_main();

	// Not reached.
	return EXIT_SUCCESS;
}

ext: cc


text:
// C++ includes
#include <iostream>
using namespace std;

// Eigen includes
#include <Eigen/Core>
using namespace Eigen;

// autodiff include
#include <autodiff/forward.hpp>
#include <autodiff/forward/eigen.hpp>
using namespace autodiff;

// The scalar function for which the gradient is needed
dual f(const VectorXdual& x, dual p)
{
    return x.cwiseProduct(x).sum() * exp(p); // sum([x(i) * x(i) for i = 1:5]) * exp(p)
}

int main()
{
    VectorXdual x(5);    // the input vector x with 5 variables
    x << 1, 2, 3, 4, 5;  // x = [1, 2, 3, 4, 5]

    dual p = 3;    // the input parameter vector p with 3 variables

    dual u;  // the output scalar u = f(x, p) evaluated together with gradient below

    VectorXd gpx = gradient(f, wrtpack(p, x), at(x, p), u);  // evaluate the function value u and its gradient vector gp = [du/dp, du/dx]

    cout << "u = " << u << endl;    // print the evaluated output u
    cout << "gpx = \n" << gpx << endl;  // print the evaluated gradient vector gp = [du/dp, du/dx]
}

max_stars_repo_name: ludkinm/autodiff

max_issues_repo_name: ludkinm/autodiff

max_forks_repo_name: ludkinm/autodiff


text:
/* Copyright (c) 2019 vesoft inc. All rights reserved.
 *
 * This source code is licensed under Apache 2.0 License,
 * attached with Common Clause Condition 1.0, found in the LICENSES directory.
 */

#include "common/http/HttpClient.h"
#include "common/webservice/Common.h"
#include "common/time/WallClock.h"
#include <boost/stacktrace.hpp>
#include <gtest/gtest.h>
#include <folly/synchronization/Baton.h>
#include "kvstore/Common.h"
#include "kvstore/KVIterator.h"
#include "meta/processors/Common.h"
#include "meta/processors/admin/AdminClient.h"
#include "meta/processors/jobMan/JobManager.h"
#include "meta/processors/jobMan/JobUtils.h"
#include "meta/processors/jobMan/TaskDescription.h"
#include "meta/processors/jobMan/JobStatus.h"
#include "meta/processors/jobMan/MetaJobExecutor.h"
#include "meta/MetaServiceUtils.h"

DEFINE_int32(dispatch_thread_num, 3, "Number of job dispatch http thread");
DEFINE_int32(job_check_intervals, 5000, "job intervals in us");
DEFINE_double(job_expired_secs, 7*24*60*60, "job expired intervals in sec");

using nebula::kvstore::ResultCode;
using nebula::kvstore::KVIterator;

namespace nebula {
namespace meta {

JobManager* JobManager::getInstance() {
    static JobManager inst;
    return &inst;
}

bool JobManager::init(nebula::kvstore::KVStore* store) {
    if (store == nullptr) {
        return false;
    }
    kvStore_ = store;
    pool_ = std::make_unique<nebula::thread::GenericThreadPool>();
    pool_->start(FLAGS_dispatch_thread_num);

    queue_ = std::make_unique<folly::UMPSCQueue<int32_t, true>>();
    bgThread_ = std::make_unique<thread::GenericWorker>();
    CHECK(bgThread_->start());
    bgThread_->addTask(&JobManager::scheduleThread, this);
    return true;
}

JobManager::~JobManager() {
    shutDown();
}

void JobManager::shutDown() {
    LOG(INFO) << "JobManager::shutDown() begin";
    shutDown_ = true;
    pool_->stop();
    bgThread_->stop();
    bgThread_->wait();
    LOG(INFO) << "JobManager::shutDown() end";
}

void JobManager::scheduleThread() {
    LOG(INFO) << "JobManager::runJobBackground() enter";
    while (!shutDown_) {
        int32_t iJob = 0;
        while (!queue_->try_dequeue(iJob)) {
            if (shutDown_) {
                LOG(INFO) << "[JobManager] detect shutdown called, exit";
                break;
            }
            usleep(FLAGS_job_check_intervals);
        }

        auto jobDesc = JobDescription::loadJobDescription(iJob, kvStore_);
        if (jobDesc == folly::none) {
            LOG(ERROR) << "[JobManager] load a invalid job from queue " << iJob;
            continue;   // leader change or archive happend
        }
        if (!jobDesc->setStatus(cpp2::JobStatus::RUNNING)) {
            LOG(INFO) << "[JobManager] skip job " << iJob;
            continue;
        }
        save(jobDesc->jobKey(), jobDesc->jobVal());

        if (runJobInternal(*jobDesc)) {
            jobDesc->setStatus(cpp2::JobStatus::FINISHED);
        } else {
            jobDesc->setStatus(cpp2::JobStatus::FAILED);
        }
        save(jobDesc->jobKey(), jobDesc->jobVal());
    }
    LOG(INFO) << "[JobManager] exit";
}

// @return: true if succeed, false if any task failed
bool JobManager::runJobInternal(const JobDescription& jobDesc) {
    auto jobExecutor = MetaJobExecutorFactory::createMetaJobExecutor(jobDesc,
                                                                     kvStore_,
                                                                     adminClient_);
    if (jobExecutor == nullptr) {
        LOG(ERROR) << "unreconized job cmd " << static_cast<int>(jobDesc.getCmd());
        return false;
    }
    if (jobDesc.getStatus() == cpp2::JobStatus::STOPPED) {
        jobExecutor->stop();
        return true;
    }
    if (jobDesc.getParas().empty()) {
        return false;
    }

    std::string spaceName = jobDesc.getParas().back();
    int spaceId = getSpaceId(spaceName);
    if (spaceId < 0) {
        return false;
    }

    auto results = jobExecutor->execute();
    if (!nebula::ok(results)) {
        return false;
    }

    size_t taskId = 0;
    bool jobSuccess = true;
    for (auto& hostAndStatus : nebula::value(results)) {
        auto& host = hostAndStatus.first;
        TaskDescription task(jobDesc.getJobId(), taskId, host.host, host.port);
        bool taskSuccess = hostAndStatus.second.ok();
        auto taskStatus = taskSuccess ? cpp2::JobStatus::FINISHED : cpp2::JobStatus::FAILED;
        if (!taskSuccess) {
            jobSuccess = false;
        }
        task.setStatus(taskStatus);
        save(task.taskKey(), task.taskVal());
        ++taskId;
    }
    return jobSuccess;
}

ResultCode JobManager::addJob(const JobDescription& jobDesc, AdminClient* client) {
    auto rc = save(jobDesc.jobKey(), jobDesc.jobVal());
    if (rc == nebula::kvstore::SUCCEEDED) {
        queue_->enqueue(jobDesc.getJobId());
    }
    adminClient_ = client;
    return rc;
}

ErrorOr<ResultCode, std::vector<cpp2::JobDesc>>
JobManager::showJobs() {
    std::unique_ptr<kvstore::KVIterator> iter;
    ResultCode rc = kvStore_->prefix(kDefaultSpaceId, kDefaultPartId,
                                     JobUtil::jobPrefix(), &iter);
    if (rc != nebula::kvstore::SUCCEEDED) {
        return rc;
    }

    int32_t lastExpiredJobId = INT_MIN;
    std::vector<std::string> expiredJobKeys;
    std::vector<cpp2::JobDesc> ret;
    for (; iter->valid(); iter->next()) {
        if (JobDescription::isJobKey(iter->key())) {
            auto optJob = JobDescription::makeJobDescription(iter->key(), iter->val());
            if (optJob == folly::none) {
                expiredJobKeys.emplace_back(iter->key());
                continue;
            }
            // skip expired job, default 1 week
            auto jobDesc = optJob->toJobDesc();
            if (isExpiredJob(jobDesc)) {
                lastExpiredJobId = jobDesc.get_id();
                LOG(INFO) << "remove expired job " << lastExpiredJobId;
                expiredJobKeys.emplace_back(iter->key());
                continue;
            }
            ret.emplace_back(jobDesc);
        } else {  // iter-key() is a TaskKey
            TaskDescription task(iter->key(), iter->val());
            if (task.getJobId() == lastExpiredJobId) {
                expiredJobKeys.emplace_back(iter->key());
            }
        }
    }
    removeExpiredJobs(expiredJobKeys);
    std::sort(ret.begin(), ret.end(), [](const auto& a, const auto& b) {
        return a.get_id() > b.get_id();
    });
    return ret;
}

bool JobManager::isExpiredJob(const cpp2::JobDesc& jobDesc) {
    auto jobStart = jobDesc.get_start_time();
    auto duration = std::difftime(nebula::time::WallClock::fastNowInSec(), jobStart);
    return duration > FLAGS_job_expired_secs;
}

void JobManager::removeExpiredJobs(const std::vector<std::string>& expiredJobsAndTasks) {
    folly::Baton<true, std::atomic> baton;
    kvStore_->asyncMultiRemove(kDefaultSpaceId, kDefaultPartId, expiredJobsAndTasks,
        [&](nebula::kvstore::ResultCode code){
            if (code != kvstore::ResultCode::SUCCEEDED) {
                LOG(ERROR) << "kvstore asyncRemoveRange failed: " << code;
            }
            baton.post();
        });
    baton.wait();
}

ErrorOr<ResultCode, std::pair<cpp2::JobDesc, std::vector<cpp2::TaskDesc>>>
JobManager::showJob(int iJob) {
    auto jobKey = JobDescription::makeJobKey(iJob);
    std::unique_ptr<kvstore::KVIterator> iter;
    ResultCode rc = kvStore_->prefix(kDefaultSpaceId, kDefaultPartId, jobKey, &iter);
    if (rc != nebula::kvstore::SUCCEEDED) {
        return rc;
    }

    if (!iter->valid()) {
        return nebula::kvstore::ERR_KEY_NOT_FOUND;
    }

    std::pair<cpp2::JobDesc, std::vector<cpp2::TaskDesc>> ret;
    for (; iter->valid(); iter->next()) {
        if (JobDescription::isJobKey(iter->key())) {
            auto optJob = JobDescription::makeJobDescription(iter->key(), iter->val());
            if (optJob != folly::none) {
                ret.first = optJob->toJobDesc();
            }
        } else {
            TaskDescription td(iter->key(), iter->val());
            ret.second.emplace_back(td.toTaskDesc());
        }
    }
    return ret;
}

ResultCode JobManager::stopJob(int32_t iJob) {
    auto jobDesc = JobDescription::loadJobDescription(iJob, kvStore_);
    if (jobDesc == folly::none) {
        return nebula::kvstore::ResultCode::ERR_KEY_NOT_FOUND;
    }

    jobDesc->setStatus(cpp2::JobStatus::STOPPED);
    return save(jobDesc->jobKey(), jobDesc->jobVal());
}

/*
 * Return: recovered job num.
 * */
ErrorOr<ResultCode, int32_t> JobManager::recoverJob() {
    int32_t recoveredJobNum = 0;
    std::unique_ptr<kvstore::KVIterator> iter;
    ResultCode rc = kvStore_->prefix(kDefaultSpaceId, kDefaultPartId, JobUtil::jobPrefix(), &iter);
    if (rc != nebula::kvstore::SUCCEEDED) {
        return rc;
    }
    for (; iter->valid(); iter->next()) {
        if (!JobDescription::isJobKey(iter->key())) {
            continue;
        }
        auto optJob = JobDescription::makeJobDescription(iter->key(), iter->val());
        if (optJob != folly::none) {
            if (optJob->getStatus() == cpp2::JobStatus::QUEUE) {
                queue_->enqueue(optJob->getJobId());
                ++recoveredJobNum;
            }
        }
    }
    return recoveredJobNum;
}

ResultCode JobManager::save(const std::string& k, const std::string& v) {
    std::vector<kvstore::KV> data{std::make_pair(k, v)};
    folly::Baton<true, std::atomic> baton;
    nebula::kvstore::ResultCode rc = nebula::kvstore::SUCCEEDED;
    kvStore_->asyncMultiPut(kDefaultSpaceId, kDefaultPartId, std::move(data),
        [&] (nebula::kvstore::ResultCode code){
        rc = code;
        baton.post();
    });
    baton.wait();
    return rc;
}

int JobManager::getSpaceId(const std::string& name) {
    auto indexKey = MetaServiceUtils::indexSpaceKey(name);
    std::string val;
    auto ret = kvStore_->get(kDefaultSpaceId, kDefaultPartId, indexKey, &val);
    if (ret != kvstore::ResultCode::SUCCEEDED) {
        LOG(ERROR) << "KVStore error: " << ret;;
        return -1;
    }
    return *reinterpret_cast<const int*>(val.c_str());
}

}  // namespace meta
}  // namespace nebula

max_stars_repo_name: panda-sheep/nebula-storage

max_issues_repo_name: panda-sheep/nebula-storage

max_forks_repo_name: panda-sheep/nebula-storage


text:
#include <boost/test/auto_unit_test.hpp>
#include <pddl_planner/Planning.hpp>
#include <pddl_planner/representation/Domain.hpp>
#include <pddl_planner/representation/Problem.hpp>

BOOST_AUTO_TEST_CASE(main_lama_test)
{

    using namespace pddl_planner;
    Planning planning;

    std::string domainDescription = "(define (domain rimres)\n(:requirements :strips :equality :typing :conditional-effects)\n(:types location physob_id physob_type)\n(:constants sherpa crex payload - physob_type)\n(:predicates ( at ?x - physob_id ?l - location)\n( is_a ?x - physob_id ?r - physob_type)\n( connected ?x ?y - physob_id)\n( cannot_move ?x - physob_id)\n)\n\n(:action move\n :parameters (?obj - physob_id ?m ?l - location)\n:precondition ( and (at ?obj ?m) (not (= ?m ?l)) (not (cannot_move ?obj) ))\n :effect (and (at ?obj ?l) (not (at ?obj ?m))\n (forall (?z)\n (when (and (connected ?z ?obj) (not (= ?z ?obj)))\n (and (at ?z ?l) (not (at ?z ?m)))\n)))\n)\n (:action move_into_range\n :parameters (?x ?y - physob_id ?m ?l - location)\n :precondition (and (not (cannot_move ?x)) (at ?x ?m) (at ?y ?l) )\n :effect (and (at ?x ?l) (at ?y ?l) (not (at ?x ?m)))\n)\n (:action connect\n :parameters (?x ?y - physob_id ?l - location)\n :precondition (and (at ?x ?l) (at ?y ?l))\n :effect (and (connected ?x ?y) (cannot_move ?y))\n)\n(:action disconnect\n :parameters (?x ?y - physob_id)\n :precondition (and (not (= ?x ?y)) (connected ?x ?y)) \n :effect (and (not (connected ?x ?y)) (not (cannot_move ?y)))\n)\n)\n";

    planning.setDomainDescription("rimres",domainDescription);

    BOOST_TEST_MESSAGE( "Domain description \n" << domainDescription );

    try {
        std::string problemDescription = "(define (problem rimres-1)\n (:domain rimres)\n (:objects\n sherpa_0 crex_0 pl_0 - physob_id\n location_s0 location_c0 location_p0 - location\n mission1 - location\n)\n (:init \n (is_a sherpa_0 sherpa)\n (is_a crex_0 crex)\n (is_a pl_0 payload)\n (at sherpa_0 location_s0)\n (at crex_0 location_c0)\n (at pl_0 location_p0)\n (cannot_move pl_0)\n)\n (:goal (and \n (connected sherpa_0 crex_0) \n (connected sherpa_0 pl_0)\n (at sherpa_0 mission1)\n)\n)\n)\n";
        BOOST_TEST_MESSAGE( "Domain description \n" << problemDescription );

        PlanCandidates planCandidates = planning.plan(problemDescription);

        BOOST_TEST_MESSAGE("PlanCandidates: " << planCandidates.toString());
        BOOST_ASSERT(planCandidates.plans.size() == 2);
    } catch(const std::runtime_error& e)
    {
        BOOST_TEST_MESSAGE("Error: " << e.what());
        BOOST_ASSERT(false);
    }
}

BOOST_AUTO_TEST_CASE(expression_test)
{
    using namespace pddl_planner;
    using namespace pddl_planner::representation;

    Expression andExpr("and","?a","?b");
    Expression notExpr("not", andExpr);
    BOOST_REQUIRE_MESSAGE(andExpr.toLISP() == "(and ?a ?b)", andExpr.toLISP());
    BOOST_REQUIRE_MESSAGE(notExpr.toLISP() == "(not (and ?a ?b))", notExpr.toLISP());

    Expression quantorExpression(EXISTS,TypedItem("?l","location"),
            Expression("and",
                Expression("at","sherpa","?l"),
                Expression("at","crex","?l"))
            );
    BOOST_REQUIRE_MESSAGE(quantorExpression.toLISP() == "(exists (?l - location) (and (at sherpa ?l) (at crex ?l)))", quantorExpression.toLISP());
    Expression notQuantorExpression("not", quantorExpression);

    BOOST_REQUIRE_MESSAGE(notQuantorExpression.toLISP() == "(not (exists (?l - location) (and (at sherpa ?l) (at crex ?l))))", notQuantorExpression.toLISP());
}

BOOST_AUTO_TEST_CASE(domain_test)
{
    using namespace pddl_planner;
    using namespace pddl_planner::representation;

    Domain domain("rimres");

    domain.addRequirement("strips");
    domain.addRequirement("equality");
    domain.addRequirement("typing");
    domain.addRequirement("conditional-effects");

    domain.addType("location");
    domain.addType("physob_id");
    domain.addType("physob_type");

    domain.addConstant( Constant("sherpa","physob_type") );
    domain.addConstant( Constant("crex","physob_type") );
    domain.addConstant( Constant("payload","physob_type") );

    BOOST_REQUIRE_MESSAGE( domain.isConstant("sherpa"), "Has constant: sherpa" );
    BOOST_REQUIRE_MESSAGE( domain.isConstant("crex"), "Has constant: crex" );
    BOOST_REQUIRE_MESSAGE( domain.isConstant("payload"), "Has constant: payload" );

    domain.addPredicate( Predicate("at", TypedItem("?x","physob_id"),TypedItem("?l","physob_id")) );
    domain.addPredicate( Predicate("is_a", TypedItem("?x","physob_id"),TypedItem("?r","physob_type")) );
    domain.addPredicate( Predicate("connected", TypedItem("?x","physob_id"),TypedItem("?y","physob_id")) ) ;
    domain.addPredicate( Predicate("cannot_move", TypedItem("?x","physob_id")) );

    // Action move
    representation::Action move("move", TypedItem("?obj","physob_id"), TypedItem("?m","location"), TypedItem("?l","location"));
    {
        Expression precondition("and", Expression("at", "?obj", "?m"), Expression("not", Expression("=", "?m", "?l")), Expression("not", Expression("cannot_move","?obj")));

        Expression effect("and", Expression("at","?obj","?l"), Expression("not", Expression("at","?obj","?m")), Expression(FORALL, TypedItem("?z","physob_type"), Expression("when", Expression("and", Expression("connected","?z","?obj"), Expression("not", Expression("=","?z","?obj"))), Expression("and", Expression("at","?z","?l"), Expression("not", Expression("at","?z","?m"))))));

        move.addPrecondition(precondition);
        move.addEffect(effect);
        domain.addAction(move);

        BOOST_REQUIRE_THROW(domain.addAction(move), std::invalid_argument);
    }

    // Action move_into_range
    representation::Action move_into_range("move_into_range", TypedItem("?x","physob_id"), TypedItem("?y","physob_id"), TypedItem("?m","location"), TypedItem("?l","location"));
    {
        Expression precondition("and", Expression("not", Expression("cannot_move","?x")), Expression("at","?x","?m"), Expression("at","?y","?l"));
        Expression effect("and", Expression("at","?x","?l"), Expression("at","?y","?l"), Expression("not", Expression("at","?x","?m")));
        move_into_range.addPrecondition(precondition);
        move_into_range.addEffect(effect);
        domain.addAction(move_into_range);
    }

    // Action connect
    representation::Action connect("connect", TypedItem("?x","physob_id"), TypedItem("?y","physob_id"), TypedItem("?l","location"));
    {
        Expression precondition("and", Expression("at","?x","?l"), Expression("at","?y","?l"));
        Expression effect("and", Expression("connected","?x","?y"), Expression("cannot_move","?y"));
        connect.addPrecondition(precondition);
        connect.addEffect(effect);
        domain.addAction(connect);
    }

    // Action connect
    representation::Action disconnect("disconnect", TypedItem("?x","physob_id"), TypedItem("?y","physob_id"));
    {
        Expression precondition("and", Expression("not", Expression("=","?x","?y")), Expression("connected","?x","?y"));
        Expression effect("and", Expression("not", Expression("connected","?x","?y")), Expression("not", Expression("cannot_move","?x")));
        disconnect.addPrecondition(precondition);
        disconnect.addEffect(effect);
        domain.addAction(disconnect);
    }

    BOOST_TEST_MESSAGE( domain.toLISP() );
    BOOST_REQUIRE_NO_THROW( domain.validate() );

    representation::Problem problem("rimres-1",domain);
    problem.addObject( Constant("sherpa_0","physob_id"));
    problem.addObject( Constant("crex_0","physob_id"));
    problem.addObject( Constant("pl_0","physob_id"));
    problem.addObject( Constant("location_s0","location"));
    problem.addObject( Constant("location_c0","location"));
    problem.addObject( Constant("location_p0","location"));
    problem.addObject( Constant("mission1","location"));
    BOOST_TEST_MESSAGE("Added objects");

    problem.addInitialStatus( Expression("is_a","sherpa_0","sherpa") );
    problem.addInitialStatus( Expression("is_a","crex_0","crex") );
    problem.addInitialStatus( Expression("is_a","pl_0","payload") );
    problem.addInitialStatus( Expression("at","sherpa_0","location_s0") );
    problem.addInitialStatus( Expression("at","crex_0","location_c0") );
    problem.addInitialStatus( Expression("at","pl_0","location_p0") );
    problem.addInitialStatus( Expression("cannot_move", "pl_0") );
    BOOST_TEST_MESSAGE("Added initial status");

    Expression subgoal0("connected","sherpa_0","crex_0");
    Expression subgoal1("connected","sherpa_0","pl_0");
    Expression subgoal2("at","sherpa_0","mission1");
    Expression goal("and", subgoal0, subgoal1, subgoal2);
    problem.setGoal(goal);
    std::string goalDescription = "(and (connected sherpa_0 crex_0) (connected sherpa_0 pl_0) (at sherpa_0 mission1))";
    BOOST_REQUIRE_MESSAGE(goal.toLISP() == goalDescription, "Problem goal: " << problem.toLISP() );

    Expression goal1 = goal;
    goal1 = goal;
    BOOST_REQUIRE_MESSAGE(goal1.toLISP() == goalDescription, "Expression assignment: " << problem.toLISP() );

    BOOST_TEST_MESSAGE( problem.domain.toLISP() );
    BOOST_REQUIRE_NO_THROW( problem.validate() );

    Planning planning;
    PlanCandidates planCandidates = planning.plan(problem);

    BOOST_TEST_MESSAGE( "PlanCandidates:\n" << planCandidates.toString());
    BOOST_ASSERT(planCandidates.plans.size() == 2);

    problem.goal.addParameter(Expression("a","sherpa_0","mission1"));

    try {
        problem.validate();
        BOOST_REQUIRE_MESSAGE(false, "Validation expected to throw, but did not");
    } catch(const std::runtime_error& e)
    {
        BOOST_TEST_MESSAGE( e.what() );
    }
}


text:
#include <iostream>
#include <boost/thread/mutex.hpp>

boost::mutex mtx;
class Singleton
{
    public:
        static Singleton& getInstance();

    private:
        Singleton() {std::cout << "Ctor\n";};
        ~Singleton() {std::cout << "Dtor\n";};
        Singleton(const Singleton&);
        const Singleton& operator=(const Singleton&);
};

Singleton& Singleton::getInstance()
{
    boost::mutex::scoped_lock lock(mtx);
    static Singleton instance;
    return instance;

}

int main()
{
    Singleton &s1 = Singleton::getInstance();
    Singleton &s2 = Singleton::getInstance();
    //std::cout << &s1 << " " << &s2 << std::endl;
    return 0;
}

max_stars_repo_name: walker-zheng/code

max_issues_repo_name: walker-zheng/code

max_forks_repo_name: walker-zheng/code


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef _VCLCANVAS_WINDOWOUTDEVHOLDER_HXX
#define _VCLCANVAS_WINDOWOUTDEVHOLDER_HXX

#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/awt/XWindow.hpp>
#include <vcl/window.hxx>

#include "outdevprovider.hxx"

#include <boost/utility.hpp>

namespace vclcanvas
{
    class WindowOutDevHolder : public OutDevProvider,
                               private ::boost::noncopyable
    {
    public:
        explicit WindowOutDevHolder( const ::com::sun::star::uno::Reference<
                                           ::com::sun::star::awt::XWindow>& xWin );

    private:
        virtual OutputDevice& 		getOutDev() { return mrOutputWindow; }
        virtual const OutputDevice& getOutDev() const { return mrOutputWindow; }

        // TODO(Q2): Lifetime issue. Though WindowGraphicDeviceBase
        // now listenes to the window component, I still consider
        // holding a naked reference unsafe here (especially as we
        // pass it around via getOutDev). This _only_ works reliably,
        // if disposing the SpriteCanvas correctly disposes all
        // entities which hold this pointer.
        // So: as soon as the protocol inside
        // vcl/source/window/window.cxx is broken, that disposes the
        // canvas during window deletion, we're riding a dead horse
        // here
        Window& mrOutputWindow;
    };
}

#endif /* _VCLCANVAS_WINDOWOUTDEVHOLDER_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/*
 * Copyright 2013 Matthew Harvey
 *
 * 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 "gui/entry_list_ctrl.hpp"
#include "account.hpp"
#include "account_type.hpp"
#include "app.hpp"
#include "date.hpp"
#include "date_parser.hpp"
#include "entry.hpp"
#include "entry_table_iterator.hpp"
#include "ordinary_journal.hpp"
#include "dcm_database_connection.hpp"
#include "gui/bs_account_entry_list_ctrl.hpp"
#include "gui/locale.hpp"
#include "gui/persistent_object_event.hpp"
#include "gui/pl_account_entry_list_ctrl.hpp"
#include "gui/reconciliation_entry_list_ctrl.hpp"
#include "gui/summary_datum.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <jewel/assert.hpp>
#include <jewel/log.hpp>
#include <jewel/on_windows.hpp>
#include <jewel/optional.hpp>
#include <sqloxx/handle.hpp>
#include <sqloxx/id.hpp>
#include <wx/event.h>
#include <wx/string.h>
#include <wx/gdicmn.h>
#include <wx/progdlg.h>
#include <wx/scrolwin.h>
#include <algorithm>
#include <string>
#include <type_traits>
#include <vector>

using boost::lexical_cast;
using boost::optional;
using jewel::value;
using sqloxx::Handle;
using sqloxx::Id;
using sqloxx::SQLStatement;
using std::is_signed;
using std::pair;
using std::string;
using std::unique_ptr;
using std::vector;

namespace gregorian = boost::gregorian;

namespace dcm
{
namespace gui
{

BEGIN_EVENT_TABLE(EntryListCtrl, wxListCtrl)
    EVT_LIST_ITEM_ACTIVATED
    (   wxID_ANY,
        EntryListCtrl::on_item_activated
    )
END_EVENT_TABLE()

EntryListCtrl::EntryListCtrl
(   wxWindow* p_parent,
    wxSize const& p_size,
    DcmDatabaseConnection& p_database_connection
):
    wxListCtrl
    (   p_parent,
        wxID_ANY,
        wxDefaultPosition,
        p_size,
        wxLC_REPORT | wxFULL_REPAINT_ON_RESIZE
    ),
    m_database_connection(p_database_connection)
{
}

EntryListCtrl::~EntryListCtrl()
{
}

EntryListCtrl*
EntryListCtrl::create_actual_ordinary_entry_list
(   wxWindow* p_parent,
    wxSize const& p_size,
    Handle<Account> const& p_account,
    optional<gregorian::date> const& p_maybe_min_date,
    optional<gregorian::date> const& p_maybe_max_date
)
{
    EntryListCtrl* ret = nullptr;
    switch (p_account->account_super_type())
    {
    case AccountSuperType::balance_sheet:
        ret = new BSAccountEntryListCtrl
        (   p_parent,
            p_size,
            p_account,
            p_maybe_min_date,
            p_maybe_max_date
        );
        break;
    case AccountSuperType::pl:
        ret = new PLAccountEntryListCtrl
        (   p_parent,
            p_size,
            p_account,
            p_maybe_min_date,
            p_maybe_max_date
        );
        break;
    default:
        JEWEL_HARD_ASSERT (false);  // Execution never reaches here.
    }
    JEWEL_ASSERT (ret);
    initialize(ret);
    return ret;
}

ReconciliationEntryListCtrl*
EntryListCtrl::create_reconciliation_entry_list
(   ReconciliationListPanel* p_parent,
    wxSize const& p_size,
    Handle<Account> const& p_account,
    gregorian::date const& p_min_date,
    gregorian::date const& p_max_date
)
{
    JEWEL_ASSERT
    (   p_account->account_super_type() ==
        AccountSuperType::balance_sheet
    );
    ReconciliationEntryListCtrl* ret = new ReconciliationEntryListCtrl
    (   p_parent,
        p_size,
        p_account,
        p_min_date,
        p_max_date
    );
    initialize(ret);
    return ret;
}

void
EntryListCtrl::initialize(EntryListCtrl* p_entry_list_ctrl)
{
    p_entry_list_ctrl->insert_columns();
    p_entry_list_ctrl->do_initialize_summary_data();
    p_entry_list_ctrl->populate();
    p_entry_list_ctrl->set_column_widths();
    p_entry_list_ctrl->Fit();
    p_entry_list_ctrl->Layout();
    return;
}

void
EntryListCtrl::insert_columns()
{
    insert_date_column();
    do_insert_non_date_columns();
    return;
}

void
EntryListCtrl::insert_date_column()
{
    InsertColumn(date_col_num(), "Date", wxLIST_FORMAT_RIGHT);
    return;
}

void
EntryListCtrl::populate()
{
    unique_ptr<SQLStatement> statement = do_create_entry_selector();
    while (statement->step())
    {
        process_push_candidate_entry
        (   Handle<Entry>
            (   database_connection(),
                statement->extract<Id>(0)
            )
        );
    }
    return;
}

void
EntryListCtrl::autosize_column_widths()
{
    int const num_cols = num_columns();
    for (int i = 0; i != num_cols; ++i)
    {
        SetColumnWidth(i, wxLIST_AUTOSIZE);
#       ifdef JEWEL_ON_WINDOWS
            // Overcome glitch on Windows build where column headers
            // are not taken into account in width calculation.
            SetColumnWidth(i, std::max(GetColumnWidth(i), 100));
#       endif
    }
    return;
}

void
EntryListCtrl::adjust_comment_column_to_fit()
{
    int const ccn = do_get_comment_col_num();
    if (ccn >= 0)
    {
        int total_widths = 0;
        int const num_cols = num_columns();
        for (int i = 0; i != num_cols; ++i) total_widths += GetColumnWidth(i);
        int const shortfall =
            GetSize().GetWidth() - total_widths - scrollbar_width_allowance();
        int const current_comment_width = GetColumnWidth(ccn);
        SetColumnWidth(ccn, current_comment_width + shortfall);
    }
    return;

}

gregorian::date
EntryListCtrl::date_displayed(long p_row, DateParser const& p_parser) const
{
    JEWEL_ASSERT (date_col_num() == 0);
    optional<gregorian::date> const maybe_date =
        p_parser.parse(GetItemText(p_row));
    JEWEL_ASSERT (maybe_date);
    return value(maybe_date);
}

long
EntryListCtrl::row_for_date(gregorian::date const& p_date) const
{
    long min = 0;
    long const num_rows = GetItemCount();
    long max = num_rows;

    // Deal with common or special cases
    if (max == 0)
    {
        // No Entries displayed
        return 0;
    }
    JEWEL_ASSERT (max == num_rows);
    JEWEL_ASSERT (max > 0);
    DateParser const parser;
    if (date_displayed(max - 1, parser) <= p_date)
    {
        // Very end
        return max;
    }
    // Date is neither first nor last... find it using binary search.
    while (true)
    {
        JEWEL_ASSERT (min < max);
        long guess = (min + max) / 2;
        if (guess == min)
        {
            // Find end of contiguous rows showing this date
            while ((date_displayed(guess, parser) == p_date) && (guess != num_rows))
            {
                ++guess;
            }
            return guess;
        }
        gregorian::date const date = date_displayed(guess, parser);
        JEWEL_ASSERT (guess > 0);
        gregorian::date const predecessor_date = date_displayed(guess - 1, parser);
        JEWEL_ASSERT (predecessor_date <= date);
        if ((predecessor_date <= p_date) && (p_date <= date))
        {
            // Find end of contiguous rows showing this date
            while ((date_displayed(guess, parser) == p_date) && (guess != num_rows))
            {
                ++guess;
            }
            return guess;
        }
        JEWEL_ASSERT ((p_date < predecessor_date) || (date < p_date));
        if (p_date < predecessor_date)
        {
            JEWEL_ASSERT (guess < max);
            max = guess;
        }
        else if (date < p_date)
        {
            JEWEL_ASSERT (guess > min);
            min = guess;
        }
    }
}

void
EntryListCtrl::set_column_widths()
{
    do_set_column_widths();
    return;
}

void
EntryListCtrl::process_push_candidate_entry(Handle<Entry> const& p_entry)
{
    JEWEL_ASSERT (p_entry->has_id());
    do_process_candidate_entry_for_summary(p_entry);
    if (do_approve_entry(p_entry)) push_back_entry(p_entry);
    return;
}

void
EntryListCtrl::process_insertion_candidate_entry
(   Handle<Entry> const& p_entry,
    long p_row
)
{
    JEWEL_ASSERT (p_entry->has_id());
    do_process_candidate_entry_for_summary(p_entry);
    if (do_approve_entry(p_entry)) insert_entry(p_entry, p_row);
    return;
}

void
EntryListCtrl::do_update_for_amended(Handle<Account> const& p_account)
{
    (void)p_account;  // Silence compiler re. unused variable
    return;
}

void
EntryListCtrl::on_item_activated(wxListEvent& event)
{
    Handle<Entry> const entry
    (   database_connection(),
        GetItemData(event.GetIndex())
    );

    // Fire a PersistentJournal editing request. This will be handled
    // higher up the window hierarchy.
    PersistentObjectEvent::fire
    (   this,
        DCM_JOURNAL_EDITING_EVENT,
        entry->journal_id()
    );
    return;
}

void
EntryListCtrl::update_for_new(Handle<OrdinaryJournal> const& p_journal)
{
    if (p_journal->is_actual())
    {
        for (Handle<Entry> const& entry: p_journal->entries())
        {
            process_insertion_candidate_entry(entry);
        }
    }
    set_column_widths();
    return;
}

void
EntryListCtrl::update_for_amended(Handle<OrdinaryJournal> const& p_journal)
{
    if (!p_journal->is_actual())
    {
        return;
    }
    JEWEL_ASSERT (p_journal->is_actual());
    wxString const wx_date_string = date_format_wx(p_journal->date());
    DateParser const parser;
    for (Handle<Entry> const& entry: p_journal->entries())
    {
        long updated_pos = -1;
        JEWEL_ASSERT (entry->has_id());
        IdSet::const_iterator const jt = m_id_set.find(entry->id());
        if (jt != m_id_set.end())
        {
            long const pos = FindItem(-1, entry->id());
            JEWEL_ASSERT
            (   GetItemData(pos) ==
                static_cast<unsigned long>(entry->id())
            );
            gregorian::date const old_date = date_displayed(pos, parser);
            do_process_removal_for_summary(pos);
            DeleteItem(pos);
            m_id_set.erase(jt);
            if (old_date == entry->date())
            {
                updated_pos = pos;
            }
        }
        process_insertion_candidate_entry(entry, updated_pos);
    }
    set_column_widths();
    return;
}

void
EntryListCtrl::update_for_new(Handle<Account> const& p_account)
{
    (void)p_account;  // Silence compiler re. unused parameter.
    // Nothing to do.
    return;
}

void
EntryListCtrl::update_for_amended(Handle<Account> const& p_account)
{
    do_update_for_amended(p_account);
    return;
}

void
EntryListCtrl::update_for_deleted(vector<sqloxx::Id> const& p_doomed_ids)
{
    for (sqloxx::Id const doomed_id: p_doomed_ids)
    {
        remove_if_present(doomed_id);
    }
    return;
}

vector<Handle<Entry> >
EntryListCtrl::selected_entries()
{
    vector<Handle<Entry> > ret;
    size_t i = 0;
    size_t const lim = GetItemCount();
    for ( ; i != lim; ++i)
    {
        if (GetItemState(i, wxLIST_STATE_SELECTED))
        {
            Handle<Entry> const entry(m_database_connection, GetItemData(i));
            ret.push_back(entry);
        }
    }
    return ret;
}

void
EntryListCtrl::scroll_to_bottom()
{
    int const count = GetItemCount();
    if (count > 0) EnsureVisible(count - 1);
    return;
}

vector<SummaryDatum> const&
EntryListCtrl::summary_data() const
{
    return do_get_summary_data();
}

int
EntryListCtrl::num_columns() const
{
    return do_get_num_columns();
}

int
EntryListCtrl::scrollbar_width_allowance() const
{
    // TODO LOW PRIORITY Make this more precise
    return 50;
}

vector<SummaryDatum> const&
EntryListCtrl::do_get_summary_data() const
{
    static const vector<SummaryDatum> ret;
    JEWEL_ASSERT (ret.empty());
    return ret;
}

void
EntryListCtrl::do_initialize_summary_data()
{
    // Do nothing.
    return;
}

void
EntryListCtrl::do_process_candidate_entry_for_summary
(   Handle<Entry> const& p_entry
)
{
    (void)p_entry;  // Silence compiler re. unused parameter.
    return;
}

void
EntryListCtrl::do_process_removal_for_summary(long p_row)
{
    (void)p_row;  // Silence compiler re. unused parameter.
    return;
}

int
EntryListCtrl::date_col_num() const
{
    return 0;
}

void
EntryListCtrl::push_back_entry(Handle<Entry> const& p_entry)
{
    auto const i = GetItemCount();
    JEWEL_ASSERT (date_col_num() == 0);
    InsertItem(i, date_format_wx(p_entry->date()));
    do_set_non_date_columns(i, p_entry);

    // The item may change position due to e.g. sorting, so store the
    // Entry ID in the item's data
    static_assert
    (   (sizeof(long) >= sizeof(decltype(p_entry->id()))) &&
        is_signed<long>::value &&
        is_signed<decltype(p_entry->id())>::value,
        "Cannot safely fit values of type of p_entry->id() into the type "
        "of i, in function EntryListCtrl::push_back_entry."
    );
    SetItemData(i, p_entry->id());
    m_id_set.insert(p_entry->id());
    return;
}

void
EntryListCtrl::insert_entry(Handle<Entry> const& p_entry, long p_row)
{
    gregorian::date const date = p_entry->date();
    JEWEL_ASSERT (p_row >= -1);
    long const pos = ((p_row == -1)? row_for_date(date): p_row);
    InsertItem(pos, date_format_wx(date));
    do_set_non_date_columns(pos, p_entry);
    sqloxx::Id const id = p_entry->id();
    SetItemData(pos, id);
    m_id_set.insert(id);
    return;
}

void
EntryListCtrl::remove_if_present(sqloxx::Id p_entry_id)
{
    IdSet::const_iterator const it = m_id_set.find(p_entry_id);
    if (it != m_id_set.end())
    {
        long const pos = FindItem(-1, p_entry_id);
        JEWEL_ASSERT
        (   GetItemData(pos) ==
            static_cast<unsigned long>(p_entry_id)
        );
        do_process_removal_for_summary(pos);
        DeleteItem(pos);
        m_id_set.erase(it);
    }
    return;
}

DcmDatabaseConnection&
EntryListCtrl::database_connection()
{
    return m_database_connection;
}

DcmDatabaseConnection const&
EntryListCtrl::database_connection() const
{
    return m_database_connection;
}

}  // namespace gui
}  // namespace dcm

max_stars_repo_name: skybaboon/dailycashmanager

max_issues_repo_name: skybaboon/dailycashmanager

max_forks_repo_name: skybaboon/dailycashmanager


text:
/*=========================================================================
 *
 *  Copyright David Doria 2012 daviddoria@gmail.com
 *
 *  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.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#ifndef FeatureVectorPrecomputedStructuredGridNormalsDescriptorVisitor_HPP
#define FeatureVectorPrecomputedStructuredGridNormalsDescriptorVisitor_HPP

// Custom
#include "PixelDescriptors/FeatureVectorPixelDescriptor.h"
#include "Concepts/DescriptorConcept.hpp"
#include "DescriptorVisitorParent.h"

// Boost
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>

// ITK
#include "itkIndex.h"

// VTK
#include <vtkFloatArray.h>
#include <vtkPointData.h>
#include <vtkStructuredGrid.h>

/**
 * This is a visitor that complies with the DescriptorVisitorConcept. It creates
 * FeatureVectorPixelDescriptor objects at each node. These descriptors are computed
 * before hand and read in from a vts file (into a vtkStructuredGrid). The mapping from
 * 3D points to pixels is provided implicity by the grid.
 */
template <typename TGraph, typename TDescriptorMap>
struct FeatureVectorPrecomputedStructuredGridNormalsDescriptorVisitor : public DescriptorVisitorParent<TGraph>
{
  typedef typename boost::property_traits<TDescriptorMap>::value_type DescriptorType;
  BOOST_CONCEPT_ASSERT((DescriptorConcept<DescriptorType, TGraph>));

  typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;

  TDescriptorMap& DescriptorMap;

  vtkStructuredGrid* FeatureStructuredGrid;

  vtkFloatArray* NormalsArray;

  FeatureVectorPrecomputedStructuredGridNormalsDescriptorVisitor(TDescriptorMap& descriptorMap, vtkStructuredGrid* const featureStructuredGrid) :
  DescriptorMap(descriptorMap), FeatureStructuredGrid(featureStructuredGrid)
  {
    this->NormalsArray = vtkFloatArray::SafeDownCast(this->FeatureStructuredGrid->GetPointData()->GetNormals());
    if(!this->NormalsArray)
    {
      std::stringstream ss;
      ss << "Structured grid does not have a float normals array!";
      throw std::runtime_error(ss.str());
    }
    if(this->NormalsArray->GetNumberOfComponents() != 3)
    {
      throw std::runtime_error("Normals array should have 3 components!");
    }
  }

  void initialize_vertex(VertexDescriptorType v, TGraph& g) const override
  {
    //std::cout << "Initializing " << v[0] << " " << v[1] << std::endl;
    unsigned int numberOfMissingPoints = 0;

    int queryPoint[3] = {v[0], v[1], 0};
    int dimensions[3];
    this->FeatureStructuredGrid->GetDimensions(dimensions);
    vtkIdType pointId = vtkStructuredData::ComputePointId(dimensions, queryPoint);
    if(this->FeatureStructuredGrid->IsPointVisible (pointId))
    {
      float descriptorValues[this->NormalsArray->GetNumberOfComponents()];
      this->NormalsArray->GetTupleValue(pointId, descriptorValues);

      std::vector<float> featureVector(descriptorValues, descriptorValues + sizeof(descriptorValues) / sizeof(float) );

      DescriptorType descriptor(featureVector);
      descriptor.SetVertex(v);
      descriptor.SetStatus(PixelDescriptor::SOURCE_NODE);
      put(this->DescriptorMap, v, descriptor);
    }
    else
    {
      //std::cout << index << " not found in the map!" << std::endl;
      numberOfMissingPoints++;

      std::vector<float> featureVector(this->NormalsArray->GetNumberOfComponents(), 0);

      DescriptorType descriptor(featureVector);
      descriptor.SetVertex(v);
      descriptor.SetStatus(PixelDescriptor::INVALID);
      put(this->DescriptorMap, v, descriptor);
    }

    //std::cout << "There were " << numberOfMissingPoints << " missing points when computing the descriptor for node " << index << std::endl;
  }

  void DiscoverVertex(VertexDescriptorType v, TGraph& g) const override
  {
    // std::cout << "Discovered " << v[0] << " " << v[1] << std::endl;
    DescriptorType& descriptor = get(this->DescriptorMap, v);
    descriptor.SetStatus(DescriptorType::TARGET_NODE);
  }

}; // FeatureVectorPrecomputedStructuredGridNormalsDescriptorVisitor

#endif

ext: hpp

max_stars_repo_name: jingtangliao/ff

max_issues_repo_name: jingtangliao/ff

max_forks_repo_name: jingtangliao/ff


text:
// Copyright (C) 2018 Tobias Loew
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt)

#include <boost/config.hpp>
#include <boost/config/pragma_message.hpp>

#if defined(BOOST_NO_CXX11_LAMBDAS)

BOOST_PRAGMA_MESSAGE("Skipping test due to BOOST_NO_CXX11_LAMBDAS")
int main() {}

#elif defined(BOOST_NO_CXX11_AUTO_DECLARATIONS)

BOOST_PRAGMA_MESSAGE("Skipping test due to BOOST_NO_CXX11_AUTO_DECLARATIONS")
int main() {}

#else

#include <boost/typeof/typeof.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

namespace detail {
    template<class T> inline T& deref(T& r) {
        return  r;
    }
    template<class T>
    struct wrapper {
        typedef T type;
    };

    template<class T> wrapper<T> wrap(T&);
};

BOOST_TYPEOF_REGISTER_TEMPLATE(::detail::wrapper, 1)

void test_typeof_in_lambda() {
    // Visual Studio 2015 (BOOST_MSVC == 1900) had an internal compiler error with Boost 1.65 and 1.66 when using BOOST_SCOPE_EXIT inside a lambda
    // the error was due to a change of include in boost/typeof/typeof.hpp  (<boost/typeof/decltype.hpp> instead of <boost/typeof/native.hpp>)
    // This test is an more or less minimal extract from the BOOST_SCOPE_EXIT macro expansions

    // worked also with VS 2015 in version 1.65/1.66
    int n;
    typedef BOOST_TYPEOF(::detail::wrap(::detail::deref(n))) n_type_wrapped;
    typedef  n_type_wrapped::type n_type;

    int test;

    auto check_property = [&n,&test]() {
        // internal compiler error with VS 2015 in version 1.65/1.66
        // minimal extract from
        //BOOST_SCOPE_EXIT(test) {
        //    test = 42;
        //}BOOST_SCOPE_EXIT_END

        // this compiles always (as long as the one before outside the lambda has the same name)
        typedef BOOST_TYPEOF(::detail::wrap(::detail::deref(n))) n_type_wrapped;
        typedef  n_type_wrapped::type n_type;

        // this fails with internal compiler error with VS 2015 in version 1.65/1.66
        typedef BOOST_TYPEOF(::detail::wrap(::detail::deref(test))) test_type_wrapped;
        typedef  test_type_wrapped::type test_type;

    };

}

int main() {
    test_typeof_in_lambda();

    return 0;
}

#endif


text:
// All content Copyright (C) 2018 Genomics plc
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>

#include "utils/multinomialCoefficients.hpp"

BOOST_AUTO_TEST_CASE( factorial_0 ) { BOOST_CHECK_EQUAL( 1, factorial( 0 ) ); }

BOOST_AUTO_TEST_CASE( factorial_1 ) { BOOST_CHECK_EQUAL( 1, factorial( 1 ) ); }

BOOST_AUTO_TEST_CASE( factorial_2 ) { BOOST_CHECK_EQUAL( 2, factorial( 2 ) ); }

BOOST_AUTO_TEST_CASE( factorial_3 ) { BOOST_CHECK_EQUAL( 6, factorial( 3 ) ); }

max_stars_repo_name: dylex/wecall

max_issues_repo_name: dylex/wecall

max_forks_repo_name: dylex/wecall


text:
// $Id$
// vim:tabstop=2
/***********************************************************************
 Moses - factored phrase-based language decoder
 Copyright (C) 2010 Hieu Hoang

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ***********************************************************************/

#include "ChartCell.h"
#include "ChartCellCollection.h"
#include "ChartTranslationOptions.h"
#include "RuleCube.h"
#include "RuleCubeQueue.h"
#include "StaticData.h"
#include "Util.h"
#include "Range.h"
#include <boost/functional/hash.hpp>

using namespace std;

namespace Moses
{
extern bool g_mosesDebug;

// initialise the RuleCube by creating the top-left corner item
RuleCube::RuleCube(const ChartTranslationOptions &transOpt,
                   const ChartCellCollection &allChartCells,
                   ChartManager &manager)
  : m_transOpt(transOpt)
{
  RuleCubeItem *item = new RuleCubeItem(transOpt, allChartCells);
  m_covered.insert(item);
  if (StaticData::Instance().options()->cube.lazy_scoring) {
    item->EstimateScore();
  } else {
    item->CreateHypothesis(transOpt, manager);
  }
  m_queue.push(item);
}

RuleCube::~RuleCube()
{
  RemoveAllInColl(m_covered);
}

RuleCubeItem *RuleCube::Pop(ChartManager &manager)
{
  RuleCubeItem *item = m_queue.top();
  m_queue.pop();
  CreateNeighbors(*item, manager);
  return item;
}

// create new RuleCube for neighboring principle rules
void RuleCube::CreateNeighbors(const RuleCubeItem &item, ChartManager &manager)
{
  // create neighbor along translation dimension
  const TranslationDimension &translationDimension =
    item.GetTranslationDimension();
  if (translationDimension.HasMoreTranslations()) {
    CreateNeighbor(item, -1, manager);
  }

  // create neighbors along all hypothesis dimensions
  for (size_t i = 0; i < item.GetHypothesisDimensions().size(); ++i) {
    const HypothesisDimension &dimension = item.GetHypothesisDimensions()[i];
    if (dimension.HasMoreHypo()) {
      CreateNeighbor(item, i, manager);
    }
  }
}

void RuleCube::CreateNeighbor(const RuleCubeItem &item, int dimensionIndex,
                              ChartManager &manager)
{
  RuleCubeItem *newItem = new RuleCubeItem(item, dimensionIndex);
  std::pair<ItemSet::iterator, bool> result = m_covered.insert(newItem);
  if (!result.second) {
    delete newItem;  // already seen it
  } else {
    if (StaticData::Instance().options()->cube.lazy_scoring) {
      newItem->EstimateScore();
    } else {
      newItem->CreateHypothesis(m_transOpt, manager);
    }
    m_queue.push(newItem);
  }
}

std::ostream& operator<<(std::ostream &out, const RuleCube &obj)
{
  out << obj.GetItemSetSize();
  return out;
}
}

max_issues_repo_name: Pangeamt/nectm

max_forks_repo_name: Pangeamt/nectm


text:
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * 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.
 */

#include "glean/ffi/wrap.h"
#include "glean/interprocess/cpp/counters.h"
#include "glean/interprocess/cpp/counters_ffi.h"

#include <fstream>
#include <unordered_map>

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>

using namespace facebook::glean;

extern "C" {

struct glean_interprocess_counters_t final
    : public facebook::glean::interprocess::Counters{
  boost::interprocess::file_mapping mapping;
  boost::interprocess::mapped_region region;
  std::atomic<uint64_t> *counters;
  size_t size;

  explicit glean_interprocess_counters_t(const char *path, size_t n) {
    mapping = boost::interprocess::file_mapping(
      path, boost::interprocess::read_write);
    region = boost::interprocess::mapped_region(
      mapping,
      boost::interprocess::read_write,
      0,
      n * sizeof(uint64_t));
    counters = static_cast<std::atomic<uint64_t> *>(region.get_address());
    size = n;
    assert(std::atomic_is_lock_free(counters));
  }

  static void create(
      const char *path,
      size_t n) {
    std::vector<uint64_t> contents(n, 0);
    std::ofstream stream(path, std::ios::out | std::ios::binary);
    stream.write(
      reinterpret_cast<const char *>(contents.data()), n * sizeof(uint64_t));
  }

  std::atomic<uint64_t> *counter(size_t i) override {
    if (i >= size) {
      throw std::invalid_argument("counter index out of range");
    }
    return counters + i;
  }
};

const char *glean_interprocess_counters_create(const char *path, size_t size) {
  return ffi::wrap([=] {
    glean_interprocess_counters_t::create(path, size);
  });
}

const char *glean_interprocess_counters_open(
    const char *path,
    size_t size,
    glean_interprocess_counters_t **counters) {
  return ffi::wrap([=] {
    *counters = new glean_interprocess_counters_t(path, size);
  });
}

void glean_interprocess_counters_close(
    glean_interprocess_counters_t *counters) {
  ffi::free_(counters);
}

const char *glean_interprocess_counters_set(
    glean_interprocess_counters_t *counters,
    size_t index,
    uint64_t value) {
  return ffi::wrap([=] {
    counters->counter(index)->store(value);
  });
}

const char *glean_interprocess_counters_get(
    glean_interprocess_counters_t *counters,
    size_t index,
    uint64_t *value) {
  return ffi::wrap([=] {
    *value = counters->counter(index)->load();
  });
}

}

namespace facebook {
namespace glean {
namespace interprocess {

void countersSetup(const std::string& path, size_t size) {
  glean_interprocess_counters_t::create(path.c_str(), size);
}

std::unique_ptr<Counters> counters(const std::string& path, size_t size) {
  return std::make_unique<glean_interprocess_counters_t>(path.c_str(), size);
}

}
}
}

max_issues_repo_name: facebookincubator/Glean


text:
/**
 * @file
 * @license BSD 3-clause
 * @copyright Copyright (c) 2020, New York University and Max Planck
 * Gesellschaft
 *
 * @brief Implements a qp allocating forces to track a desired centroidal wrench.
 *
 */

#pragma once

#include <Eigen/Dense>
#include <eiquadprog/eiquadprog-fast.hpp>

namespace blmc_controllers
{
typedef Eigen::Array<double, 6, 1> Array6d;
typedef Eigen::Matrix<double, 6, 1> Vector6d;

/**
 * @brief Impedance controller between any two frames of the robot.
 */
class CentroidalForceQPController
{
public:
    /**
     * @brief Construct a new ImpedanceController object.
     */
    CentroidalForceQPController();

    /**
     * @brief Initialize the internal data. None real-time safe method.
     *
     * @param number_endeffectors Maximum number of endeffectors in the problem.
     * @param friction_coeff Floor friction coefficient to use.
     * @param qp_penalty_lin The penalty weight for the linear wcom violation.
     * @param qp_penalty_ang The penalty weight for the angular wcom violation.
     */
    void initialize(int number_endeffectors, double friction_coeff,
                    double qp_penalty_lin, double qp_penalty_ang);

    /**
     * @brief Computes the centroidal wrench using a PD controller.
     *
     * @param w_com The desired centroidal wrench to track.
     * @param relative_position_endeff The relative position of the endeffectors
     *     with respect to the center of mass.
     */
    void run(Eigen::Ref<const Vector6d> w_com,
             Eigen::Ref<const Eigen::VectorXd> relative_position_endeff,
             Eigen::Ref<const Eigen::VectorXd> cnt_array);

    /**
     * @brief Get the computed desired forces
     *
     * @return Eigen::VectorXd&
     */
    Eigen::VectorXd& get_forces();

private:  // attributes
    /** @brief Output forces */
    Eigen::VectorXd forces_;
    Eigen::VectorXd sol_;

    Eigen::MatrixXd hess_;
    Eigen::MatrixXd ce_;
    Eigen::MatrixXd ce_new_;
    Eigen::MatrixXd ci_;

    Eigen::VectorXd g0_;
    Eigen::VectorXd ci0_;

    int nb_eff_;

    double mu_;

    double qp_penalty_lin_;
    double qp_penalty_ang_;

    eiquadprog::solvers::EiquadprogFast qp_;

};

}  // namespace blmc_controllers


text:
#include <iostream>
#include <armadillo>

#include "Isomap.h"

int main(int argc, const char * argv[]) {

    isomap::Isomap isomap;

    // Format is
    std::srand(0);
    arma::fmat input = arma::randn<arma::fmat>(20000, 100).t();

    auto start = std::chrono::steady_clock::now();
    auto knn = isomap.knn(input, 10);
    auto end = std::chrono::steady_clock::now();

    std::cout << double(std::chrono::nanoseconds(end - start).count()) / double(std::nano::den) << std::endl;

    //std::tie(knnIndex, knnDistance) = kNearestNeighbours(); // TODO parameters (k epsilon)

    // Work out how much GPU memory we have
    // We need to split input into an appropriate sized chunks
    // These chunks need to be sized that (K * n * sizeof(size_t)) + (K * n * sizeof(double)) + 2x < gpumemory

    // Allocate a matrix to hold the results of the KNN operation (K * n doubles), (k * n size_t)

    // Call the KNN kernel for each chunk of memory passing in each input and output chunk

    return 0;
}

max_stars_repo_name: TrentHouliston/IMP

max_issues_repo_name: TrentHouliston/IMP

max_forks_repo_name: TrentHouliston/IMP