text:
/*
 * flex_shoebox_extractor.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/array_family/shoebox_extractor.h>

namespace dials { namespace af { namespace boost_python {

  using namespace boost::python;

  void export_flex_shoebox_extractor() {
    class_<ShoeboxExtractor>("ShoeboxExtractor", no_init)
      .def(init<af::reflection_table, std::size_t, int, int>(
        (boost::python::arg("data"),
         boost::python::arg("npanels"),
         boost::python::arg("frame0"),
         boost::python::arg("frame1"))))
      .def("next", &ShoeboxExtractor::next<int>)
      .def("next", &ShoeboxExtractor::next<float>)
      .def("next", &ShoeboxExtractor::next<double>)
      .def("finished", &ShoeboxExtractor::finished)
      .def("frame0", &ShoeboxExtractor::frame0)
      .def("frame1", &ShoeboxExtractor::frame1)
      .def("frame", &ShoeboxExtractor::frame)
      .def("nframes", &ShoeboxExtractor::nframes)
      .def("npanals", &ShoeboxExtractor::npanels);
  }

}}}  // namespace dials::af::boost_python

max_stars_repo_name: TiankunZhou/dials

max_issues_repo_name: TiankunZhou/dials

max_forks_repo_name: TiankunZhou/dials


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

/**
 * @file sat_solver.hpp
 *
 * @brief Generic SAT solver interface
 *
 * @author Mathias Soeken
 * @author Heinz Riener
 *
 * @since  2.2
 */

/******************************************************************************
 * Simple generic SAT solver interface                                        *
 ******************************************************************************
 *                                                                            *
 * Synopsis:                                                                  *
 *                                                                            *
 *   Provides some simple generic functions which are used in many SAT-based  *
 *   algorithms.  These functions can be specialized for several SAT solvers. *
 *                                                                            *
 * API:                                                                       *
 *                                                                            *
 *   Solver make_solver( [properties] )                                       *
 *     Creates a solver                                                       *
 *                                                                            *
 *   bool add_clause( solver )( clause )                                      *
 *     Adds a clause (container of literals) to the solver and returns false, *
 *     if a conflict was detected and the instance is UNSAT.                  *
 *     Each literal is a positive or negative integer different from 0.       *
 *                                                                            *
 *   solver_result_t solve( solver, [statistics, [assumptions]] )             *
 *     Solves the instance.  The statistics data stores runtime, number of    *
 *     variables and number of clauses. Assumptions are a list of literals.   *
 *                                                                            *
 *   solver_gen_model( solver, genmodel )                                     *
 *     Allows to turn off model generation, if one is only interested in the  *
 *     SAT/UNSAT answer.                                                      *
 ******************************************************************************/

#ifndef SAT_SOLVER_HPP
#define SAT_SOLVER_HPP

#include <vector>

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

#include <core/properties.hpp>

namespace cirkit
{

using clause_t = std::vector<int>;

/**
 * @brief Solver result type
 *
 * If the value is empty, the result was unsatisfiable, otherwise the first
 * bitset holds the values of assigned variables where the second bitset masks
 * the assigned variables (1 = contained, 0 = don't care)
 */
using solver_result_t = boost::optional<std::pair<boost::dynamic_bitset<>, boost::dynamic_bitset<>>>;

struct solver_execution_statistics
{
  unsigned num_vars = 0;
  unsigned num_clauses = 0;
  double parse_time = 0.0;
  double runtime = 0.0;
  uint64_t num_conflicts = 0;
};

template<class S>
class solver_traits {};

template<class Base>
class base_clause_adder : public Base
{
public:
  template<class S>
  base_clause_adder( S& solver ) : Base( solver ) {}

  template<class C>
  inline bool operator()( const C& clause )
  {
    return Base::add( clause );
  }

  inline bool operator()( const std::initializer_list<int>& clause )
  {
    return Base::add( clause );
  }
};

template<class S>
S make_solver( properties::ptr settings = properties::ptr() );

template<class S>
typename solver_traits<S>::clause_adder add_clause( S& solver );

template<class S>
solver_result_t solve( S& solver, solver_execution_statistics& statistics, const std::vector<int>& assumptions = std::vector<int>() );

template<class S>
solver_result_t solve( S& solver )
{
  solver_execution_statistics ignore;
  return solve( solver, ignore );
}

template<class S>
void solver_gen_model( S& solver, bool genmodel )
{
  assert( false && "not implemented" );
}

template<class S>
void solver_add_blocking_var( S& solver, int var )
{
  assert( false && "not implemented" );
}

template<class S>
void solver_clear_blocking_vars( S& solver )
{
  assert( false && "not implemented" );
}

template<class S>
inline void equals( S& solver, int a, int b )
{
  add_clause( solver )( {-a, b} );
  add_clause( solver )( {a, -b} );
}

template<class S>
inline void not_equals( S& solver, int a, int b )
{
  add_clause( solver )( {a, b} );
  add_clause( solver )( {-a, -b} );
}

}

#endif

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

ext: hpp

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
#include "gtest/gtest.h"
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <csugar.h>
#include <map>
#include <vector>

using namespace csugar;

TEST(tests_json, test_json) {
  std::string json = R"({"foo":"bar"})";
  Json::Value rest = json_decode(json);
  ASSERT_EQ("bar", rest["foo"].asString());
  ASSERT_EQ(json, json_encode(rest));
}

TEST(tests_json, test_json_decode_to_any) {
  std::string json =
      R"({"bool":true,"foo":"bar","long":9223372036854775807,"map":{"foo":"bar"},"string":"string","vector":["foo","bar"]})";
  std::map<std::string, boost::any> m = {
      {"foo", boost::any("bar")},
      {"string", boost::any(std::string("string"))},
      {"long", boost::any(LONG_MAX)},
      {"bool", boost::any(true)},
      {"vector", boost::any(std::vector<boost::any>({{boost::any("foo")}}))},
      {"map", boost::any(std::map<std::string, boost::any>(
                  {{"foo", boost::any("bar")}}))}};
  std::stringstream ss(json);
  boost::property_tree::ptree pt;
  read_json(ss, pt);
  boost::any target = csugar::json_decode(pt);
  std::map<std::string, boost::any> data =
      boost::any_cast<std::map<std::string, boost::any>>(target);
  std::vector<boost::any> vec =
      boost::any_cast<std::vector<boost::any>>(data["vector"]);

  ASSERT_EQ(std::string("foo"), boost::any_cast<std::string>(vec[0]));
  ASSERT_EQ(std::string("bar"), boost::any_cast<std::string>(vec[1]));
  ASSERT_EQ(true, boost::any_cast<bool>(data["bool"]));
}

ext: cpp

max_stars_repo_name: AxiosCros/cpp-suger

max_issues_repo_name: AxiosCros/cpp-suger

max_forks_repo_name: AxiosCros/cpp-sugar


text:
#ifndef STAN_LANG_AST_FUN_IS_NIL_VIS_HPP
#define STAN_LANG_AST_FUN_IS_NIL_VIS_HPP

#include <boost/variant/static_visitor.hpp>

namespace stan {
namespace lang {

struct nil;
struct int_literal;
struct double_literal;
struct array_expr;
struct matrix_expr;
struct row_vector_expr;
struct variable;
struct fun;
struct integrate_1d;
struct integrate_ode;
struct integrate_ode_control;
struct algebra_solver;
struct algebra_solver_control;
struct map_rect;
struct index_op;
struct index_op_sliced;
struct conditional_op;
struct binary_op;
struct unary_op;

/**
 * Callback functor for determining if one of the variant types
 * making up an expression is nil.
 */
struct is_nil_vis : public boost::static_visitor<bool> {
  bool operator()(const nil& x) const;
  bool operator()(const int_literal& x) const;
  bool operator()(const double_literal& x) const;
  bool operator()(const array_expr& x) const;
  bool operator()(const matrix_expr& x) const;
  bool operator()(const row_vector_expr& x) const;
  bool operator()(const variable& x) const;
  bool operator()(const fun& x) const;
  bool operator()(const integrate_1d& x) const;
  bool operator()(const integrate_ode& x) const;
  bool operator()(const integrate_ode_control& x) const;
  bool operator()(const algebra_solver& x) const;
  bool operator()(const algebra_solver_control& x) const;
  bool operator()(const map_rect& x) const;
  bool operator()(const index_op& x) const;         // NOLINT(runtime/explicit)
  bool operator()(const index_op_sliced& x) const;  // NOLINT
  bool operator()(const conditional_op& x) const;   // NOLINT
  bool operator()(const binary_op& x) const;        // NOLINT(runtime/explicit)
  bool operator()(const unary_op& x) const;         // NOLINT(runtime/explicit)
};

}  // namespace lang
}  // namespace stan
#endif

max_stars_repo_name: ludkinm/stan

max_issues_repo_name: ludkinm/stan

max_forks_repo_name: ludkinm/stan


text:
#include <sys/time.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

#include "ros/ros.h"
#include "bosch_arm.h"
#include <kdl/frames.hpp>
#include "trajectory_controller3.h"
#include <bosch_arm_control/ArmState.h>
#include <bosch_arm_control/PointCmd.h>
#include <bosch_arm_control/Diagnostic.h>
#include "cc2.h"
#include <Eigen/Core>
#include<Eigen/Array>
#include <Eigen/LU>
#include <Eigen/QR>

using namespace std;
void TrajectoryController::singlePtCmdCallBack(const bosch_arm_control::PointCmd& msg)
{
  MoveAbsAction* a=new MoveAbsAction(msg.coordinates,this,msg.duration);
  act_que.push_back(a);
}

TrajectoryController::TrajectoryController(BoschArm *ptr)
{
  rob=ptr;
  diagnostic_pub =  n.advertise<bosch_arm_control::Diagnostic> ("/diagnostics",100);
  sigle_point_cmd_sub = n.subscribe("/joint_point_cmd",3, &TrajectoryController::singlePtCmdCallBack, this);
  joint_state_pub =  n.advertise<bosch_arm_control::ArmState> ("/joint_states",100);
  js.position.resize(4);
  js.velocity.resize(4);
  js.effort.resize(4);
  Kp[0]=10;
  Kp[1]=10;
  Kp[2]=20;
  Kp[3]=23;
//    for(int i=0;i<4;i++)
//      Kp[i]=Kp[i]*0.02;
  Kv[0]=0.20;
  Kv[1]=0.20;
  Kv[2]=0.24;
  Kv[3]=0.26;
//   for(int i=0;i<4;i++)
//     Kv[i]=0;
  joint_limit_low[0]=-1.7;
  joint_limit_high[0]=2.1;
  joint_limit_low[1]=-0.6;
  joint_limit_high[1]=0.55;
  joint_limit_low[2]=-2.5;
  joint_limit_high[2]=2.3;
  joint_limit_low[3]=-2.3;
  joint_limit_high[3]=2.4;

  tmax[0]=constants::t_max/constants::r1;
  tmax[1]=constants::t_max/constants::r2;
  tmax[2]=constants::t_max/constants::r2;
  tmax[3]=constants::t_max/constants::r2;

  vtime[0]=3000;
  vtime[1]=1500;
  vtime[2]=1500;
  vtime[3]=1500;

  vstep[0]=0.0001;
  vstep[1]=0.0002;
  vstep[2]=0.001;
  vstep[3]=0.001;

  dovstep=false;
  tvstep=0;
}

//calculate the frames given the joint values.
void TrajectoryController::updateKinematics()
{
  frm_cur[0]=frm_home[0];
  frm0[0]=frm_home[0];
  for (int i=1;i<=4;i++)
  {
    frm_cur[i].p=frm_home[i].p;
    frm_cur[i].M=frm_home[i].M*Rotation::RotZ(q[i-1]);
    frm0[i]=frm0[i-1]*frm_cur[i];
  }
  frm_cur[5]=frm_home[5];
  frm0[5]=frm0[4]*frm_cur[5];
  frmn[4]=frm_cur[5];
  Vector z(0,0,1);

  //jacobian[3](joint 4) = z4*p54
  for (int i=3;i>=0;i--)
  {
    frmn[i]=frm_cur[i+1]*frmn[i+1];
    jacobian[i]=z*frmn[i+1].p;
    jacobian[i]=frm0[i+1].M*jacobian[i];
  }
}

void TrajectoryController::start()
{
  rob->initialize();
  //L0,L3 are not available until rob is initialized.
  frm_home[0]=Frame::Identity();
  Rotation r(0,-1,0,
             0,0,-1,
             1,0,0);
  frm_home[1].M=r;
  frm_home[1].p=Vector(0,0,rob->L0);
  frm_home[2].M=r;
  frm_home[3].M=r;
  frm_home[4].M=r;
  frm_home[4].p=Vector(-rob->L5,0,rob->L3);
  frm_home[5].p=Vector(rob->L4,0,0);

  rob->motor2JointPosition(rob->q,q);

  for (int i=0;i<4;i++)
  {
    v[i]=0;
    dq[i]=0;
    f[i]=0;
    ql[i]=q[i];
    qd[i]=q[i];
    vd[i]=v[i];
  }
  for (int i=0;i<4;i++)
    gc[i]=Vector(constants::gravc[i*2],constants::gravc[i*2+1],0);
  //state=CALIBRATION;
  //state=LOADTRACE;
  state=SERVO;
  ctr_mode=GRAVITY;
  //ctr_mode=PDCONTROL;
  //ctr_mode=PDWITHGC;
  if (state==CALIBRATION)
  {
    genCalibTraj2();
    cur_act=act_que.front();
    cur_act->initialize();
    act_que.pop_front();
  }
  else if (state==LOADTRACE)
  {

    vector<double> des(4,0);
//     for(int i=0;i<4;i++)
//       des[i]=q[i];
//     des[1]=joint_limit_low[1];
//     des[3]=joint_limit_low[3]+0.1;
//     act_que.push_back(new MoveAbsAction(des,this));
//     des[1]=joint_limit_high[1];
    act_que.push_back(new MoveAbsAction(des,this));
    cur_act=act_que.front();
    cur_act->initialize();
    act_que.pop_front();

    //state=SERVO;

  }
}

void TrajectoryController::genCalibTraj2()
{
  vector<double> des(4,0);
//  int t=8000;
  //move the the zero position.
  act_que.push_back(new MoveAbsAction(des,this));
  des[0]=-1.5;
  des[1]=-0.5;
  des[2]=-2.2;
  des[3]=-1.7;
  cali1_act=new MoveAbsAction(des,this);
  calib1=new Calibration("calib1");
  cali1_act->calib=calib1;
  act_que.push_back(cali1_act);
  des[0]=0.7;
  des[1]=0;
  des[2]=0;
  des[3]=0;
  act_que.push_back(new MoveAbsAction(des,this));
  des[0]=-0.8;
  des[1]=-0.5;
  des[2]=-2.2;
  des[3]=-1.7;
  cali2_act=new MoveAbsAction(des,this);
  calib2=new Calibration("calib2");
  cali2_act->calib=calib2;
  act_que.push_back(cali2_act);

}

void TrajectoryController::calcGravityCompensation()
{
  for (int j=0;j<calib1->len_b;j++)
    if (calib1->count[j]>0&&calib2->count[j]>0)
    {
      calib1->b[j]-=calib2->b[j];
      calib1->count[j]=1;
    }

  for (int i=0;i<8;i++)
  {
    for (int j=0;j<calib1->len_b;j++)
    {
      if (calib1->count[j]>0)
      {
        calib1->A[i][j]-=calib2->A[i][j];
      }
    }
  }

  Eigen::MatrixXf AA(8,8);
  for (int i=0;i<8;i++)
  {
    for (int j=0;j<8;j++)
    {
      double s=0;
      for (int k=0;k<calib1->len_b;k++)
        if (calib1->count[k]>0)
          s+=calib1->A[i][k]*calib1->A[j][k];
      AA(i,j)=s/calib1->len_b;
    }
  }
  //cout<<AA;
  Eigen::VectorXf Ab(8);
  for (int i=0;i<8;i++)
  {
    double s=0;
    for (int j=0;j<calib1->len_b;j++)
      if (calib1->count[j]>0)
        s+=calib1->A[i][j]*calib1->b[j];
    Ab(i)=-s/calib1->len_b;
  }
  Eigen::MatrixXf M=AA.inverse()*Ab;
  //cout<<M<<endl;
  for (int i=0;i<4;i++)
  {
    gc[i]=Vector(M(i*2,0),M(i*2+1,0),0);
  }
  for (int i=0;i<4;i++)
  {
    for (int j=0;j<3;j++)
      cout<<gc[i][j]<<',';
    cout<<endl;
  }
}

// void TrajectoryController::vstep(int joint, double step)
// {
//   vector<double> des(4,0);
//   for (int i=0;i<4;i++)
//     des[i]=qd[i];
//   des[joint]+=step;
//   cur_act=new MoveAbsAction(des,this);
//   cur_act->initialize();
//
// }

void TrajectoryController::step(int joint, double step)
{

  for (int i=0;i<4;i++)
    qd[i]=q[i];
  qd[joint]+=step;

}

void TrajectoryController::update()
{
  rob->update();
  clock_gettime(CLOCK_REALTIME, &ts);
  //save the last joint position
  for (int i=0;i<4;i++)
    ql[i]=q[i];
  rob->motor2JointPosition(rob->q,q);
  rob->motor2JointVelocity(rob->v,v);

  if (state==CALIBRATION)
  {
    //update desired position
    if (cur_act->finished)
    {
      if (cur_act->calib==NULL)
        delete cur_act;

      if (act_que.size()==0)
      {
        calcGravityCompensation();
        state=SERVO;
        return;
      }
      cur_act=act_que.front();
      //cout<<cur_act->rel[3]<<endl;
      cur_act->initialize();
      act_que.pop_front();
    }
    cur_act->update();
    for (int i=0;i<4;i++)
    {
      qd[i]=cur_act->cmd.coordinates[i];
      vd[i]=cur_act->cmd.velocity[i];

    }
    //update torque command
    PDControl();

    logging();
  }
  else if (state==LOADTRACE)
  {
    if (cur_act->finished)
    {
      if (cur_act->calib==NULL)
        delete cur_act;

      if (act_que.size()==0)
      {
        //calcGravityCompensation();
        state=SERVO;
        return;
      }

      cur_act=act_que.front();
      //cout<<cur_act->rel[3]<<endl;
      cur_act->initialize();
      act_que.pop_front();

    }
    cur_act->update();
    for (int i=0;i<4;i++)
    {
      qd[i]=cur_act->cmd.coordinates[i];
      vd[i]=cur_act->cmd.velocity[i];

    }
    //update torque command
    //PDWithGC();
    PDControl();
    logging();
  }
  else if (state==SERVO)
  {
    if (cur_act!=NULL)
    {
      if (cur_act->finished)
      {
        if (cur_act->calib==NULL)
        {
          delete cur_act;
          cur_act=NULL;
        }

//         if (act_que.size()!=0)
//         {
//           cur_act=act_que.front();
//           cur_act->initialize();
//           act_que.pop_front();
//         }

      }
      else
      {
        cur_act->update();
        for (int i=0;i<4;i++)
        {
          qd[i]=cur_act->cmd.coordinates[i];
          vd[i]=cur_act->cmd.velocity[i];

        }
      }
    }
    if(dovstep)
    {
      if(tvstep==2*vtime[jid])
        tvstep=0;
      if(tvstep<vtime[jid]/2)
      {
        qd[jid]+=vstep[jid];
        vd[jid]=vstep[jid];
      }
      else if(tvstep<vtime[jid]/2+vtime[jid])
      {
        qd[jid]-=vstep[jid];
        vd[jid]=-vstep[jid];
      }
      else
      {
        qd[jid]+=vstep[jid];
        vd[jid]=vstep[jid];
      }
      tvstep++;
    }
    //PDControl();
    if (ctr_mode==PDWITHGC)
      PDWithGC();
    else if (ctr_mode==PDCONTROL)
      PDControl();
    else if (ctr_mode==GRAVITY)
      gravity_compensation();
    else if (ctr_mode==NOCONTROL)
    {
      for (int i=0;i<4;i++)
        rob->torque[i]=0;
    }
    //floating();
    //gravity_compensation();
    logging();
  }
}

void TrajectoryController::gravity_compensation()
{

  updateKinematics();
  //T=sum(gcj) dot (g*Zi
  Vector g(0,0,-1);
  //double tq[4];
  for (int i=0;i<4;i++)
  {
    Vector Zi=frm0[i+1].M.UnitZ();
    f[i]=0;
    for (int j=i;j<4;j++)
    {
      Rotation R0j=frm0[j+1].M.Inverse();
      Vector tmp=R0j*(g*Zi);
      f[i]-=dot(gc[j],tmp);
    }
  }

  for (int i=0;i<4;i++)
  {
    torque[i]=0;
    for (int j=0;j<4;j++)
    {
      torque[i]+=rob->m2j[4*j+i]*f[j];

    }

  }
  for (int i=0;i<4;i++)
    rob->torque[i]=torque[i];
  //logging();

}

void TrajectoryController::PDWithGC()
{
  updateKinematics();
  for (int i=0;i<4;i++)
  {

    dq[i]=qd[i]-q[i];
    f[i]=Kp[i]*dq[i]-Kv[i]*(v[i]-vd[i]);
  }

  //T=sum(gcj) dot (g*Zi
  Vector g(0,0,-1);
  //double tq[4];
  for (int i=0;i<4;i++)
  {
    Vector Zi=frm0[i+1].M.UnitZ();
    for (int j=i;j<4;j++)
    {
      Rotation R0j=frm0[j+1].M.Inverse();
      Vector tmp=R0j*(g*Zi);
      f[i]-=dot(gc[j],tmp);
    }
  }
  for (int i=0;i<4;i++)
  {
    torque[i]=0;
    for (int j=0;j<4;j++)
    {
      torque[i]+=rob->m2j[4*j+i]*f[j];

    }

  }
  for (int i=0;i<4;i++)
    rob->torque[i]=torque[i];
  //logging();
}

void TrajectoryController::PDControl()
{
  for (int i=0;i<4;i++)
  {

    dq[i]=qd[i]-q[i];
    f[i]=Kp[i]*dq[i]-Kv[i]*(v[i]-vd[i]);
  }
  for (int i=0;i<4;i++)
  {
    torque[i]=0;
    for (int j=0;j<4;j++)
    {
      torque[i]+=rob->m2j[4*j+i]*f[j];

    }

  }
  for (int i=0;i<4;i++)
    rob->torque[i]=torque[i];
  //logging();
}

void TrajectoryController::logging()
{
  std::string log;
  std::stringstream out;
  for (int i=0;i<4;i++)
    out<<q[i]<<",";
  for (int i=0;i<4;i++)
    out<<qd[i]<<",";
  for (int i=0;i<4;i++)
    out<<v[i]<<",";
  for (int i=0;i<4;i++)
    out<<f[i]<<",";
  for (int i=0;i<4;i++)
    out<<(q[i]-qd[i])<<",";
  for (int i=0;i<4;i++)
    out<<rob->q[i]<<',';
  for (int i=0;i<4;i++)
    out<<rob->v[i]<<',';
  for (int i=0;i<4;i++)
    out<<rob->torque[i]<<',';
  out << ts.tv_sec << ','<< ts.tv_nsec;
  log = out.str();
  diag.data=log;
  diag.header.stamp.sec=ts.tv_sec;
  diag.header.stamp.nsec=ts.tv_nsec;
  diagnostic_pub.publish(diag);
  //vector<double> cur_pos_act(q,q+4);
  js.header.stamp.sec=ts.tv_sec;
  js.header.stamp.nsec=ts.tv_nsec;
  //js.position=cur_pos_act;

  for (int i=0;i<4;i++)
  {
    js.position[i]=q[i];
    js.velocity[i]=v[i];
    js.effort[i]=f[i];
  }
  joint_state_pub.publish(js);
}
void TrajectoryController::stop()
{
  rob->close();
}

max_issues_repo_name: salisbury-robotics/jks-ros-pkg

max_forks_repo_name: salisbury-robotics/jks-ros-pkg


text:
#include "libs/model_prediction/prediction_flow.h"
#include "libs/model_prediction/prediction_row.h"
#include "utils/missing_values.hpp"
#include "logging.h"
#include <boost/variant.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <iostream>
#include <sstream>

namespace prediction
{

namespace
{

struct run_prediction :
    boost::static_visitor<apply_model::result_type>
{
    run_prediction(const predicate& p) :
        predictor{p}
    {
    }

    apply_model::result_type operator () (const output& o) const
    {
        return o;
    }

    apply_model::result_type operator () (const row& r) const
    {
        LOG_DEBUG<<"running prediction for row "<<index(r);
        return preform_action(predictor, r);
    }

private:
    const predicate& predictor;
};

struct normalized_data :
    boost::static_visitor<normalized::result_type>

{
    normalized_data(const normalized::action_list& al) :
        actions{al}
    {
    }

    normalized::result_type operator () (const output& o) const
    {
        return normalized::result_type{o};
    }

    normalized::result_type operator () (row r) const
    {
        row result{r};
        LOG_DEBUG<<"normalizing data for row "<<index(r);
        for (const auto& act : actions) {
            auto corret_val = preform_action(act, r);
            r[column(act).value] = corret_val;
        }
        return normalized::result_type{std::move(r)};
    }

    const normalized::action_list& actions;
};

///////////////////////////////////////////////////////////////////////////////
//
struct fix_missing_vals :
    boost::static_visitor<verify_fix::result_type>
{
    fix_missing_vals(const verify_fix::actions_list& al) :
        actions{al}
    {
    }

    verify_fix::result_type operator () (output o) const
    {
        return verify_fix::result_type{o};
    }

    verify_fix::result_type operator () (row r) const
    {
        column_number from{0}, to = (column_number)r.size();
        while (from != to) {
            from = find(r, from, to);
            if (from != to) {
                LOG_DEBUG<<"need to fix invalid entry for row "<<index(r);
                auto f = match_column(from);
                if (f == actions.end()) {   // we don't have a fix for it
                    LOG_INFO<<"no fixing action for row "<<index(r)<<" this would be removed";
                    return verify_fix::result_type{output{index(r), status::REMOVED}};
                } else {
                    LOG_INFO<<"fixing invalid value for row "<<index(r);
                    replace(r, *f);
                }
            }
        }
        return verify_fix::result_type{std::move(r)};
    }

private:
    using iterator = verify_fix::actions_list::const_iterator;

    column_number find(const row& r, column_number start, column_number end) const
    {
        boost::counting_iterator<column_number::value_type> from{start.value},
                                                            to{end.value};
        //for (; start != end; ++start) {
        auto i = std::find_if(from, to, [&r](auto col) {
                    return missing_value(r[col]);
                }
            );
        return i == to ? end : column_number{*i};
    }

    iterator match_column(column_number at) const
    {
        return std::find_if(std::begin(actions), std::end(actions), [at](const auto& act) {
                                return act.column == at;
                        }
                );
    }

    const verify_fix::actions_list& actions;
};

}   // end of local namespace

///////////////////////////////////////////////////////////////////////////////
//
void verify_fix::assign(const actions_list::value_type act)
{
    actions.push_back(std::move(act));
}

void normalized::assign(action_list::value_type new_entry)
{
    actions.push_back(std::move(new_entry));
}

verify_fix::result_type verify_fix::operator () (arg_type input) const
{
    input = boost::apply_visitor(fix_missing_vals{actions}, input.value);
    return input;
}

std::ostream& operator << (std::ostream& os, const verify_fix& vf)
{
    return vf.stream(os);
}

std::ostream& verify_fix::stream(std::ostream& os) const
{
    os<<"fix missing actions ";
    if (actions.empty()) {
        return os<<"no actions";
    } else {
        std::copy(std::begin(actions), std::end(actions), std::ostream_iterator<actions_list::value_type>(os, "\n"));
        return os;
    }
}

std::string to_string(const verify_fix& vf)
{
    std::stringstream sp;
    sp<<vf;
    return sp.str();
}

verify_fix::result_type apply(const verify_fix& fix, verify_fix::arg_type what)
{
    return fix(what);
}

///////////////////////////////////////////////////////////////////////////////
//
normalized::result_type normalized::operator () (arg_type arg) const
{
    return boost::apply_visitor(normalized_data{actions}, arg.value);
}

std::ostream& normalized::stream(std::ostream& os) const
{
    os<<"normalized actions:\n";
    for (const auto& ac : actions) {
        os<<"action: "<<ac<<"\n";
    }
    return os;
}

std::string to_string(const normalized& n)
{
    std::ostringstream p;
    p<<n;
    return p.str();
}

std::ostream& operator << (std::ostream& os, const normalized& n)
{
    return n.stream(os);
}

normalized::result_type norm(const normalized& with, const normalized::arg_type& what)
{
    return with(what);
}

///////////////////////////////////////////////////////////////////////////////
//
read_row::result_type read_row::operator()(arg_type& input) const
{
    try {
        auto r = read(input, input_layout);
        if (r.empty()) {
            return result_type{output{invalid_row(), status::END_OF_FILE}};
        } else {
            return result_type{r};
        }
    } catch (const std::runtime_error& e) {
        LOG_ERROR<<"error while trying to read row from input: '"<<e.what()<<"'";
        return result_type{output{invalid_row(), status::INVALID}};
    }
}

read_row::result_type read(const read_row& with,
                        read_row::arg_type& input)
{
    return with(input);
}

read_row::read_row(const schema_mapper& sc) : input_layout{sc}
{
}

///////////////////////////////////////////////////////////////////////////////

apply_model::result_type predict(const apply_model& with, const apply_model::arg_type& on)
{
    return with(on);
}

apply_model::apply_model(predicate p) : predictor{std::move(p)}
{
}

apply_model::result_type apply_model::operator () (const arg_type& arg) const
{
    run_prediction r{predictor};
    return boost::apply_visitor(r, arg.value);
}

std::ostream& operator << (std::ostream& os, const apply_model& am)
{
    return am.stream(os);
}

std::ostream& apply_model::stream(std::ostream& os) const
{
    return os<<"apply model action "<<predictor;
}

///////////////////////////////////////////////////////////////////////////////

load_model::result_type load_model::operator () (const arg_type& arg) const
{
    return preform_action(action, arg);
}

std::ostream& load_model::stream(std::ostream& os) const
{
    return os<<"load model: "<<action;
}
load_model::result_type
    load(const load_model& lm, const load_model::arg_type& arg)
{
    return lm(arg);
}

std::ostream& operator << (std::ostream& os, const load_model& lm)
{
    return lm.stream(os);
}

std::string to_string(const load_model& lm)
{
    std::ostringstream p;
    p<<lm;
    return p.str();
}

std::ostream& operator << (std::ostream& os, const read_row&)
{
    return os<<"read operation";
}
}   // end of namespace predition


text:
#include "rodsClient.h"
#include "reFuncDefs.hpp"
#include "rods.h"
#include "reGlobalsExtern.hpp"
#include "rsGlobalExtern.hpp"
#include "rcGlobalExtern.h"

#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <string>
#include "irods_server_properties.hpp"

extern "C" {
    static
    int connectToRemoteiRODS(
        char*      inStr,
        rcComm_t** rcComm ) {
        rErrMsg_t errMsg;

        /*inStr of form: //irods:host[:port][:user[@zone][:pass]]/remotePath
          if port is not given default port 1247 is used
          if user@zone is not given ANONYMOUS_USER is used
          if pass is not given ANONYMOUS_USER is used
        */
        const std::string input( inStr );
        boost::smatch matches;
        boost::regex expression( "irods:([^:/]+)(:([0-9]+))?"           // irods:host[:port]
                                 "(:([^:/@]+)(@([^:/]+))?(:([^/]+))?)?" // [:user[@zone][:pass]]
                                 "/(.*)" );                             // /remotePath
        try {
            const bool matched = boost::regex_match( input, matches, expression );
            if ( !matched ) {
                return USER_INPUT_FORMAT_ERR;
            }
            std::string host = matches.str( 1 );
            int port = 1247;
            if ( !matches.str( 3 ).empty() ) {
                port = boost::lexical_cast<int>( matches.str( 3 ) );
            }
            std::string user( ANONYMOUS_USER );
            if ( !matches.str( 5 ).empty() ) {
                user = matches.str( 5 );
            }
            std::string zone = matches.str( 7 );
            printf( "MM: host=%s,port=%i,user=%s\n", host.c_str(), port, user.c_str() );
            *rcComm = rcConnect( host.c_str(), port, user.c_str(), zone.c_str(), 0, &errMsg );
            if ( *rcComm == NULL ) {
                return REMOTE_IRODS_CONNECT_ERR;
            }
            int status = clientLogin( *rcComm );
            if ( status != 0 ) {
                rcDisconnect( *rcComm );
            }
            return status;
        }
        catch ( const boost::bad_lexical_cast& ) {
            return INVALID_LEXICAL_CAST;
        }
        catch ( const boost::exception& ) {
            return SYS_INTERNAL_ERR;
        }

    }

    /**
     * \fn msiobjget_irods(msParam_t*  inRequestPath, msParam_t* inFileMode, msParam_t* inFileFlags, msParam_t* inCacheFilename,  ruleExecInfo_t* rei )
     *
     * \brief Gets an iRODS object
     *
     * \module msoDrivers_irods
     *
     * \since 3.0
     *
     *
     * \usage See clients/icommands/test/rules/
     *
     * \param[in] inRequestPath - a STR_MS_T request string to external resource
     * \param[in] inFileMode - a STR_MS_T mode of cache file creation
     * \param[in] inFileFlags - a STR_MS_T flags for cache file creation
     * \param[in] inCacheFilename - a STR_MS_T cache file name (full path)
     * \param[in,out] rei - The RuleExecInfo structure that is automatically
     *    handled by the rule engine. The user does not include rei as a
     *    parameter in the rule invocation.
     *
     * \DolVarDependence none
     * \DolVarModified none
     * \iCatAttrDependence none
     * \iCatAttrModified none
     * \sideeffect none
     *
     * \return integer
     * \retval 0 on success
     * \pre none
     * \post none
     * \sa none
    **/

    int msiobjget_irods(
        msParam_t* inRequestPath,
        msParam_t* inFileMode,
        msParam_t* inFileFlags,
        msParam_t* inCacheFilename,
        ruleExecInfo_t* rei ) {

        char *locStr;
        int mode;
        char *cacheFilename;
        char *str, *t;
        int status, bytesRead, bytesWritten;
        int destFd, i;
        rcComm_t *rcComm = NULL;

        dataObjInp_t dataObjInp;
        int objFD;
        openedDataObjInp_t dataObjReadInp;
        openedDataObjInp_t dataObjCloseInp;
        bytesBuf_t readBuf;

        RE_TEST_MACRO( "    Calling msiobjget_irods" );

        /*  check for input parameters */
        if ( inRequestPath ==  NULL ||
                strcmp( inRequestPath->type , STR_MS_T ) != 0 ||
                inRequestPath->inOutStruct == NULL ) {
            return USER_PARAM_TYPE_ERR;
        }

        if ( inFileMode ==  NULL ||
                strcmp( inFileMode->type , STR_MS_T ) != 0 ||
                inFileMode->inOutStruct == NULL ) {
            return USER_PARAM_TYPE_ERR;
        }

        if ( inFileFlags ==  NULL ||
                strcmp( inFileFlags->type , STR_MS_T ) != 0 ||
                inFileFlags->inOutStruct == NULL ) {
            return USER_PARAM_TYPE_ERR;
        }

        if ( inCacheFilename ==  NULL ||
                strcmp( inCacheFilename->type , STR_MS_T ) != 0 ||
                inCacheFilename->inOutStruct == NULL ) {
            return USER_PARAM_TYPE_ERR;
        }

        /*  coerce input to local variables */
        str = strdup( ( char * ) inRequestPath->inOutStruct );
        if ( ( t = strstr( str, ":" ) ) != NULL ) {
            locStr = t + 1;
            if ( ( t = strstr( locStr, "/" ) ) != NULL ) {
                locStr = t;
            }
            else {
                free( str );
                return USER_INPUT_FORMAT_ERR;
            }
        }

        else {
            free( str );
            return USER_INPUT_FORMAT_ERR;
        }

        cacheFilename = ( char * ) inCacheFilename->inOutStruct;
        mode  = atoi( ( char * ) inFileMode->inOutStruct );

        /* Do the processing */

        i = connectToRemoteiRODS( ( char * ) inRequestPath->inOutStruct, &rcComm );
        if ( i < 0 ) {
            printf( "msiputobj_irods: error connecting to remote iRODS: %s:%i\n",
                    ( char * ) inRequestPath->inOutStruct, i );
            free( str );
            return i;
        }

        bzero( &dataObjInp, sizeof( dataObjInp ) );
        bzero( &dataObjReadInp, sizeof( dataObjReadInp ) );
        bzero( &dataObjCloseInp, sizeof( dataObjCloseInp ) );
        bzero( &readBuf, sizeof( readBuf ) );

        dataObjInp.openFlags = O_RDONLY;
        rstrcpy( dataObjInp.objPath, locStr, MAX_NAME_LEN );
        free( str );

        objFD = rcDataObjOpen( rcComm, &dataObjInp );
        if ( objFD < 0 ) {
            printf( "msigetobj_irods: Unable to open file %s:%i\n", dataObjInp.objPath, objFD );
            rcDisconnect( rcComm );
            return objFD;
        }

        destFd = open( cacheFilename, O_WRONLY | O_CREAT | O_TRUNC, mode );
        if ( destFd < 0 ) {
            status = UNIX_FILE_OPEN_ERR - errno;
            printf(
                "msigetobj_irods: open error for cacheFilename %s, status = %d",
                cacheFilename, status );
            rcDisconnect( rcComm );
            return status;
        }

        dataObjReadInp.l1descInx = objFD;
        dataObjCloseInp.l1descInx = objFD;

        int single_buff_sz = 0;
        irods::error ret = irods::get_advanced_setting<int>(
                               irods::CFG_MAX_SIZE_FOR_SINGLE_BUFFER,
                               single_buff_sz );
        if ( !ret.ok() ) {
            irods::log( PASS( ret ) );
            close( destFd );
            return ret.code();
        }
        single_buff_sz *= 1024 * 1024;
        readBuf.len = single_buff_sz;
        readBuf.buf = ( char * )malloc( readBuf.len );
        dataObjReadInp.len = readBuf.len;

        while ( ( bytesRead = rcDataObjRead( rcComm, &dataObjReadInp, &readBuf ) ) > 0 ) {
            bytesWritten = write( destFd, readBuf.buf, bytesRead );
            if ( bytesWritten != bytesRead ) {
                free( readBuf.buf );
                close( destFd );
                rcDataObjClose( rcComm, &dataObjCloseInp );
                rcDisconnect( rcComm );
                printf(
                    "msigetobj_irods: In Cache File %s bytesWritten %d != returned objLen %i\n",
                    cacheFilename, bytesWritten, bytesRead );
                return SYS_COPY_LEN_ERR;
            }
        }
        free( readBuf.buf );
        close( destFd );
        i = rcDataObjClose( rcComm, &dataObjCloseInp );
        rcDisconnect( rcComm );
        return i;

    }

    // =-=-=-=-=-=-=-
    // plugin factory
    irods::ms_table_entry*  plugin_factory( ) {
        // =-=-=-=-=-=-=-
        // instantiate a new msvc plugin
        irods::ms_table_entry* msvc = new irods::ms_table_entry( 4 );

        // =-=-=-=-=-=-=-
        // wire the implementation to the plugin instance
        msvc->add_operation( "msiobjget_irods", "msiobjget_irods" );

        // =-=-=-=-=-=-=-
        // hand it over to the system
        return msvc;

    } // plugin_factory

} // extern "C"

max_stars_repo_name: cyverse/irods

max_issues_repo_name: cyverse/irods

max_forks_repo_name: benlazarine/irods


text:
/*
 * Copyright (C) 2005-2012, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file liburbi/uclient.cc

#if !defined WIN32
# include <libport/ctime>
# include <libport/csignal>
#endif

#include <boost/lambda/bind.hpp>

#include <libport/boost-error.hh>
#include <libport/format.hh>

#include <urbi/uclient.hh>
#include <urbi/utag.hh>

#include <liburbi/compatibility.hh>

GD_CATEGORY(Urbi.Client);

namespace urbi
{

  /*-------------------.
  | UClient::options.  |
  `-------------------*/

  UClient::options::options(bool server)
    : server_(server)
      // Unless stated otherwise, auto start.
    , start_(true)
    , asynchronous_(false)
  {
  }

  UCLIENT_OPTION_IMPL(UClient, bool, server)
  UCLIENT_OPTION_IMPL(UClient, bool, start)
  UCLIENT_OPTION_IMPL(UClient, bool, asynchronous)

  /*----------.
  | UClient.  |
  `----------*/

  UClient::UClient(const std::string& host, unsigned port,
                   size_t buflen,
                   const options& opt)
    : UAbstractClient(host, port, buflen, opt.server())
    , ping_interval_(0)
    , pong_timeout_(0)
    , link_(new UClient*(this))
    , ping_sent_(libport::utime())
    , ping_sem_(0)
    , asynchronous_(opt.asynchronous())
    , synchronous_send_(false)
  {
    if (opt.start())
      start();
  }

  UClient::error_type
  UClient::start()
  {
    return rc = server_ ? listen_() : connect_();
  }

  UClient::error_type
  UClient::connect_()
  {
    if (boost::system::error_code erc = connect(host_, port_, false, 0,
                                                asynchronous_))
    {
      libport::boost_error(libport::format("UClient::UClient connect(%s, %s)",
                                           host_, port_),
                           erc);
      return -1;
    }
    else
      return 0;
  }

  UClient::error_type
  UClient::listen_()
  {
    if (boost::system::error_code erc =
        listen(boost::bind(&UClient::mySocketFactory, this), host_, port_))
    {
      libport::boost_error(libport::format("UClient::UClient listen(%s, %s)",
                                           host_, port_),
                           erc);
      return -1;
    }
    else
      return 0;
  }

  UClient::~UClient()
  {
    *link_ = 0;
    closeUClient();
  }

  UClient::error_type
  UClient::onClose()
  {
    if (!closed_)
      UAbstractClient::onClose();
    return !!closed_;
  }

  UClient::error_type
  UClient::closeUClient()
  {
    close();
    onClose();
    return 0;
  }

  UClient::error_type
  UClient::effectiveSend(const void* buffer, size_t size)
  {
    if (rc)
      return -1;
    if (synchronous_send_)
      libport::Socket::syncWrite(buffer, size);
    else
      libport::Socket::write(buffer, size);
    return 0;
  }

  libport::Socket*
  UClient::mySocketFactory()
  {
    return this;
  }

  void
  UClient::onConnect()
  {
    init_ = true;
    onConnection();

    // Declare ping channel for kernel that requires it.  Do not try
    // to depend on kernelMajor, because it has not been computed yet.
    // And computing kernelMajor requires this code to be run.  So we
    // need to write something that both k1 and k2 will like.
    send(SYNCLINE_WRAP(
           "var lobby.%s = Channel.new(\"%s\")|;",
           internalPongTag(), internalPongTag()));
    // The folowwing calls may fail if we got disconnected.
    try
    {
      host_ = getRemoteHost();
      port_ = getRemotePort();
    }
    catch (const std::exception& e)
    {
      // Ignore the error, next read attempt will trigger onError.
      GD_FINFO_DUMP("ignore std::exception: %s", e.what());
    }
    if (ping_interval_)
      sendPing(link_);
  }

  void
  UClient::onError(boost::system::error_code erc)
  {
    rc = -1;
    resetAsyncCalls_();
    clientError("!!! " + erc.message());
    notifyCallbacks(UMessage(*this, 0, CLIENTERROR_TAG,
                             "!!! " + erc.message()));
    return;
  }

  size_t
  UClient::onRead(const void* data, size_t length)
  {
    size_t capacity = recvBufSize - recvBufferPosition - 1;

    if (ping_interval_ && ping_sem_.uget(1))
    {
      pong_timeout_handler_->cancel();
      send_ping_handler_ =
        libport::asyncCall(boost::bind(&UClient::sendPing,
                                       this, link_),
                           ping_interval_ - (libport::utime() - ping_sent_));
    }
    if (capacity < length)
    {
      size_t nsz = std::max(recvBufSize*2, recvBufferPosition + length+1);
      char* nbuf = new char[nsz];
      memcpy(nbuf, recvBuffer, recvBufferPosition);
      delete[] recvBuffer;
      recvBuffer = nbuf;
      recvBufSize = nsz;
    }
    memcpy(&recvBuffer[recvBufferPosition], data, length);
    recvBufferPosition += length;
    recvBuffer[recvBufferPosition] = 0;
    processRecvBuffer();
    return length;
  }

  void
  UClient::pongTimeout(link_type l)
  {
    if (*l)
    {
      const char* err = "!!! Lost connection with server: ping timeout";
      // FIXME: Choose between two differents way to alert user program.
      clientError(err);
      notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag(), err));
      close();
    }
  }

  void
  UClient::sendPing(link_type l)
  {
    if (*l)
    {
      pong_timeout_handler_ =
        libport::asyncCall(boost::bind(&UClient::pongTimeout, this, link_),
                           pong_timeout_);
      send("%s << 1,", internalPongTag());
      ping_sent_ = libport::utime();
      ping_sem_++;
    }
  }

  void
  UClient::printf(const char * format, ...)
  {
    va_list arg;
    va_start(arg, format);
    vfprintf(stderr, format, arg);
    va_end(arg);
  }

  unsigned int UClient::getCurrentTime() const
  {
  // FIXME: Put this into libport.
#ifdef WIN32
    return GetTickCount();
#else
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec*1000+tv.tv_usec/1000;
#endif
  }

  void
  UClient::setKeepAliveCheck(unsigned ping_interval,
                             unsigned pong_timeout)
  {
    // Always interrupt previous ping handler.
    resetAsyncCalls_();
    // From milliseconds to microseconds.
    ping_interval_ = ping_interval * 1000;
    pong_timeout_  = pong_timeout * 1000;
    if (ping_interval_)
      sendPing(link_);
  }

  void
  UClient::resetAsyncCalls_()
  {
    if (pong_timeout_handler_)
    {
      pong_timeout_handler_->cancel();
      pong_timeout_handler_.reset();
    }
    if (send_ping_handler_)
    {
      send_ping_handler_->cancel();
      send_ping_handler_.reset();
    }
  }

  void
  UClient::waitForKernelVersion() const
  {
    // FIXME: use a condition.
    while (kernelMajor_ < 0 && !error())
      sleep(100000);
  }

  void
  UClient::setSynchronousSend(bool enable)
  {
    synchronous_send_ = enable;
  }

} // namespace urbi

ext: cc

max_stars_repo_name: jcbaillie/urbi

max_issues_repo_name: jcbaillie/urbi

max_forks_repo_name: jcbaillie/urbi


text:
#include "timetable/timetable.hpp"
#include "algorithm/ranges.hpp"
#include "gtfs/dataset.hpp"
#include "gtfs/stop.hpp"
#include "gtfs/transfer.hpp" // for Transfer
#include "gtfs/trip.hpp"     // for Trip
#include "id/route.hpp"
#include "id/trip.hpp"
#include "search/coordinate_to_stop.hpp"
#include "timetable/line_table.hpp" // for LineTable
#include "timetable/line_table_factory.hpp"
#include "timetable/station_table.hpp" // for StationTable
#include "timetable/station_table_factory.hpp"
#include "timetable/timetable_factory.hpp"
#include "timetable/transfer_table.hpp" // for TransferTable
#include "timetable/transfer_table_factory.hpp"

#include <algorithm>          // for stable_sort, for...
#include <boost/assert.hpp>   // for BOOST_ASSERT
#include <boost/optional.hpp> // for optional
#include <iterator>
#include <tuple>
#include <unordered_map>
#include <utility>

namespace nepomuk
{
namespace geometric
{
class WGS84Coordinate;
}
}
namespace nepomuk
{
struct ShapeID;
}
namespace nepomuk
{
struct StopID;
}

namespace nepomuk
{
struct ShapeID;
struct StopID;
namespace geometric
{
class WGS84Coordinate;
}

namespace timetable
{

namespace
{

// template to produce items based on equal ranges in a sorted order
template <typename factory,
          typename result_type,
          typename input_type,
          typename sorting_predicate,
          typename grouping_predicate>
void produceByEqualRanges(std::vector<result_type> &output,
                          std::vector<input_type> &input,
                          sorting_predicate sort_by,
                          grouping_predicate group_by)
{
    BOOST_ASSERT(input.begin() != input.end());
    // ensure correct ordering.
    std::stable_sort(input.begin(), input.end(), sort_by);

    using InputIter = typename std::vector<input_type>::iterator;
    using InputIterRange = std::pair<InputIter, InputIter>;

    const auto output_inserter = [&output](InputIterRange const range) {
        output.push_back(factory::produce(range.first, range.second));
    };

    algorithm::by_equal_ranges(input.begin(), input.end(), group_by, output_inserter);
}

template <typename factory,
          typename result_type,
          typename input_type,
          typename sorting_predicate,
          typename grouping_predicate>
void produceByEqualRangesVector(std::vector<result_type> &output,
                                std::vector<input_type> &input,
                                sorting_predicate sort_by,
                                grouping_predicate group_by)
{
    BOOST_ASSERT(input.begin() != input.end());
    // ensure correct ordering.
    std::stable_sort(input.begin(), input.end(), sort_by);

    using InputIter = typename std::vector<input_type>::iterator;
    using InputIterRange = std::pair<InputIter, InputIter>;

    const auto output_inserter = [&output](InputIterRange const range) {
        auto result_range = factory::produce(range.first, range.second);
        for (auto itr = result_range.begin(); itr != result_range.end(); ++itr)
            output.push_back(std::move(*itr));
    };

    algorithm::by_equal_ranges(input.begin(), input.end(), group_by, output_inserter);
}

template <typename factory_type,
          typename result_type,
          typename input_type,
          typename sorting_predicate,
          typename grouping_predicate>
void produceByEqualRangesVector(std::vector<result_type> &output,
                                std::vector<input_type> &input,
                                sorting_predicate sort_by,
                                grouping_predicate group_by,
                                factory_type &factory)
{
    BOOST_ASSERT(input.begin() != input.end());
    // ensure correct ordering.
    std::stable_sort(input.begin(), input.end(), sort_by);

    using InputIter = typename std::vector<input_type>::iterator;
    using InputIterRange = std::pair<InputIter, InputIter>;

    const auto output_inserter = [&output, &factory](InputIterRange const range) {
        auto result_range = factory.produce(range.first, range.second);
        for (auto itr = result_range.begin(); itr != result_range.end(); ++itr)
            output.push_back(std::move(*itr));
    };

    algorithm::by_equal_ranges(input.begin(), input.end(), group_by, output_inserter);
}

} // namespace

TimeTable TimeTableFactory::produce(gtfs::Dataset &dataset,
                                    std::vector<std::size_t> &trip_offsets_by_line)
{
    TimeTable result;

    // prepare routes for trips
    std::unordered_map<TripID, RouteID> route_id_by_trip;
    auto const add_trip_route_mapping = [&route_id_by_trip](auto const &trip) {
        route_id_by_trip[trip.id] = trip.route_id;
    };
    std::for_each(dataset.trips.begin(), dataset.trips.end(), add_trip_route_mapping);

    {
        if (!dataset.transfers)
            dataset.transfers = std::vector<gtfs::Transfer>();

        LineTableFactory factory(*dataset.transfers, trip_offsets_by_line);
        produceByEqualRangesVector(
            result.line_tables,
            dataset.stop_times,
            [&route_id_by_trip](auto const &lhs, auto const &rhs) {
                // group all trips by their route-id, their trip id, their sequence id
                return std::tie(route_id_by_trip.find(lhs.trip_id)->second,
                                lhs.trip_id,
                                lhs.sequence_id) <
                       std::tie(route_id_by_trip.find(rhs.trip_id)->second,
                                rhs.trip_id,
                                rhs.sequence_id);
            },
            // process elements by their trip id
            [&route_id_by_trip](gtfs::StopTime const &value, gtfs::StopTime const &candidate) {
                return route_id_by_trip.find(value.trip_id)->second <
                       route_id_by_trip.find(candidate.trip_id)->second;
            },
            factory);
    }

    result.station_table = StationTableFactory::produce(dataset.stops.begin(), dataset.stops.end());

    if (dataset.transfers)
    {
        std::vector<std::pair<geometric::WGS84Coordinate, StopID>> locations;
        locations.reserve(dataset.stops.size());
        std::transform(dataset.stops.begin(),
                       dataset.stops.end(),
                       std::back_inserter(locations),
                       [](auto const &stop) { return std::make_pair(stop.location, stop.id); });
        auto const stop_lookup = search::CoordinateToStop(locations);
        // sorts internally
        result.transfer_table = TransferTableFactory::produce(dataset.transfers->begin(),
                                                              dataset.transfers->end(),
                                                              dataset.stops.size(),
                                                              result.line_tables,
                                                              dataset.stops,
                                                              stop_lookup);
    }
    return result;
}

} // namespace timetable
} // namespace nepomuk

max_stars_repo_name: mapbox/nepomuk

max_issues_repo_name: mapbox/nepomuk

max_forks_repo_name: mapbox/nepomuk


text:
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm

#pragma once

#include "libvideostitch/quaternion.hpp"

#include <Eigen/Dense>

#include <vector>

namespace VideoStitch {

namespace Stabilization {

typedef Eigen::Matrix<double, 9, 1> Vector9d;

/**
 * @brief The UKF_Quaternion class
 *
 * Inspired by: A Quaternion-Based Unscented Kalman Filter for Orientation Tracking (Edgar Kraft)
 */
class UKF_Quaternion {
 public:
  UKF_Quaternion();
  /**
   * @brief Propagate current state in time
   * @param delta_t : time in seconds
   */
  void predict(double delta_t);

  /**
   * @brief Incorporate a new measurement, update state and covariance matrix
   * @param v : 9 dimensional vector (gyr_xyz, acc_xyz, mag_xyz)
   */
  void measure(const Vector9d& v);

  Quaternion<double> getCurrentOrientation() const;
  Vector3<double> getCurrentAngularVelocity() const;
  Vector3<double> getCurrentAngularAcceleration() const;
  Eigen::Matrix<double, 9, 9> getCovarianceMatrix() const;

 protected:
  class qState {
   public:
    qState();
    void initFromVect(const Vector9d& v);
    void toVect(Vector9d& v) const;

    Quaternion<double> q;  // quaternion orientation
    Vector3<double> w;     // angular velocity
    Vector3<double> ww;    // angular acceleration
  };

  void computeSigmaPoints();
  void computeProcessModel(double delta_t);
  void computeAverageState();
  void computeCovarianceState();
  void computeMeasurements();
  void computeMeanAndCovMeasures();

  qState x;    // current a posteriori state vector
  qState xk_;  // a priori state vector

  Quaternion<double> b;  // orientation of the magnetic north
  Quaternion<double> g;  // orientation of the gravity

  Eigen::Matrix<double, 9, 9> P;    // current covariance of the state vector
  Eigen::Matrix<double, 9, 9> Pk_;  // a priori state vector covariance

  Eigen::Matrix<double, 9, 9> Q;  // process noise
  Eigen::Matrix<double, 9, 9> R;  // measurement noise

  Eigen::Matrix<double, 4, 18> M;  // temporary data used to compute Cholesky decomposition

  Eigen::Matrix<double, 9, 18> W_;  // temporary data used to compute a priori state vector covariance
  std::vector<Vector9d> W;          // temporary data used to compute sigma points
  std::vector<qState> X;            // sigma points {Xi}
  std::vector<qState> Y;            // propagated sigma points {Yi}
  Eigen::Matrix<double, 9, 18> Z;   // projection of the sigma points in the measurement space {Zi}
  std::vector<Vector3<double> > E;  // temporary data used to compute error vectors ei
  Vector9d zk_;                     // mean of {Zi}
  Eigen::Matrix<double, 9, 9> Pvv;  // innovation covariance
  Eigen::Matrix<double, 9, 9>
      Pxz;  // cross-correlation matrix (temporary data used for the computation of the Kalman gain)
  Eigen::Matrix<double, 9, 9> Kk;  // Kalman gain
};

}  // namespace Stabilization
}  // namespace VideoStitch

max_stars_repo_name: tlalexander/stitchEm

max_issues_repo_name: tlalexander/stitchEm

max_forks_repo_name: tlalexander/stitchEm


text:
/*
 * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <string>
#include <boost/lexical_cast.hpp>
#include "analysistool.h"
#include <votca/tools/histogram.h>
#include <votca/csg/version.h>
#include "bondedstatistics.h"
#include "tabulatedpotential.h"

using namespace std;
using namespace boost;

TabulatedPotential::TabulatedPotential()
{
    _tab_smooth1 = _tab_smooth2 = 0;
    _T = 300;
}

void TabulatedPotential::Register(map<string, AnalysisTool *> &lib)
{
    lib["tab"] = this;
    lib["hist"] = this;
}

void TabulatedPotential::Command(BondedStatistics &bs, string cmd, vector<string> &args)
{
    if(args[0] == "set") {
        if(cmd == "hist") SetOption(_hist_options, args);
        else if(cmd == "tab") {
            if(!SetOption(_tab_options, args)) {
                if(args.size() >2) {
                    if(args[1] == "smooth_pdf")
                        _tab_smooth1 = lexical_cast<int>(args[2]);
                    else if(args[1] == "smooth_pot")
                        _tab_smooth2 = lexical_cast<int>(args[2]);
                    else if(args[1] == "T")
                        _T = lexical_cast<double>(args[2]);
                    else {
                        cout << "unknown option " << args[2] << endl;
                        return;
                    }
                }
            }
            if(args.size() <=2) {
                cout << "smooth_pdf: " << _tab_smooth1 << endl;
                cout << "smooth_pot: " << _tab_smooth2 << endl;
                cout << "T: " << _T << endl;
            }
        }
    }
    else if(args.size() >= 2) {
        if(cmd == "hist") WriteHistogram(bs, args);
        else if(cmd == "tab") WritePotential(bs, args);
    }
    else cout << "wrong number of arguments" << endl;
}

void TabulatedPotential::Help(string cmd, vector<string> &args)
{
    if(args.size() == 0) {
        if(cmd == "tab") {
            cout << "tab <file> <selection>\n"
                 << "Calculate tabulated potential by inverting the distribution function. "
                    "Statistics is calculated using all interactions in selection.\n"
                    "see also: help tab set\n\n"
                    "example:\ntab set scale bond\ntab U_bond.txt *:bond:*\n";
        }
        if(cmd == "hist") {
            cout << "hist <file> <selection>\n"
                 << "Calculate distribution function for selection. "
                    "Statistics is calculated using all interactions in selection.\n"
                    "see also: help hist set\n\n"
                    "example:hist U_bond.txt *:bond:*\n";
        }
        return;
    }
    if(args[0] == "set") {
        if(args.size() == 1) {
            cout << cmd << " set <option> <value>\n"
                 << "set option for this command. Use \"" << cmd << " set\""
                    " for a list of available options. To get help on a specific option use e.g.\n"
                    << cmd << " set periodic\n";
            return;
        }
        if(args[1] == "n") {
            cout << cmd << "set n <integer>\n"
                 << "set number of bins for table\n";
            return;
        }
        if(args[1] == "min") {
            cout << cmd << "set min <value>\n"
                 << "minimum value of interval for histogram (see also periodic, extend)\n";
            return;
        }
        if(args[1] == "max") {
            cout << cmd << "set max <value>\n"
                 << "maximum value of interval for histogram (see also periodic, extend)\n";
            return;
        }
        if(args[1] == "periodic") {
            cout << cmd << "set periodic <value>\n"
                << "can be 1 for periodic interval (e.g. dihedral) or 0 for "
                    "non-periodic (e.g. bond)\n";
            return;
        }
        if(args[1] == "auto") {
            cout << cmd << "set auto <value>\n"
                 "can be 1 for automatically determine the interval for the "
                 "table (min, max, extend will be ignored) or 0 to use min/max as specified\n";
            return;
        }
        if(args[1] == "extend") {
            cout << cmd << "set extend <value>\n"
                 "should only be used with auto=0. Can be 1 for extend the interval "
                 "if values are out of bounds (min/max) "
                 "or 0 to ignore values which are out of the interal\n";
            return;
        }
        if(args[1] == "scale") {
            cout << cmd << "set scale <value>\n"
                "volume normalization of pdf. Can be no (no scaling), bond "
                "(1/r^2) or angle ( 1/sin(phi) ). See VOTCA manual, section "
                "theoretical background for details\n";
            return;
        }
        if(args[1] == "normalize") {
            cout << cmd << "set normalize <value>\n"
                 "can be 1 for a normalized histogram or 0 to skip normalization\n";
            return;
        }

        if(cmd == "tab") {
            if(args[1] == "smooth_pdf") {
                cout << "tab set smooth_pdf <value>\n"
                 "Perform so many smoothing iterations on the distribution function before inverting the potential\n";
                return;
            }
            if(args[1] == "smooth_pot") {
                cout << "tab set smooth_pot <value>\n"
                 "Perform so many smoothing iterations on tabulated potential after inverting the potential\n";
                return;
            }
            if(args[1] == "T") {
                cout << "tab set T <value>\n"
                 "Temperature in Kelvin the simulation was performed\n";
                return;
            }
        }
    }

    cout << "no help text available" << endl;
}

bool TabulatedPotential::SetOption(Histogram::options_t &op, const vector<string> &args)
{
    if(args.size() >2) {
        if(args[1] == "n")
            op._n = lexical_cast<int>(args[2]);
        else if(args[1] == "min") {
            op._min = lexical_cast<double>(args[2]);
        }
        else if(args[1] == "max")
            op._max = lexical_cast<double>(args[2]);
        else if(args[1] == "periodic")
            op._periodic = lexical_cast<bool>(args[2]);
        else if(args[1] == "auto")
            op._auto_interval = lexical_cast<bool>(args[2]);
        else if(args[1] == "extend")
            op._extend_interval = lexical_cast<bool>(args[2]);
        else if(args[1] == "normalize")
            op._normalize = lexical_cast<bool>(args[2]);
        else if(args[1] == "scale") {
            if(args[2]=="no" || args[2]=="bond" || args[2]=="angle")
                op._scale = args[2];
            else {
                cout << "scale can be: no, bond or angle\n";
            }
        }
        else {
            return false;
        }
    }
    else {
        cout << "n: " << op._n << endl;
        cout << "min: " << op._min << endl;
        cout << "max: " << op._max << endl;
        cout << "periodic: " << op._periodic << endl;
        cout << "auto: " << op._auto_interval << endl;
        cout << "extend: " << op._extend_interval << endl;
        cout << "scale: " << op._scale << endl;
        cout << "normalize: " << op._normalize << endl;
    }
    return true;
}

void TabulatedPotential::WriteHistogram(BondedStatistics &bs, vector<string> &args)
{
    ofstream out;
    DataCollection<double>::selection *sel = NULL;

    for(size_t i=1; i<args.size(); i++)
        sel = bs.BondedValues().select(args[i], sel);
    Histogram h(_hist_options);
    h.ProcessData(sel);
    out.open(args[0].c_str());
/*    out << "# histogram, created csg version " <<  VERSION_STR  << endl;
    out << "# n = " << _hist_options._n << endl;
    out << "# min = " << _hist_options._min << endl;
    out << "# max = " << _hist_options._max << endl;
    out << "# periodic = " << _hist_options._periodic << endl;
    out << "# auto = " << _hist_options._auto_interval << endl;
    out << "# extend = " << _hist_options._extend_interval << endl;
    out << "# scale = " << _hist_options._scale << endl;*/
    out << h ;
    out.close();
    cout << "histogram created using " << sel->size() << " data-rows, written to " << args[0] << endl;
    delete sel;
}

void TabulatedPotential::CalcForce(vector<double> &U, vector<double> &F, double dx, bool bPeriodic)
{
    size_t n=U.size();
    double f = 0.5/dx;
    F.resize(n);
    if(bPeriodic)
        F[n-1] = F[0] = -(U[1] - U[n-2])*f;
    else {
        F[0] = -(U[1] - U[0])*2*f;
        F[n-1] = -(U[n-1] - U[n-2])*2*f;
    }
    for(size_t i=1; i<n-1; i++)
        F[i] = -(U[i+1] - U[i-1])*f;
}

void TabulatedPotential::WritePotential(BondedStatistics &bs, vector<string> &args)
{
   ofstream out;
    DataCollection<double>::selection *sel = NULL;

    for(size_t i=1; i<args.size(); i++)
        sel = bs.BondedValues().select(args[i], sel);
    Histogram h(_tab_options);
    h.ProcessData(sel);
    for(int i=0; i<_tab_smooth1; ++i)
        Smooth(h.getPdf(), _tab_options._periodic);
    BoltzmannInvert(h.getPdf(), _T);
    for(int i=0; i<_tab_smooth2; ++i)
        Smooth(h.getPdf(), _tab_options._periodic);
    out.open(args[0].c_str());

/*       out << "# tabulated potential, created csg version " VERSION_STR  << endl;
    out << "# n = " << _tab_options._n << endl;
    out << "# min = " << _tab_options._min << endl;
    out << "# max = " << _tab_options._max << endl;
    out << "# periodic = " << _tab_options._periodic << endl;
    out << "# auto = " << _tab_options._auto_interval << endl;
    out << "# extend = " << _tab_options._extend_interval << endl;
    out << "# scale = " << _tab_options._scale << endl;
    out << "# smooth_pdf = " << _tab_smooth1 << endl;
    out << "# smooth_pot = " << _tab_smooth2 << endl;
    out << "# T = " << _T << endl;*/

    vector<double> F;

    CalcForce(h.getPdf(), F, h.getInterval(), _tab_options._periodic);
    for(int i=0; i<h.getN(); i++) {
        out << h.getMin() + h.getInterval()*((double)i) << " " << h.getPdf()[i] << " " << F[i] << endl;
    }
    out.close();
    cout << "histogram created using " << sel->size() << " data-rows, written to " << args[0] << endl;
    delete sel;
}

void TabulatedPotential::Smooth(vector<double> &data, bool bPeriodic)
{
    double old[3];
    int n=data.size();
    if(bPeriodic) {
        old[0] = data[n-3];
        old[1] = data[n-2];
    }
    else {
        old[0] = data[0];
        old[1] = data[0];
    }
    size_t i;
    for(i=0; i<data.size()-2; i++) {
        old[2] = data[i];
        data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[i+2])/9.;
        old[0]=old[1];
        old[1]=old[2];;
    }
    if(bPeriodic) {
        data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 2.*data[i+1] + data[0])/9.;
        old[0]=old[1];old[1]=data[i];
        data[n-1] = data[0];
    }
    else {
        data[i] = (old[0] + 2.*old[1] + 3.*data[i] + 3.*data[i+1])/9.;
        old[0]=old[1];old[1]=data[i];
        i++;
        data[i] = (old[0] + 2.*old[1] + 6.*data[i])/9.;
    }
}

void TabulatedPotential::BoltzmannInvert(vector<double> &data, double T)
{
    double _min, _max;

    _min = numeric_limits<double>::max();
    _max = numeric_limits<double>::min();

    for(size_t i=0; i<data.size(); i++) {
        _max = max(data[i], _max);
        if(data[i] > 0) _min = min(data[i], _min);
    }
    _max = -8.3109*T*log(_max)*0.001;
    _min = -8.3109*T*log(_min)*0.001-_max;

    for(size_t i=0; i<data.size(); i++) {
        if(data[i] == 0) data[i] = _min;
        else
            data[i] = -8.3109*T*log(data[i])*0.001 - _max;
    }
}


text:
#pragma once

#include <conduit/async/callback.hpp>

#include <conduit/io/responses.hpp>

#include <boost/asio.hpp>

#include <coroutine>

namespace conduit::io {
using boost::asio::ip::tcp;
using boost::system::error_code;
template <class...>
struct resolve;

template <class Protocol, class Executor>
class resolve<boost::asio::ip::basic_resolver<Protocol, Executor>> {

    using resolver = boost::asio::ip::basic_resolver<Protocol, Executor>;
    using endpoint_list = typename resolver::results_type;
    resolver& r;
    std::string_view host;
    std::string_view service;
    error_code const* ec_ptr;
    endpoint_list endpoints;

    auto get_handler(std::coroutine_handle<> h) {
        return [this, caller = async::callback(h)](
                   error_code const& ec,
                   endpoint_list r) mutable {
            ec_ptr = &ec;
            endpoints = std::move(r);
            caller.resume();
        };
    }

   public:
    resolve(resolver& r, std::string_view host, std::string_view service)
      : r(r)
      , host(host)
      , service(service) {}

    constexpr bool await_ready() noexcept { return false; }
    void await_suspend(std::coroutine_handle<> h) {
        r.async_resolve(host, service, get_handler(h));
    }
    auto await_resume() {
        return resolve_result {*ec_ptr, std::move(endpoints)};
    }
};

template <class Protocol, class Executor>
resolve(
    boost::asio::ip::basic_resolver<Protocol, Executor>&,
    std::string_view,
    std::string_view)
    -> resolve<boost::asio::ip::basic_resolver<Protocol, Executor>>;
} // namespace conduit::io

max_stars_repo_name: jantonioperez/conduit

max_issues_repo_name: functionalperez/conduit

max_forks_repo_name: codeinred/conduit


text:
/*=============================================================================
    Copyright (c) 2003 Martin Wille
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <boost/spirit/core.hpp>
#include <boost/spirit/dynamic/while.hpp>

extern bool fun();

struct ftor
{
    bool operator()() const;
};

int
main()
{
    //////////////////////////////////
    // compile time check wether as_parser<> works for while_p

    ::boost::spirit::rule<> r;

    r = ::boost::spirit::while_p('-')['-'];
    r = ::boost::spirit::while_p("-")["-"];

    r = ::boost::spirit::while_p(&fun)["foo"];
    r = ::boost::spirit::while_p(ftor())["foo"];

    r = ::boost::spirit::while_p(r)[r];

    r = ::boost::spirit::do_p['-'].while_p('-');
    r = ::boost::spirit::do_p["-"].while_p("-");

    r = ::boost::spirit::do_p["foo"].while_p(&fun);
    r = ::boost::spirit::do_p["foo"].while_p(ftor());

    r = ::boost::spirit::do_p[r].while_p(r);
}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
//// Copyright (c) 2018 Silvio Mayolo
//// See LICENSE.txt for licensing details

#include "catch2/catch.hpp"
#include "test.hpp"
#include "Garnish.hpp"
#include "Proto.hpp"
#include "Number.hpp"
#include "Symbol.hpp"
#include <boost/blank.hpp>
#include <string>

// Not testing the garnishSeq stuff here right now.

TEST_CASE( "String garnishing", "[garnish]" ) {

  ObjectPtr obj = garnishObject(globalVM->reader, std::string("abc"));
  std::string* str = boost::get<std::string>(&obj->prim());

  REQUIRE( str != nullptr );
  REQUIRE( *str == "abc" );
  REQUIRE( (*obj)[Symbols::parent()] == globalVM->reader.lit[Lit::STRING] );

}

TEST_CASE( "Number garnishing", "[garnish]" ) {

  ObjectPtr n1 = garnishObject(globalVM->reader, 10);
  ObjectPtr n2 = garnishObject(globalVM->reader, 10l);
  ObjectPtr n3 = garnishObject(globalVM->reader, Number((Number::smallint)10));

  Number* x1 = boost::get<Number>(&n1->prim());
  Number* x2 = boost::get<Number>(&n2->prim());
  Number* x3 = boost::get<Number>(&n3->prim());

  REQUIRE( x1 != nullptr );
  REQUIRE( x2 != nullptr );
  REQUIRE( x3 != nullptr );

  REQUIRE( *x1 == 10l );
  REQUIRE( *x2 == 10l );
  REQUIRE( *x3 == 10l );

  REQUIRE( (*n1)[Symbols::parent()] == globalVM->reader.lit[Lit::NUMBER] );
  REQUIRE( (*n2)[Symbols::parent()] == globalVM->reader.lit[Lit::NUMBER] );
  REQUIRE( (*n3)[Symbols::parent()] == globalVM->reader.lit[Lit::NUMBER] );

}

TEST_CASE( "Symbol garnishing", "[garnish]" ) {

  Symbolic sym = Symbols::get()["foo"];

  ObjectPtr obj = garnishObject(globalVM->reader, sym);
  Symbolic* sym1 = boost::get<Symbolic>(&obj->prim());

  REQUIRE( sym1 != nullptr );
  REQUIRE( *sym1 == sym );
  REQUIRE( (*obj)[Symbols::parent()] == globalVM->reader.lit[Lit::SYMBOL] );

}

TEST_CASE( "Singleton garnishing (Booleans and nil)", "[garnish]" ) {

  ObjectPtr t = garnishObject(globalVM->reader, true);
  ObjectPtr f = garnishObject(globalVM->reader, false);
  ObjectPtr n = garnishObject(globalVM->reader, boost::blank());

  REQUIRE( t == globalVM->reader.lit[Lit::TRUE] );
  REQUIRE( f == globalVM->reader.lit[Lit::FALSE] );
  REQUIRE( n == globalVM->reader.lit[Lit::NIL] );

}

max_stars_repo_name: Mercerenies/latitude

max_issues_repo_name: Mercerenies/latitude

max_forks_repo_name: Mercerenies/proto-lang


text:
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/functional.hpp>

#include <boost/hana/detail/assert.hpp>
using namespace boost::hana;

struct nonpod { virtual ~nonpod() { } };

int main() {
    BOOST_HANA_CONSTEXPR_ASSERT(always('a')() == 'a');
    BOOST_HANA_CONSTEXPR_ASSERT(always('a')(1) == 'a');
    BOOST_HANA_CONSTEXPR_ASSERT(always('a')(1, '2') == 'a');
    BOOST_HANA_CONSTEXPR_ASSERT(always('a')(1, '2', "3") == 'a');
    BOOST_HANA_CONSTEXPR_ASSERT(always('a')(1, '2', "3", 4.4f) == 'a');
    BOOST_HANA_RUNTIME_ASSERT(always('a')(1, '2', "3", 4.4f, nonpod{}) == 'a');
}

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
// -*- mode: c++; -*-

#include <iostream>
using namespace std;

#include <lbp/frame_range.hpp>
#include <lbp/oclbp.hpp>
#include <lbp/utils.hpp>

#include <options.hpp>
#include <run.hpp>

#include <boost/format.hpp>
using fmt = boost::format;

static void
f (cv::VideoCapture& cap, const options_t& opts) {
    const bool display = opts.have ("display");

    const auto op = lbp::oclbp< unsigned char, 1, 8 >;

    for (auto& frame : lbp::getframes_from (cap)) {
        lbp::frame_delay temp { 0 };

        const auto images = op (frame);

        if (display) {
            size_t i = 0;

            for (const auto& image : images) {
                imshow ((fmt ("Opponent Color LBP #%1%") % (i++)).str (), image);
            }
        }

        if (temp.wait_for_key (27))
            break;
    }
}

int main (int argc, char** argv) {
    program_options_from (argc, argv);
    return run_with (f, global_options ()), 0;
}

max_stars_repo_name: thinkoid/lbp

max_issues_repo_name: thinkoid/lbp

max_forks_repo_name: thinkoid/lbp


text: #include <boost/pending/fibonacci_heap.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <Access/RowPolicy.h>
#include <Common/quoteString.h>
#include <boost/range/algorithm/equal.hpp>

namespace DB
{
namespace ErrorCodes
{
    extern const int NOT_IMPLEMENTED;
}

void RowPolicy::setDatabase(const String & database)
{
    full_name.database = database;
    IAccessEntity::setName(full_name.toString());
}

void RowPolicy::setTableName(const String & table_name)
{
    full_name.table_name = table_name;
    IAccessEntity::setName(full_name.toString());
}

void RowPolicy::setShortName(const String & short_name)
{
    full_name.short_name = short_name;
    IAccessEntity::setName(full_name.toString());
}

void RowPolicy::setFullName(const String & short_name, const String & database, const String & table_name)
{
    full_name.short_name = short_name;
    full_name.database = database;
    full_name.table_name = table_name;
    IAccessEntity::setName(full_name.toString());
}

void RowPolicy::setFullName(const RowPolicyName & full_name_)
{
    full_name = full_name_;
    IAccessEntity::setName(full_name.toString());
}

void RowPolicy::setName(const String &)
{
    throw Exception("RowPolicy::setName() is not implemented", ErrorCodes::NOT_IMPLEMENTED);
}

bool RowPolicy::equal(const IAccessEntity & other) const
{
    if (!IAccessEntity::equal(other))
        return false;
    const auto & other_policy = typeid_cast<const RowPolicy &>(other);
    return (full_name == other_policy.full_name) && boost::range::equal(filters, other_policy.filters)
        && restrictive == other_policy.restrictive && (to_roles == other_policy.to_roles);
}

}

max_stars_repo_name: pdv-ru/ClickHouse

max_issues_repo_name: pdv-ru/ClickHouse

max_forks_repo_name: pdv-ru/ClickHouse


text: #include <boost/fusion/include/make_vector.hpp>


text:
/*****************************************************************\
           __
          / /
		 / /                     __  __
		/ /______    _______    / / / / ________   __       __
	   / ______  \  /_____  \  / / / / / _____  | / /      / /
	  / /      | / _______| / / / / / / /____/ / / /      / /
	 / /      / / / _____  / / / / / / _______/ / /      / /
	/ /      / / / /____/ / / / / / / |______  / |______/ /
   /_/      /_/ |________/ / / / /  \_______/  \_______  /
                          /_/ /_/                     / /
			                                         / /
		       High Level Game Framework            /_/

  ---------------------------------------------------------------

  Copyright (c) 2007-2012 - Rodrigo Braz Monteiro.
  This file is subject to the terms of halley_license.txt.

\*****************************************************************/

// Comment this whole thing out for now
#ifdef false

#include "http.h"
#include <halley/support/exception.h>

using namespace Halley;

#ifdef _MSC_VER
#pragma warning(disable: 6386 6258 6309 6387 4913)
#endif

#define BOOST_SYSTEM_NO_DEPRECATED
#include <boost/asio.hpp>

Bytes HTTP::get(String host, String path)
{
	String content = "";
	return request(host, path, false, content, "");
}

Bytes HTTP::post(String host, String path, Vector<HTTPPostEntry>& entries)
{
	String boundary = "=.AaB03xBOunDaRyyy--";

	std::stringstream c;
	for (size_t i=0; i<entries.size(); i++) {
		c << "--" << boundary << "\r\n";
		if (entries[i].filename == "") {
			c << "content-disposition: form-data; name=\"" << entries[i].name << "\"\r\n\r\n";
		} else {
			c << "content-disposition: form-data; name=\"" << entries[i].name << "\"; filename=\"" << entries[i].filename << "\"\r\n";
			c << "Content-Type: application/unknown\r\n";
			c << "Content-Transfer-Encoding: binary\r\n\r\n";
		}
		c.write(reinterpret_cast<const char*>(entries[i].data.data()), entries[i].data.size());
		if (i != entries.size() - 1) c << "\r\n";
	}
	String content = c.str();

	return request(host, path, true, content, boundary);
}

Bytes HTTP::request(String host, String path, bool isPost, String& content, String boundary)
{
	// Code adapted from http://www.boost.org/doc/libs/1_49_0_beta1/doc/html/boost_asio/example/http/client/sync_client.cpp

	using boost::asio::ip::tcp;
	boost::asio::io_service io_service;

	// Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(host.c_str(), "http");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << (isPost ? "POST " : "GET ") << path.c_str() << " HTTP/1.0\r\n";
    request_stream << "Host: " << host.c_str() << "\r\n";
    request_stream << "Accept: */*\r\n";
	if (isPost) {
		request_stream << "Content-Length: " << content.length() << "\r\n";
		request_stream << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
	}
    request_stream << "Connection: close\r\n\r\n";
	if (isPost) {
		request_stream << content;
	}

	// Send the request.
	write(socket, request);

	// Read the reply
	Bytes result;
	size_t pos = 0;
	while (true) {
		std::array<char, 128> buf;
		boost::system::error_code error;

		size_t len = socket.read_some(boost::asio::buffer(buf), error);
		if (error == boost::asio::error::eof) {
			break;
		} else if (error) {
			throw Exception("Error reading from socket: " + error.message());
		}

		result.resize(result.size() + len);
		memcpy(&result[pos], &buf[0], len);
		pos += len;
	}
	return result;
}

#endif

max_stars_repo_name: sunhay/halley

max_issues_repo_name: sunhay/halley

max_forks_repo_name: sunhay/halley