text:
//   Copyright: Copyright (C) 2005, Jan Ringos, http://Tringi.Mx-3.cz
//   Version: 1.1
//
//  Copyright (c) 2014 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef INT128_HPP
#define INT128_HPP

#include <hpx/hpx_fwd.hpp>

#include <exception>
#include <cstdlib>
#include <cstdio>
#include <new>

#include <boost/cstdint.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/split_member.hpp>

namespace hpx { namespace util { namespace numerics
{
    ///////////////////////////////////////////////////////////////////////////
    class HPX_EXPORT int128
    {
    private:
        // Binary correct representation of signed 128bit integer
        boost::uint64_t lo;
        boost::int64_t hi;

    protected:
        // Some global operator functions must be friends
        friend bool operator <  (const int128 &, const int128 &) throw ();
        friend bool operator == (const int128 &, const int128 &) throw ();
        friend bool operator || (const int128 &, const int128 &) throw ();
        friend bool operator && (const int128 &, const int128 &) throw ();

    public:
        // Constructors
        inline int128 () throw () {};

        inline int128 (const unsigned int & a) throw () : lo (a), hi (0ll) {};
        inline int128 (const signed int & a) throw () : lo (a), hi (0ll) {
            if (a < 0) this->hi = -1ll;
        };

        inline int128 (const boost::uint64_t & a) throw () : lo (a), hi (0ll) {};
        inline int128 (const boost::int64_t & a) throw () : lo (a), hi (0ll) {
            if (a < 0) this->hi = -1ll;
        };

        int128 (const float a) throw ();
        int128 (const double & a) throw ();
        int128 (const long double & a) throw ();

        int128 (const char * sz) throw ();

        // TODO: Consider creation of operator= to eliminate
        //       the need of intermediate objects during assignments.

    private:
        // Special internal constructors
        int128 (const boost::uint64_t & a, const boost::int64_t & b) throw ()
            : lo (a), hi (b) {};

    public:
        // Operators
        bool operator ! () const throw ();

        int128 operator - () const throw ();
        int128 operator ~ () const throw ();

        int128 & operator ++ ();
        int128 & operator -- ();
        int128 operator ++ (int);
        int128 operator -- (int);

        int128 & operator += (const int128 & b) throw ();
        int128 & operator *= (const int128 & b) throw ();

        int128 & operator >>= (unsigned int n) throw ();
        int128 & operator <<= (unsigned int n) throw ();

        int128 & operator |= (const int128 & b) throw ();
        int128 & operator &= (const int128 & b) throw ();
        int128 & operator ^= (const int128 & b) throw ();

        // Inline simple operators
        inline const int128 & operator + () const throw () { return *this; };

        // Rest of inline operators
        inline int128 & operator -= (const int128 & b) throw () {
            return *this += (-b);
        };
        inline int128 & operator /= (const int128 & b) throw () {
            int128 dummy;
            *this = this->div (b, dummy);
            return *this;
        };
        inline int128 & operator %= (const int128 & b) throw () {
            this->div (b, *this);
            return *this;
        };

        // Common methods
        int toInt () const throw () { return (int) this->lo; };
        boost::int64_t toInt64 () const throw ()
            { return (boost::uint64_t) this->lo; };

        const char * toString (unsigned int radix = 10) const throw ();
        float toFloat () const throw ();
        double toDouble () const throw ();
        long double toLongDouble () const throw ();

        // Arithmetic methods
        int128  div (const int128 &, int128 &) const throw ();

        // Bit operations
        bool    bit (unsigned int n) const throw ();
        void    bit (unsigned int n, bool val) throw ();

    private:
        friend class boost::serialization::access;

        BOOST_SERIALIZATION_SPLIT_MEMBER()

        template <typename Archive>
        void save(Archive& ar, const unsigned int version) const;
        template <typename Archive>
        void load(Archive& ar, const unsigned int version);
    }
#ifdef __GNUC__
    __attribute__ ((__aligned__ (16), __packed__))
#endif
    ;

    // GLOBAL OPERATORS

    bool operator <  (const int128 & a, const int128 & b) throw ();
    bool operator == (const int128 & a, const int128 & b) throw ();
    bool operator || (const int128 & a, const int128 & b) throw ();
    bool operator && (const int128 & a, const int128 & b) throw ();

    // GLOBAL OPERATOR INLINES

    inline int128 operator + (const int128 & a, const int128 & b) throw () {
        return int128 (a) += b; };
    inline int128 operator - (const int128 & a, const int128 & b) throw () {
        return int128 (a) -= b; };
    inline int128 operator * (const int128 & a, const int128 & b) throw () {
        return int128 (a) *= b; };
    inline int128 operator / (const int128 & a, const int128 & b) throw () {
        return int128 (a) /= b; };
    inline int128 operator % (const int128 & a, const int128 & b) throw () {
        return int128 (a) %= b; };

    inline int128 operator >> (const int128 & a, unsigned int n) throw () {
        return int128 (a) >>= n; };
    inline int128 operator << (const int128 & a, unsigned int n) throw () {
        return int128 (a) <<= n; };

    inline int128 operator & (const int128 & a, const int128 & b) throw () {
        return int128 (a) &= b; };
    inline int128 operator | (const int128 & a, const int128 & b) throw () {
        return int128 (a) |= b; };
    inline int128 operator ^ (const int128 & a, const int128 & b) throw () {
        return int128 (a) ^= b; };

    inline bool operator >  (const int128 & a, const int128 & b) throw () {
        return   b < a; };
    inline bool operator <= (const int128 & a, const int128 & b) throw () {
        return !(b < a); };
    inline bool operator >= (const int128 & a, const int128 & b) throw () {
        return !(a < b); };
    inline bool operator != (const int128 & a, const int128 & b) throw () {
        return !(a == b); };
}}}

// MISC

// typedef hpx::util::numerics::int128 __int128_t;

#endif


text:
/*
 * Stream-Processing Architecture for Real-time Cyber-physical Security (SPARCS)
 */

/*
 * File:   serviceInstanceList.cpp
 * Author: mcp
 *
 * Created on January 25, 2016, 7:46 AM
 */

#include <boost/thread.hpp>
#include <boost/dll/import.hpp>
#include <boost/thread/condition.hpp>
#include <boost/any.hpp>
#include <dlfcn.h>
#include <map>
#include <mutex>
#include <iostream>
#include "serviceCommandQueueTemplate.h"
#include "serviceInstanceApi.h"
#include "serviceInstance.h"
#include "serviceInstanceList.h"

namespace serviceCommon {

using namespace serviceCommon;

using namespace boost;

bool serviceInstanceList::instanceFlag = false;
serviceInstanceList* serviceInstanceList::single = NULL;

serviceInstanceList::serviceInstanceList() {
}

serviceInstanceList::~serviceInstanceList() {
}

serviceInstanceList* serviceInstanceList::getInstance()
{
    if(! instanceFlag)
    {
        single = new serviceInstanceList();
        instanceFlag = true;
        return single;
    }
    else
    {
        return single;
    }
}

void serviceInstanceList::createServiceInstance(
    serviceInstance * si) {
    boost::filesystem::path lib_path(si->serviceLibPath);

    //try {
        si->serviceThread = boost::dll::import_alias<serviceInstanceApi>(
            lib_path / si->serviceImplementation,
            "plugin",
            boost::dll::load_mode::default_mode);
    //}
    //catch (const std::exception &e) {
       /* log error */
        //int i = 0;
   // }

    services.insert(std::make_pair(si->serviceName, si));
}

}

ext: cpp

max_stars_repo_name: lbnl-cybersecurity/sparcs

max_issues_repo_name: lbnl-cybersecurity/sparcs

max_forks_repo_name: lbnl-cybersecurity/sparcs


text:
/*
 *  connectivity.hpp
 *
 *
 *  Created by Andrea Bedini on 10/Jul/2009.
 *  Copyright (c) 2009-2014, Andrea Bedini <andrea.bedini@gmail.com>.
 *
 *  Distributed under the terms of the Modified BSD License.
 *  The full license is in the file COPYING, distributed as part of
 *  this software.
 *
 */

#ifndef CONNECTIVITY_HPP
#define CONNECTIVITY_HPP

#include "connectivity_functions.hpp"

#include <boost/cstdint.hpp>
#include <boost/functional/hash.hpp>

#include <algorithm>
#include <iosfwd>

class connectivity
{
  typedef boost::uint8_t uint8_t;

  unsigned int size_;
  uint8_t * impl_;

public:
  connectivity(unsigned int n)
    : size_(n)
    , impl_(new uint8_t[size_])
  {
    for (unsigned int i = 0; i < size_; ++i)
      impl_[i] = i + 1;
  }

  connectivity(const connectivity& rhs)
    : size_(rhs.size_)
    , impl_(new uint8_t[size_])
  {
    std::copy(rhs.impl_, rhs.impl_ + rhs.size_, impl_);
  }

  ~connectivity()
  {
    if (impl_)
      delete [] impl_;
  }

  connectivity& operator=(const connectivity& rhs)
  {
    if (this != &rhs) {
      uint8_t* new_impl_ = new uint8_t[rhs.size_];
      std::copy(rhs.impl_, rhs.impl_ + rhs.size_, new_impl_);
      delete [] impl_;
      impl_ = new_impl_;
      size_ = rhs.size_;
    }
    return *this;
  }

  unsigned int size() const
  {
    return size_;
  }

  void swap(connectivity& rhs) throw ()
  {
    using std::swap;
    swap(size_, rhs.size_);
    swap(impl_, rhs.impl_);
  }

  bool operator==(const connectivity& rhs) const
  {
    return (size_ == rhs.size_) and std::equal(impl_, impl_ + size_, rhs.impl_);
  }

  connectivity& canonicalize()
  {
    connectivity_functions::canonicalize(size_, impl_);
    return *this;
  }

  //////////////////////////////////////////////////////////////////////
  // const
  //////////////////////////////////////////////////////////////////////

  bool connected(unsigned int i, unsigned int j) const
  {
    return connectivity_functions::connected(impl_, i, j);
  }

  bool singleton(unsigned int i) const
  {
    return connectivity_functions::is_singleton(size_, impl_, i);
  }

  connectivity& delete_node(unsigned int i)
  {
    connectivity new_(size_ - 1);
    std::copy(impl_, impl_ + i, new_.impl_);
    std::copy(impl_ + i + 1, impl_ + size_, new_.impl_ + i);
    swap(new_);
    return *this;
  }

  connectivity& connect(unsigned int i, unsigned int j)
  {
    connectivity_functions::connect(size_, impl_, i, j);
    return *this;
  }

  connectivity& detach(unsigned int i)
  {
    connectivity_functions::detach(size_, impl_, i);
    return *this;
  }

  template<typename F>
  void decompose(F f) const
  {
    connectivity_functions::decompose(size_, impl_, f);
  }

  friend std::size_t hash_value(const connectivity&);
  friend std::ostream& operator<<(std::ostream&, const connectivity&);
};

std::size_t hash_value(const connectivity& a)
{
  return boost::hash_range(a.impl_, a.impl_ + a.size_);
}

std::ostream& operator<<(std::ostream& o, const connectivity& c)
{
  o << "{ ";
  for (unsigned int i = 0; i < c.size_; ++i) {
    o << (int) c.impl_[i] << " ";
  }
  return o << "}";
}

#endif

ext: hpp

max_stars_repo_name: andreabedini/tutte

max_issues_repo_name: andreabedini/tutte

max_forks_repo_name: andreabedini/tutte


text:
#ifdef RICH_MPI
#include <mpi.h>
#endif
#include <boost/foreach.hpp>
#include "source/newtonian/two_dimensional/diagnostics.hpp"
#include "source/newtonian/test_2d/main_loop_2d.hpp"
#include "source/tessellation/shape_2d.hpp"
#include "source/newtonian/test_2d/piecewise.hpp"
#include "source/newtonian/two_dimensional/physical_geometry.hpp"
#include "source/newtonian/two_dimensional/geometric_outer_boundaries/SquareBox.hpp"
#include "source/tessellation/VoronoiMesh.hpp"
#include "source/newtonian/common/ideal_gas.hpp"
#include "source/newtonian/two_dimensional/point_motions/eulerian.hpp"
#include "source/newtonian/common/hllc.hpp"
#include "source/newtonian/two_dimensional/source_terms/zero_force.hpp"
#include "source/misc/mesh_generator.hpp"
#include "source/newtonian/two_dimensional/spatial_distributions/uniform2d.hpp"
#include "source/newtonian/two_dimensional/source_terms/cylindrical_complementary.hpp"
#include "source/newtonian/two_dimensional/simple_flux_calculator.hpp"
#include "source/newtonian/two_dimensional/simple_cell_updater.hpp"
#include "source/newtonian/two_dimensional/hdf5_diagnostics.hpp"
#include "source/newtonian/two_dimensional/simple_extensive_updater.hpp"
#include "source/newtonian/two_dimensional/stationary_box.hpp"

using namespace std;
using namespace simulation2d;

namespace {

  bool same_side(const Vector2D& p1,
		 const Vector2D& p2,
		 const Vector2D& a,
		 const Vector2D& b)
  {
    const double cp1 = CrossProduct(b-a,p1-a);
    const double cp2 = CrossProduct(b-a,p2-a);
    return cp1*cp2>=0;
  }

  class Triangle: public Shape2D
  {
  public:

    const Vector2D p1;
    const Vector2D p2;
    const Vector2D p3;

    Triangle(const Vector2D& p1_i,
	     const Vector2D& p2_i,
	     const Vector2D& p3_i):
      p1(p1_i), p2(p2_i), p3(p3_i) {}

    bool operator()(const Vector2D& p) const
    {
      return same_side(p,p1,p2,p3)&&
	same_side(p,p2,p1,p3)&&
	same_side(p,p3,p1,p2);
    }
  };

  vector<ComputationalCell> calc_init_cond
  (const Tessellation& tess)
  {
    vector<ComputationalCell> res(static_cast<size_t>(tess.GetPointNo()));
    for(size_t i=0;i<res.size();++i){
      const Triangle triangle(Vector2D(0.5,0.6),
			      Vector2D(0.7,0.5),
			      Vector2D(0.4,0.4));
      const Vector2D r = tess.GetMeshPoint(static_cast<int>(i));
      res[i].density = 1;
      res[i].pressure = triangle(r) ? 2 : 1;
      res[i].velocity = triangle(r) ? Vector2D(1,-1) : Vector2D(0,0);
      //      res[i].tracers.push_back(triangle(r) ? 1 : 0);
      res[i].tracers[0] = triangle(r) ? 1 : 0;
    }
    return res;
  }

  class SimData
  {
  public:

    SimData(void):
      pg_(),
      outer_(Vector2D(0,0), Vector2D(1,1)),
#ifdef RICH_MPI
      proc_tess_(process_positions(outer_),outer_),
      init_points_
      (distribute_grid(proc_tess_,CartesianGridGenerator
		       (30,30, outer_.getBoundary().first,
			outer_.getBoundary().second))),
#else
      init_points_(cartesian_mesh(30,30,
				  outer_.getBoundary().first,
				  outer_.getBoundary().second)),
#endif
      tess_(init_points_,outer_),
      eos_(5./3.),
      pm_(),
      evc_(),
      rs_(),
      force_(),
      tsf_(0.3),
      fc_(rs_),
      eu_(),
      cu_(),
      sim_(tess_,
	   outer_,
	   pg_,
	   calc_init_cond(tess_),
	   eos_,
	   pm_,
	   evc_,
	   force_,
	   tsf_,
	   fc_,
	   eu_,
	   cu_,
	   TracerStickerNames(vector<string>(1,"tracer"),vector<string>())) {}

    hdsim& getSim(void)
    {
      return sim_;
    }

  private:
    SlabSymmetry pg_;
    SquareBox outer_;
#ifdef RICH_MPI
    VoronoiMesh proc_tess_;
#endif
    const vector<Vector2D> init_points_;
    VoronoiMesh tess_;
    IdealGas eos_;
    Eulerian pm_;
    const StationaryBox evc_;
    Hllc rs_;
    ZeroForce force_;
    SimpleCFL tsf_;
    SimpleFluxCalculator fc_;
    const SimpleExtensiveUpdater eu_;
    SimpleCellUpdater cu_;
    hdsim sim_;
  };

  class WriteConserved: public DiagnosticFunction
  {
  public:

    WriteConserved(string const& fname):
      cons_(), fname_(fname) {}

    void operator()(hdsim const& sim)
    {
      cons_.push_back(total_conserved(sim));
    }

    ~WriteConserved(void)
    {
#ifdef RICH_MPI
      if(get_mpi_rank()==0){
#endif
	ofstream f(fname_.c_str());
	for(size_t i=0;i<cons_.size();++i)
	  f << cons_[i].mass << " "
	    << cons_[i].momentum.x << " "
	    << cons_[i].momentum.y << " "
	    << cons_[i].energy << " "
	    << cons_[i].tracers[0] << "\n";
	f.close();
#ifdef RICH_MPI
      }
#endif
    }

  private:
    mutable vector<Extensive> cons_;
    const string fname_;
  };
}

namespace {
  void my_main_loop(hdsim& sim)
  {
    SafeTimeTermination term_cond(0.05,1e6);
    WriteConserved diag("res.txt");
    write_snapshot_to_hdf5(sim,"initial.h5");
    main_loop(sim,
	      term_cond,
	      &hdsim::TimeAdvance,
	      &diag);
    write_snapshot_to_hdf5(sim,"final.h5");
  }
}

int main(void)
{
#ifdef RICH_MPI
  MPI_Init(NULL, NULL);
#endif
  SimData sim_data;
  hdsim& sim = sim_data.getSim();

  my_main_loop(sim);

#ifdef RICH_MPI
  MPI_Finalize();
#endif

  return 0;
}

max_stars_repo_name: GalaxyHunters/Vivid

max_issues_repo_name: GalaxyHunters/Vivid

max_forks_repo_name: GalaxyHunters/Vivid


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// This file was modified by Oracle on 2020-2021.
// Modifications copyright (c) 2020-2021 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// 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)

#ifndef BOOST_GEOMETRY_VIEWS_SEGMENT_VIEW_HPP
#define BOOST_GEOMETRY_VIEWS_SEGMENT_VIEW_HPP

#include <array>

#include <boost/geometry/algorithms/detail/assign_indexed_point.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tag.hpp>

namespace boost { namespace geometry
{

// NOTE: This is equivalent to the previous implementation with detail::points_view.
//       Technically this should not be called a view because it owns the elements.
//       It's also not a borrowed_range because of dangling iterators after the
//       destruction.
//       It's a container or more specifically a linestring of some sort, e.g. static_linestring.
// NOTE: It would be possible to implement a borrowed_range or a view.
//       The iterators would have to store copies of points.
//       Another possibility is to store the original Segment or reference/pointer
//       to Segment and index. But then the reference would be the value type
//       so technically they would be InputIterators not RandomAccessIterators.

/*!
\brief Makes a segment behave like a linestring or a range
\details Adapts a segment to the Boost.Range concept, enabling the user to
    iterate the two segment points. The segment_view is registered as a LineString Concept
\tparam Segment \tparam_geometry{Segment}
\ingroup views

\qbk{before.synopsis,
[heading Model of]
[link geometry.reference.concepts.concept_linestring LineString Concept]
}

\qbk{[include reference/views/segment_view.qbk]}

*/
template <typename Segment>
struct segment_view
{
    using array_t = std::array<typename geometry::point_type<Segment>::type, 2>;

    using iterator = typename array_t::const_iterator;
    using const_iterator = typename array_t::const_iterator;

    /// Constructor accepting the segment to adapt
    explicit segment_view(Segment const& segment)
    {
        geometry::detail::assign_point_from_index<0>(segment, m_array[0]);
        geometry::detail::assign_point_from_index<1>(segment, m_array[1]);
    }

    const_iterator begin() const noexcept { return m_array.begin(); }
    const_iterator end() const noexcept { return m_array.end(); }

private:
    array_t m_array;
};

#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS

// All segment ranges can be handled as linestrings
namespace traits
{

template<typename Segment>
struct tag<segment_view<Segment> >
{
    typedef linestring_tag type;
};

}

#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_VIEWS_SEGMENT_VIEW_HPP


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

#include "exec/hbase-table-writer.h"

#include <boost/scoped_array.hpp>
#include <sstream>

#include "runtime/hbase-table-factory.h"
#include "util/jni-util.h"
#include "util/logging.h"
#include "exprs/expr.h"

using namespace boost;
using namespace std;

namespace impala {

jclass HBaseTableWriter::put_cl_ = NULL;
jclass HBaseTableWriter::list_cl_ = NULL;

jmethodID HBaseTableWriter::put_ctor_ = NULL;
jmethodID HBaseTableWriter::list_ctor_ = NULL;
jmethodID HBaseTableWriter::list_add_id_ = NULL;

jmethodID HBaseTableWriter::put_add_id_ = NULL;

HBaseTableWriter::HBaseTableWriter(RuntimeState* state,
                                   HBaseTableDescriptor* table_desc,
                                   const vector<Expr*>& output_exprs)
    : state_(state),
      table_desc_(table_desc),
      table_(NULL),
      output_exprs_(output_exprs),
      put_list_(NULL) {
};

Status HBaseTableWriter::Init(RuntimeState* state) {
  RETURN_IF_ERROR(state->htable_factory()->GetTable(table_desc_->name(),
      &table_));
  return Status::OK;
}

Status HBaseTableWriter::InitJNI() {
  JNIEnv* env = getJNIEnv();
  if (env == NULL) {
    return Status("Error getting JNIEnv.");
  }

  RETURN_IF_ERROR(
      JniUtil::GetGlobalClassRef(
          env, "org/apache/hadoop/hbase/client/Put", &put_cl_));
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
  put_ctor_ = env->GetMethodID(put_cl_, "<init>", "([B)V");
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
  put_add_id_ = env->GetMethodID(put_cl_, "add",
    "([B[B[B)Lorg/apache/hadoop/hbase/client/Put;");
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
  RETURN_IF_ERROR(
      JniUtil::GetGlobalClassRef(env, "java/util/ArrayList", &list_cl_));
  list_ctor_ = env->GetMethodID(list_cl_, "<init>", "(I)V");
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
  list_add_id_ = env->GetMethodID(list_cl_, "add", "(Ljava/lang/Object;)Z");
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());

  return Status::OK;
}

Status HBaseTableWriter::AppendRowBatch(RowBatch* batch) {
  JNIEnv* env = getJNIEnv();
  if (env == NULL) {
    return Status("Error getting JNIEnv.");
  }

  int limit = batch->num_rows();
  int num_cols = table_desc_->num_cols();
  if (num_cols < 2) {
    return Status("HBase tables must contain at least"
        " one column in addition to the row key.");
  }
  if (limit == 0) return Status::OK;

  // Create the array list.
  RETURN_IF_ERROR(CreatePutList(env, limit));

  scoped_array<jobject> puts(new jobject[limit]);
  // For every TupleRow in the row batch create a put, assign the row key,
  // and add all of the values generated from the expressions.
  for (int idx_batch = 0; idx_batch < limit; idx_batch++) {
    TupleRow* current_row = batch->GetRow(idx_batch);
    jobject put = NULL;
    for (int j = 0; j < num_cols; j++) {
      void* value = output_exprs_[j]->GetValue(current_row);
      if (value != NULL) {
        stringstream col_stringstream;
        output_exprs_[j]->PrintValue(value, &col_stringstream);
        if (j == 0) {
          DCHECK(put == NULL);
          RETURN_IF_ERROR(CreatePut(env, col_stringstream.str(), &put));

        } else {
          DCHECK(put != NULL) << "Put shouldn't be NULL for non-key cols.";

          const string value = col_stringstream.str();
          const pair<string, string>& col = table_desc_->cols()[j];

          jbyteArray cf_array;
          RETURN_IF_ERROR(CreateByteArray(env, col.first, &cf_array));

          jbyteArray qual_array;
          RETURN_IF_ERROR(CreateByteArray(env, col.second, &qual_array));

          jbyteArray val_array;
          RETURN_IF_ERROR(CreateByteArray(env, value, &val_array));

          env->CallObjectMethod(put, put_add_id_, cf_array, qual_array,
              val_array);
          RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());

          // Clean up the local references.
          env->DeleteLocalRef(cf_array);
          RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
          env->DeleteLocalRef(qual_array);
          RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
          env->DeleteLocalRef(val_array);
          RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
        }
      }
    }

    DCHECK(put != NULL);
    env->DeleteLocalRef(put);
    RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
  }

  // Send the array list to HTable.
  RETURN_IF_ERROR(table_->Put(put_list_));

  // Now clean things up.
  RETURN_IF_ERROR(CleanJNI());
  return Status::OK;
}

Status HBaseTableWriter::CleanJNI() {
  if (put_list_ == NULL) return Status::OK;

  JNIEnv* env = getJNIEnv();
  if (env == NULL) {
    return Status("Error getting JNIEnv.");
  }

  env->DeleteGlobalRef(put_list_);
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
  put_list_ = NULL;
  return Status::OK;
}

Status HBaseTableWriter::CreatePutList(JNIEnv* env, int num_puts) {
  jobject local_put_list = env->NewObject(list_cl_, list_ctor_, num_puts);
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());

  RETURN_IF_ERROR(JniUtil::LocalToGlobalRef(env, local_put_list, &put_list_));

  return Status::OK;
}

Status HBaseTableWriter::CreatePut(JNIEnv* env, const string& rk,
                                   jobject* put) {
  // Create the row key byte array.
  jbyteArray rk_array;
  RETURN_IF_ERROR(CreateByteArray(env, rk, &rk_array));

  (*put) = env->NewObject(put_cl_, put_ctor_, rk_array);
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());

  // Add the put to the list.
  env->CallObjectMethod(put_list_, list_add_id_, *put);
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());

  env->DeleteLocalRef(rk_array);
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());

  return Status::OK;
}

Status HBaseTableWriter::CreateByteArray(JNIEnv* env, const string& s,
                                         jbyteArray* j_array) {
  int s_len = static_cast<jsize>(s.size());
  // Create the byte array.
  (*j_array) = env->NewByteArray(s_len);
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());
  // Copy in the chars backing the std::string
  env->SetByteArrayRegion((*j_array), 0, s_len,
      reinterpret_cast<const jbyte*>(s.data()));
  RETURN_ERROR_IF_EXC(env, JniUtil::throwable_to_string_id());

  return Status::OK;
}

Status HBaseTableWriter::Close(RuntimeState* state) {
  // Guard against double closing.
  if (table_.get() != NULL) {
    RETURN_IF_ERROR(table_->Close());
    table_.reset(NULL);
  }

  // The jni should already have everything cleaned at this point
  // but try again just in case there was an error that caused
  // AppendRowBatch to exit out before calling CleanJNI.
  RETURN_IF_ERROR(CleanJNI());
  return Status::OK;
}

}  // namespace impala

ext: cc

max_stars_repo_name: wangxnhit/impala

max_issues_repo_name: boorad/impala

max_forks_repo_name: boorad/impala


text:
#include "OccupancyGrid/occgrid.hpp"
#include "OccupancyGrid/cvmat_serialization.h"
#include <opencv2/opencv.hpp>
#include <boost/format.hpp>

/// Override class to override is_occupied function so that it can copy the
/// ground truth map everytime a laser crosses a cell.
template<typename real_t, typename int_t>
class OccupancyGrid2DInverseSensor : public OccupancyGrid2D<real_t, int_t> {
  public:
    using OccupancyGrid2D<real_t, int_t>::og_;
    using OccupancyGrid2D<real_t, int_t>::cell_size_;
    using OccupancyGrid2D<real_t, int_t>::min_pt_;
    using OccupancyGrid2D<real_t, int_t>::FREE;
    int_t observed_manh_range_;
    cv::Vec<int_t, 2> robot_position_;
    cv::Mat_<real_t> log_odds_map_;
    const real_t LOG_ODDS_OCCUPIED;
    const real_t LOG_ODDS_FREE;

    OccupancyGrid2DInverseSensor(real_t min_x, real_t min_y, real_t cell_size_x, real_t
        cell_size_y, int_t ncells_x, int_t ncells_y) :
      OccupancyGrid2D<real_t, int_t>(min_x, min_y, cell_size_x, cell_size_y,
          ncells_x, ncells_y),
      observed_manh_range_(),
      robot_position_(),
      log_odds_map_(ncells_x, ncells_y, 0.0L),
      LOG_ODDS_OCCUPIED(1.3863),
      LOG_ODDS_FREE(-1.3863)
    {
    };

    void set_up_ray_trace(
        real_t px,
        real_t py,
        real_t ptheta,
        real_t observed_range) {
        robot_position_(0) =
            (int)floor((px - min_pt_(0)) / cell_size_(0));
        robot_position_(1) =
            (int)floor((py - min_pt_(1)) / cell_size_(1));
        real_t dx_abs = fabs(cos(ptheta));
        real_t dy_abs = fabs(sin(ptheta));
        real_t dmag = sqrt(dx_abs * dx_abs + dy_abs * dy_abs);
        observed_manh_range_ =
          floor(observed_range * dx_abs / dmag / cell_size_(0)) +
          floor(observed_range * dy_abs / dmag / cell_size_(1));
        //printf("-----------------\n");
    }

    inline int_t manh_distance(int_t i, int_t j) {
        return std::abs(i - robot_position_(0)) + std::abs(j - robot_position_(1));
    }

    virtual bool is_occupied(int_t i, int_t j) {
        uint8_t val = og_.ptr(i)[j];
        bool retval = (val != FREE);
        int_t d = manh_distance(i, j);
        // update step
        // printf("%d < %d\n", d, observed_manh_range_);
        log_odds_map_(i, j) +=
          (d < observed_manh_range_) ?  LOG_ODDS_FREE
          : (d == observed_manh_range_) ? LOG_ODDS_OCCUPIED
          : 0; // unknown
        return retval;
    }

    inline void show(int r) {
        cv::Mat vis;
        cv::exp(log_odds_map_, vis);
        vis = 1 / (1 + vis);
        vis *= 255;
        vis.convertTo(vis, CV_8U);
        cv::imshow("c", vis);
        //cv::imwrite((boost::format("out-%d.png") % r).str(), vis);
        cv::waitKey(1);
        cv::imwrite("/tmp/two_assumption_algo.png", vis);
    }
};

int main(int argc, char** argv) {
    if (argc != 4) {
        std::cout << "Sample Usage:" << std::endl;
        std::cout << "bin/two_assumption_alg Data/player_sim/laser_pose_all.bin Data/player_sim/laser_range_all.bin Data/player_sim/scan_angles_all.bin" << std::endl;
        exit(1);
    }
    cv::Mat laser_pose;
    loadMat(laser_pose, argv[1]);
    cv::Mat laser_ranges;
    loadMat(laser_ranges, argv[2]);
    cv::Mat scan_angles;
    loadMat(scan_angles, argv[3]);

    cv::Vec2d min_pt(-9, -9);
    cv::Vec2d range = -2 * min_pt;
    cv::Vec2i gridsize(100, 100);
    cv::Vec2d cellsize;
    cv::divide(range, gridsize, cellsize);
    //std::cout << cellsize(0) << cellsize(1) << std::endl;
    cv::Vec2i ncells;
    cv::divide(min_pt, cellsize, ncells, -2);

    //std::cout << ncells(0) << ncells(1) << std::endl;

    OccupancyGrid2DInverseSensor<double, int> map(
        min_pt(0),
        min_pt(1),
        cellsize(0),
        cellsize(1),
        ncells(0),
        ncells(1));

    double MAX_RANGE = 8;

    int r;
    for (r = 0; r < laser_pose.rows; r++) {
        double* pose = laser_pose.ptr<double>(r);
        double* ranges = laser_ranges.ptr<double>(r);
        double* angles = scan_angles.ptr<double>(r);
        double robot_angle = pose[2];
        for (int c = 0; c < scan_angles.cols; c++) {
            double total_angle = robot_angle + angles[c];
            cv::Vec2d final_pos;
            map.set_up_ray_trace(pose[0], pose[1], total_angle, ranges[c]);
            bool reflectance;
            map.ray_trace(pose[0], pose[1], total_angle, MAX_RANGE, final_pos, reflectance);
        }
    }
    map.show(r);
}

max_stars_repo_name: wecacuee/modern-occupancy-grid

max_issues_repo_name: wecacuee/modern-occupancy-grid

max_forks_repo_name: wecacuee/modern-occupancy-grid


text:
/* Copyright (c) 2017, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 *
 * All rights reserved.
 *
 * The Astrobee platform is 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
 *
 *     https://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.
 */

// ROS includes
#include <ros/ros.h>

#include <astrobee_gazebo/astrobee_gazebo.h>
#include <config_reader/config_reader.h>
#include <ff_msgs/CommandConstants.h>
#include <ff_msgs/CommandStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/point_cloud2_iterator.h>

#include <Eigen/Geometry>
#include <Eigen/Core>

// STL includes
#include <string>

namespace gazebo {
class GazeboSensorPluginHazCam : public FreeFlyerSensorPlugin {
 public:
  GazeboSensorPluginHazCam() :
    FreeFlyerSensorPlugin("pico_driver", "haz_cam", true), rate_(0.0), num_channels_(0) {
  }

  ~GazeboSensorPluginHazCam() {
    if (depth_update_) {
      #if GAZEBO_MAJOR_VERSION > 7
      depth_update_.reset();
      #else
      camera_->DisconnectNewRGBPointCloud(depth_update_);
      #endif
    }
    if (image_update_) {
      #if GAZEBO_MAJOR_VERSION > 7
      image_update_.reset();
      #else
      camera_->DisconnectNewImageFrame(image_update_);
      #endif
    }
  }

 protected:
  // Called when plugin is loaded into gazebo
  void LoadCallback(ros::NodeHandle *nh,
                    sensors::SensorPtr sensor, sdf::ElementPtr sdf) {
    // Get a link to the parent sensor
    sensor_ = std::dynamic_pointer_cast<sensors::DepthCameraSensor>(sensor);
    if (!sensor_) {
      gzerr << "GazeboSensorPluginHazCam requires a depth camera sensor.\n";
      return;
    }

    // Get a link to the depth camera
    camera_ = sensor_->DepthCamera();
    if (!camera_) {
      gzerr << "GazeboSensorPluginHazCam cannot get rendering object.\n";
      return;
    }

    // Look at the intensity component of the depth camera,
    // which we will call the "amplitude"
    // Check that we have a mono camera
    if (camera_->ImageFormat() != "L8")
      ROS_FATAL_STREAM("Camera format must be L8");

    // Create a publisher for the depth camera intensity
    std::string amplitude_topic =
      TOPIC_HARDWARE_PICOFLEXX_PREFIX
      + (std::string) TOPIC_HARDWARE_NAME_HAZ_CAM
      + "/extended/amplitude_int";
    pub_image_ = nh->advertise<sensor_msgs::Image>(amplitude_topic, 2);

    // Set image constants
    image_msg_.is_bigendian = false;
    image_msg_.header.frame_id = GetFrame();
    image_msg_.encoding = sensor_msgs::image_encodings::MONO8;

    // Create a publisher for the depth camera point cloud
    std::string point_topic = TOPIC_HARDWARE_PICOFLEXX_PREFIX
                            + (std::string) TOPIC_HARDWARE_NAME_HAZ_CAM
                            + (std::string) TOPIC_HARDWARE_PICOFLEXX_SUFFIX;
    pub_point_cloud_ = nh->advertise<sensor_msgs::PointCloud2>(point_topic, 1,
      boost::bind(&GazeboSensorPluginHazCam::ToggleCallback, this),
      boost::bind(&GazeboSensorPluginHazCam::ToggleCallback, this));
    pub_pose_ = nh->advertise<geometry_msgs::PoseStamped>(TOPIC_HAZ_CAM_SIM_POSE, 10);

    // Create a publisher for the intrinsics
    pub_info_ = nh->advertise<sensor_msgs::CameraInfo>(TOPIC_HAZ_CAM_SIM_INFO, 10);

    // Basic header information
    // Must set in <format>L8</format> in sensor_haz_cam.urdf.xacro
    // in order to get an output with 4 channels (x, y, z, intensity)
    num_channels_ = 4;
    point_cloud_msg_.header.frame_id = GetFrame();
    point_cloud_msg_.is_dense = true;
    point_cloud_msg_.is_bigendian = false;
    point_cloud_msg_.point_step = sizeof(float) * num_channels_;

    // Declare the striped memory layout.
    sensor_msgs::PointField field;
    field.name = "x";
    field.offset = 0 * sizeof(float);
    field.datatype = sensor_msgs::PointField::FLOAT32;
    field.count = 1;  // Number of ELEMENTS, not bytes
    point_cloud_msg_.fields.push_back(field);
    field.name = "y";
    field.offset = 1 * sizeof(float);
    field.datatype = sensor_msgs::PointField::FLOAT32;
    field.count = 1;  // Number of ELEMENTS, not bytes
    point_cloud_msg_.fields.push_back(field);
    field.name = "z";
    field.offset = 2 * sizeof(float);
    field.datatype = sensor_msgs::PointField::FLOAT32;
    field.count = 1;  // Number of ELEMENTS, not bytes
    point_cloud_msg_.fields.push_back(field);
    field.name = "intensity";  // for voxblox
    field.offset = 3 * sizeof(float);
    field.datatype = sensor_msgs::PointField::FLOAT32;
    field.count = 1;  // Number of ELEMENTS, not bytes
    point_cloud_msg_.fields.push_back(field);

    // Read configuration
    config_reader::ConfigReader config;
    config.AddFile("simulation/simulation.config");
    if (!config.ReadFiles()) {
      ROS_FATAL("Failed to read simulation config file.");
      return;
    }
    bool dos = true;
    if (!config.GetBool("disable_cameras_on_speedup", &dos))
      ROS_FATAL("Could not read the drawing_width parameter.");
    if (!config.GetReal("haz_cam_rate", &rate_))
      ROS_FATAL("Could not read the drawing_width parameter.");
    config.Close();

    // If we have a sped up simulation and we need to disable the camera
    double simulation_speed = 1.0;
    if (nh->getParam("/simulation_speed", simulation_speed))
      if (simulation_speed > 1.0 && dos) rate_ = 0.0;
  }

  // Only send measurements when extrinsics are available
  void OnExtrinsicsReceived(ros::NodeHandle *nh) {
    // Toggle if the camera is active or not
    ToggleCallback();

    // Listen to the point cloud
    depth_update_ = camera_->ConnectNewRGBPointCloud
      (boost::bind(&GazeboSensorPluginHazCam::PointCloudCallback, this, _1, _2, _3, _4, _5));
    image_update_ = camera_->ConnectNewImageFrame
      (boost::bind(&GazeboSensorPluginHazCam::ImageCallback, this, _1, _2, _3, _4, _5));
  }

  // Turn camera on or off based on topic subscription
  void ToggleCallback() {
    if (pub_point_cloud_.getNumSubscribers() > 0 && rate_ > 0) {
      sensor_->SetUpdateRate(rate_);
      sensor_->SetActive(true);
    } else {
      sensor_->SetUpdateRate(0.0001);
      sensor_->SetActive(false);
    }
  }

  // Publish the haz cam image
  void ImageCallback(const unsigned char * image_data, unsigned int width, unsigned height,
                     unsigned int len, const std::string & type) {
    // Publish the haz cam intrinsics
    ros::Time curr_time = ros::Time::now();
    info_msg_.header.frame_id = GetFrame();
    info_msg_.header.stamp = curr_time;  // it is very important to get the time right
    FillCameraInfo(sensor_->DepthCamera(), info_msg_);  // fill in from the camera pointer
    pub_info_.publish(info_msg_);

    // Record not the current time, but the time when the image was acquired
    image_msg_.header.stamp.sec = sensor_->LastMeasurementTime().sec;
    image_msg_.header.stamp.nsec = sensor_->LastMeasurementTime().nsec;
    image_msg_.height = camera_->ImageHeight();
    image_msg_.width = camera_->ImageWidth();
    image_msg_.step = image_msg_.width;
    image_msg_.data.resize(image_msg_.step * image_msg_.height);
    const uint8_t* data_start = reinterpret_cast<const uint8_t*>(image_data);
    std::copy(data_start, data_start + image_msg_.step * image_msg_.height,
              image_msg_.data.begin());
    pub_image_.publish(image_msg_);
  }

  // Publish the haz cam cloud and other data
  void PointCloudCallback(const float *depth_data, unsigned int width, unsigned int height,
    unsigned int len, const std::string & type) {
    // Quickly record the current time and current pose before doing other computations
    ros::Time curr_time = ros::Time::now();

    // Publish the haz cam pose
    #if GAZEBO_MAJOR_VERSION > 7
    Eigen::Affine3d sensor_to_world = SensorToWorld(GetModel()->WorldPose(), sensor_->Pose());
    #else
    Eigen::Affine3d sensor_to_world = SensorToWorld(GetModel()->GetWorldPose(), sensor_->Pose());
    #endif
    pose_msg_.header.frame_id = GetFrame();
    pose_msg_.header.stamp = curr_time;  // it is very important to get the time right
    pose_msg_.pose.position.x = sensor_to_world.translation().x();
    pose_msg_.pose.position.y = sensor_to_world.translation().y();
    pose_msg_.pose.position.z = sensor_to_world.translation().z();

    Eigen::Quaterniond q(sensor_to_world.rotation());
    pose_msg_.pose.orientation.w = q.w();
    pose_msg_.pose.orientation.x = q.x();
    pose_msg_.pose.orientation.y = q.y();
    pose_msg_.pose.orientation.z = q.z();
    pub_pose_.publish(pose_msg_);

    // Ensure that the cloud we publish has the timestamp for when
    // the data was actually measured.
    point_cloud_msg_.header.stamp.sec  = sensor_->LastMeasurementTime().sec;
    point_cloud_msg_.header.stamp.nsec = sensor_->LastMeasurementTime().nsec;

    // Populate the point cloud fields
    point_cloud_msg_.width = width;
    point_cloud_msg_.height = height;
    point_cloud_msg_.row_step = point_cloud_msg_.width * point_cloud_msg_.point_step;

    size_t num_bytes = point_cloud_msg_.row_step * point_cloud_msg_.height;
    size_t num_floats = num_bytes / sizeof(float);

    // Sanity checks
    if (num_channels_ != 4)
      ROS_FATAL("Expecting 4 channels.");
    if (num_floats != num_channels_ * width * height)
      ROS_FATAL("Expecting 4 floats per pixel.");

    // Copy the x, y, z values and the intensity. The latter is, for some reason, always 1.
    std::vector<float> cloud_data(num_floats);
    for (size_t i = 0; i < num_floats; i++)
      cloud_data[i] = depth_data[i];

    // Copy the correct intensity. NOTE(oalexan1): This intensity data
    // seems to be not fresh. The ImageCallback() above publishes the
    // correct intensity on a separate topic.
    const unsigned char * image_data = camera_->ImageData();

    if (!image_data) {
      // first frame of image data may not be received
      return;
    }
    for (size_t i = 0; i < num_floats / num_channels_; i++)
      cloud_data[num_channels_ * i + num_channels_ - 1] = static_cast<float>(image_data[i]);

    // Copy these to the point cloud
    point_cloud_msg_.data.resize(num_bytes);
    std::copy(reinterpret_cast<const uint8_t*>(&cloud_data[0]),              // input beg
              reinterpret_cast<const uint8_t*>(&cloud_data[0]) + num_bytes,  // input end
              point_cloud_msg_.data.begin());                                // destination

    pub_point_cloud_.publish(point_cloud_msg_);
  }

 private:
  // Published topics
  ros::Publisher pub_image_;
  ros::Publisher pub_point_cloud_;
  ros::Publisher pub_pose_;
  ros::Publisher pub_info_;

  // Sensor and camera pointers
  sensors::DepthCameraSensorPtr sensor_;
  rendering::DepthCameraPtr camera_;

  // Published messages
  sensor_msgs::PointCloud2 point_cloud_msg_;
  sensor_msgs::Image image_msg_;
  geometry_msgs::PoseStamped pose_msg_;
  sensor_msgs::CameraInfo info_msg_;

  event::ConnectionPtr depth_update_, image_update_;
  double rate_;
  int num_channels_;
};

GZ_REGISTER_SENSOR_PLUGIN(GazeboSensorPluginHazCam)

}   // namespace gazebo

max_stars_repo_name: jdekarske/astrobee

max_issues_repo_name: jdekarske/astrobee

max_forks_repo_name: jdekarske/astrobee


text:
// Copyright (c) 2009, Willow Garage, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Willow Garage, Inc. nor the names of its
//       contributors may be used to endorse or promote products derived from
//       this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "rosbag/query.h"
#include "rosbag/bag.h"

#include <boost/foreach.hpp>

#define foreach BOOST_FOREACH

using std::map;
using std::string;
using std::vector;
using std::multiset;

namespace rosbag {

// Query

Query::Query(boost::function<bool(ConnectionInfo const*)>& query, rs2rosinternal::Time const& start_time, rs2rosinternal::Time const& end_time)
	: query_(query), start_time_(start_time), end_time_(end_time)
{
}

boost::function<bool(ConnectionInfo const*)> const& Query::getQuery() const {
	return query_;
}

rs2rosinternal::Time const& Query::getStartTime() const { return start_time_; }
rs2rosinternal::Time const& Query::getEndTime()   const { return end_time_;   }

// TopicQuery

TopicQuery::TopicQuery(std::string const& topic) {
    topics_.push_back(topic);
}

TopicQuery::TopicQuery(std::vector<std::string> const& topics) : topics_(topics) { }

bool TopicQuery::operator()(ConnectionInfo const* info) const {
    foreach(string const& topic, topics_)
        if (topic == info->topic)
            return true;

    return false;
}

// TypeQuery

TypeQuery::TypeQuery(std::string const& type) {
    types_.push_back(type);
}

TypeQuery::TypeQuery(std::vector<std::string> const& types) : types_(types) { }

bool TypeQuery::operator()(ConnectionInfo const* info) const {
    foreach(string const& type, types_)
        if (type == info->datatype)
            return true;

    return false;
}

// BagQuery

BagQuery::BagQuery(Bag const* _bag, Query const& _query, uint32_t _bag_revision) : bag(_bag), query(_query), bag_revision(_bag_revision) {
}

// MessageRange

MessageRange::MessageRange(std::multiset<IndexEntry>::const_iterator const& _begin,
                           std::multiset<IndexEntry>::const_iterator const& _end,
                           ConnectionInfo const* _connection_info,
                           BagQuery const* _bag_query)
	: begin(_begin), end(_end), connection_info(_connection_info), bag_query(_bag_query)
{
}

// ViewIterHelper

ViewIterHelper::ViewIterHelper(std::multiset<IndexEntry>::const_iterator _iter, MessageRange const* _range)
	: iter(_iter), range(_range)
{
}

bool ViewIterHelperCompare::operator()(ViewIterHelper const& a, ViewIterHelper const& b) {
	return (a.iter)->time > (b.iter)->time;
}

} // namespace rosbag


text:
/**********************************************************************************/
/* This file is part of spla project                                              */
/* https://github.com/JetBrains-Research/spla                                     */
/**********************************************************************************/
/* MIT License                                                                    */
/*                                                                                */
/* Copyright (c) 2021 JetBrains-Research                                          */
/*                                                                                */
/* 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.                                                                      */
/**********************************************************************************/
#ifndef SPLA_SPLAREDUCE_HPP
#define SPLA_SPLAREDUCE_HPP

#include <boost/compute/algorithm/reduce.hpp>

#include <compute/metautil/SplaMetaUtil.hpp>

namespace spla {

    namespace detail {

        inline void InplaceReduce(const boost::compute::vector<unsigned char> &values,
                                  std::size_t valueByteSize,
                                  const std::string &functionBody,
                                  boost::compute::command_queue &queue) {
            std::size_t inputSize = values.size() / valueByteSize;
            if (inputSize < 2) {
                return;
            }

            const compute::context &context = queue.get_context();

            const std::size_t blockSize = 64;
            const std::size_t valuesPerThread = 8;
            std::size_t blockCount = inputSize / (blockSize * valuesPerThread);
            if (blockCount * blockSize * valuesPerThread != inputSize)
                blockCount++;

            compute::vector<unsigned char> output(blockCount * valueByteSize, context);

            compute::detail::meta_kernel k("inplace_reduce");
            size_t inputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, "input");
            size_t inputSizeArg = k.add_arg<const uint_>("input_size");
            size_t outputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, "output");
            size_t scratchArg = k.add_arg<unsigned char *>(compute::memory_object::local_memory, "scratch");

            ReduceOp reduceOp1(k, "inplace_reduce_reduce_1", functionBody, valueByteSize,
                               Visibility::Unspecified,
                               Visibility::Global,
                               Visibility::Unspecified);

            ReduceOp reduceOp2(k, "inplace_reduce_reduce_2", functionBody, valueByteSize,
                               Visibility::Local,
                               Visibility::Local,
                               Visibility::Unspecified);

            k << "const uint gid = get_global_id(0);\n"
              << "const uint lid = get_local_id(0);\n"
              << "const uint values_per_thread = " << uint_(valuesPerThread) << ";\n"
              << "const uint index = gid * values_per_thread;\n"
              << "if(index < input_size){\n"
              << DeclareVal{"sum", valueByteSize} << ";\n"
              << AssignVal{ValVar{"sum"}, ValArrItem{"input", "index", valueByteSize}, valueByteSize} << ";\n"
              << "for(uint i = 1; i < values_per_thread && (index + i) < input_size; i++) {\n"
              << reduceOp1.Apply(ValVar{"sum"}, ValArrItem{"input", "index+i", valueByteSize}, ValVar{"sum"}) << ";\n"
              << "}\n"
              << AssignVal{ValArrItem("scratch", "lid", valueByteSize), ValVar("sum"), valueByteSize} << ";\n"
              << "}\n"
              << "for(uint i = 1; i < get_local_size(0); i <<= 1){\n"
              << "    barrier(CLK_LOCAL_MEM_FENCE);\n"
              << "    uint mask = (i << 1) - 1;\n"
              << "    uint next_index = (gid + i) * values_per_thread;\n"
                 "    if((lid & mask) == 0 && next_index < input_size){\n"
              << reduceOp2.Apply(ValArrItem("scratch", "lid", valueByteSize), ValArrItem("scratch", "lid+i", valueByteSize), ValArrItem("scratch", "lid", valueByteSize))
              << "    }\n"
              << "}\n"
              << "if(lid == 0){\n"
              << AssignVal{ValArrItem("output", "get_group_id(0)", valueByteSize), ValArrItem("scratch", "0", valueByteSize), valueByteSize} << ";\n"
              << "}\n";

            const compute::buffer *inputBuffer = &values.get_buffer();
            const compute::buffer *outputBuffer = &output.get_buffer();

            compute::kernel kernel = k.compile(context);

            while (inputSize > 1) {
                kernel.set_arg(inputArg, *inputBuffer);
                kernel.set_arg(inputSizeArg, static_cast<uint_>(inputSize));
                kernel.set_arg(outputArg, *outputBuffer);
                kernel.set_arg(scratchArg, compute::local_buffer<unsigned char>(blockSize * valueByteSize));

                queue.enqueue_1d_range_kernel(kernel,
                                              0,
                                              blockCount * blockSize,
                                              blockSize);

                inputSize = static_cast<std::size_t>(std::ceil(static_cast<float>(inputSize) / (blockSize * valuesPerThread)));

                blockCount = inputSize / (blockSize * valuesPerThread);
                if (blockCount * blockSize * valuesPerThread != inputSize)
                    blockCount++;

                std::swap(inputBuffer, outputBuffer);
            }

            if (inputBuffer != &values.get_buffer()) {
                ::boost::compute::copy(output.begin(),
                                       output.begin() + static_cast<std::ptrdiff_t>(valueByteSize),
                                       values.begin(),
                                       queue);
            }
        }

        inline std::size_t Reduce(const boost::compute::vector<unsigned char> &values,
                                  std::size_t valueByteSize,
                                  boost::compute::vector<unsigned char> &result,
                                  std::size_t blockSize,
                                  const std::string &functionBody,
                                  boost::compute::command_queue &queue) {
            using namespace boost;

            const compute::context &context = queue.get_context();
            const std::size_t nValues = values.size() / valueByteSize;
            const std::size_t blockCount = nValues / 2 / blockSize;
            const auto totalBlockCount = static_cast<std::size_t>(
                    std::ceil(static_cast<float>(nValues) / 2.f / static_cast<float>(blockSize)));

            if (blockCount != 0) {
                compute::detail::meta_kernel k("block_reduce");
                std::size_t outputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, "output");
                std::size_t blockArg = k.add_arg<unsigned char *>(compute::memory_object::local_memory, "block");

                ReduceOp reduceOpGlobal(k, "block_reduce_reduce_global", functionBody, valueByteSize,
                                        Visibility::Global,
                                        Visibility::Global,
                                        Visibility::Local);
                ReduceOp reduceOpLocal(k, "block_reduce_reduce_local", functionBody, valueByteSize,
                                       Visibility::Local,
                                       Visibility::Local,
                                       Visibility::Unspecified);

                k << "const uint gid = get_global_id(0);\n"
                  << "const uint lid = get_local_id(0);\n"
                  << reduceOpGlobal.Apply(ValArrItem(values, "gid*2+0", valueByteSize, k),
                                          ValArrItem(values, "gid*2+1", valueByteSize, k),
                                          ValArrItem("block", "lid", valueByteSize))
                  << "for(uint i = 1; i < " << uint_(blockSize) << "; i <<= 1){\n"
                  << "    barrier(CLK_LOCAL_MEM_FENCE);\n"
                  << "    uint mask = (i << 1) - 1;\n"
                  << "    if((lid & mask) == 0){\n"
                  << reduceOpLocal.Apply(ValArrItem("block", "lid", valueByteSize),
                                         ValArrItem("block", "lid+i", valueByteSize),
                                         ValArrItem("block", "lid", valueByteSize))
                  << "    }\n"
                  << "}\n"
                  << "if(lid == 0)\n"
                  << AssignVal{ValArrItem{"output", "get_group_id(0)", valueByteSize},
                               ValArrItem{"block", "0", valueByteSize},
                               valueByteSize}
                  << ";\n";

                compute::kernel kernel = k.compile(context);
                kernel.set_arg(outputArg, result.get_buffer());
                kernel.set_arg(blockArg, compute::local_buffer<unsigned char>(blockSize * valueByteSize));

                queue.enqueue_1d_range_kernel(kernel,
                                              0,
                                              blockCount * blockSize,
                                              blockSize);
            }

            // serially reduce any leftovers
            if (blockCount * blockSize * 2 < nValues) {
                std::size_t lastBlockStart = blockCount * blockSize * 2;

                compute::detail::meta_kernel k("extra_serial_reduce");
                const std::size_t countArg = k.add_arg<uint_>("count");
                const std::size_t offsetArg = k.add_arg<uint_>("offset");
                const std::size_t outputArg = k.add_arg<unsigned char *>(compute::memory_object::global_memory, "output");
                const std::size_t outputOffsetArg = k.add_arg<uint_>("output_offset");

                ReduceOp reduceOp(k, "leftover_reduce_reduce", functionBody, valueByteSize,
                                  Visibility::Unspecified,
                                  Visibility::Global,
                                  Visibility::Unspecified);

                k << DeclareVal{"result", valueByteSize} << ";\n"
                  << AssignVal{ValVar{"result"}, ValArrItem{values, "offset", valueByteSize, k}, valueByteSize}
                  << "for(uint i = offset + 1; i < count; i++)\n"
                  << reduceOp.Apply(ValVar{"result"},
                                    ValArrItem(values, "i", valueByteSize, k),
                                    ValVar{"result"})
                  << AssignVal{ValArrItem{"output", "output_offset", valueByteSize},
                               ValVar{"result"},
                               valueByteSize}
                  << ";\n";

                compute::kernel kernel = k.compile(context);
                kernel.set_arg(countArg, static_cast<uint_>(nValues));
                kernel.set_arg(offsetArg, static_cast<uint_>(lastBlockStart));
                kernel.set_arg(outputArg, result.get_buffer());
                kernel.set_arg(outputOffsetArg, static_cast<uint_>(blockCount));

                queue.enqueue_task(kernel);
            }

            return totalBlockCount;
        }

        inline boost::compute::vector<unsigned char> BlockReduce(const boost::compute::vector<unsigned char> &values,
                                                                 std::size_t valueByteSize,
                                                                 std::size_t blockSize,
                                                                 const std::string &functionBody,
                                                                 boost::compute::command_queue &queue) {
            using namespace boost;

            const compute::context &ctx = queue.get_context();
            const std::size_t nValues = values.size() / valueByteSize;

            auto totalBlockCount = static_cast<std::size_t>(
                    std::ceil(static_cast<float>(nValues) / 2.f / static_cast<float>(blockSize)));
            compute::vector<unsigned char> resultVector(totalBlockCount * valueByteSize, ctx);

            Reduce(values, valueByteSize, resultVector, blockSize, functionBody, queue);

            return resultVector;
        }

        inline void GenericReduce(const boost::compute::vector<unsigned char> &values,
                                  std::size_t valueByteSize,
                                  boost::compute::vector<unsigned char> &result,
                                  const std::string &functionBody,
                                  boost::compute::command_queue &queue) {
            using namespace boost;

            const std::size_t blockSize = 256;

            compute::vector<unsigned char> results = BlockReduce(values, valueByteSize, blockSize, functionBody, queue);

            if (results.size() / valueByteSize > 1) {
                InplaceReduce(results,
                              valueByteSize,
                              functionBody,
                              queue);
            }

            compute::copy_n(results.begin(), valueByteSize, result.begin(), queue);
        }

    }// namespace detail

    inline boost::compute::vector<unsigned char> Reduce(const boost::compute::vector<unsigned char> &values,
                                                        std::size_t valueByteSize,
                                                        const std::string &reduceOp,
                                                        boost::compute::command_queue &queue) {
        using namespace boost;

        const compute::context &ctx = queue.get_context();
        boost::compute::vector<unsigned char> result(valueByteSize, ctx);
        compute::fill(result.begin(), result.end(), 0, queue);

        detail::GenericReduce(values, valueByteSize, result, reduceOp, queue);

        return result;
    }

}// namespace spla

#endif//SPLA_SPLAREDUCE_HPP

max_stars_repo_name: Glebanister/spla

max_issues_repo_name: Glebanister/spla

max_forks_repo_name: Glebanister/spla


text:
#pragma once
#include <functional>
#include <boost/asio/signal_set.hpp>

namespace fc
{
   /// Set a handler to process an IPC (inter process communication) signal.
   /// Handler will be called from ASIO thread.
   /// @return shared pointer to the signal_set that holds the handler
   std::shared_ptr<boost::asio::signal_set> set_signal_handler( std::function<void(int)> handler, int signal_num );
}

max_stars_repo_name: Revolution-Populi/fc

max_issues_repo_name: Revolution-Populi/fc

max_forks_repo_name: Revolution-Populi/fc


text:
// Copyright 2019, Beeri 15.  All rights reserved.
// Author: Roman Gershman (romange@gmail.com)
//

#include "util/http/https_client.h"

#include "base/logging.h"
#include "util/asio/io_context.h"

#ifdef BOOST_ASIO_SEPARATE_COMPILATION
#include <boost/asio/ssl/impl/src.hpp>
#endif

// libssl1.0.x has performance locking bugs that practically prevent scalable communication
// with ssl library. It seems that libssl1.1 fixes that. libssl-dev in 18.04 installs libssl1.1.
#if OPENSSL_VERSION_NUMBER < 0x10100000L
#warning Please update your libssl to libssl1.1 - install libssl-dev
#endif

namespace util {
namespace http {

using namespace boost;
using namespace std;
namespace h2 = beast::http;

namespace {
constexpr const char kPort[] = "443";

::boost::system::error_code SslConnect(SslStream* stream, unsigned ms) {
  system::error_code ec;
  for (unsigned i = 0; i < 2; ++i) {
    ec = stream->next_layer().ClientWaitToConnect(ms);
    if (ec) {
      VLOG(1) << "Error " << i << ": " << ec << "/" << ec.message() << " for socket "
              << stream->next_layer().native_handle();

      continue;
    }

    stream->handshake(asio::ssl::stream_base::client, ec);
    if (!ec) {
      auto* cipher = SSL_get_current_cipher(stream->native_handle());
      VLOG(1) << "SSL handshake success " << i << ", chosen " << SSL_CIPHER_get_name(cipher) << "/"
              << SSL_CIPHER_get_version(cipher);
    }
    return ec;
  }

  return ec;
}

}  // namespace

SslContextResult CreateClientSslContext(absl::string_view cert_string) {
  system::error_code ec;
  asio::ssl::context cntx{asio::ssl::context::tlsv12_client};
  cntx.set_options(boost::asio::ssl::context::default_workarounds |
                   boost::asio::ssl::context::no_compression | boost::asio::ssl::context::no_sslv2 |
                   boost::asio::ssl::context::no_sslv3 | boost::asio::ssl::context::no_tlsv1 |
                   boost::asio::ssl::context::no_tlsv1_1);
  cntx.set_verify_mode(asio::ssl::verify_peer, ec);
  if (ec) {
    return SslContextResult(ec);
  }
  cntx.add_certificate_authority(asio::buffer(cert_string.data(), cert_string.size()), ec);
  if (ec) {
    return SslContextResult(ec);
  }
  SSL_CTX* ssl_cntx = cntx.native_handle();

  long flags = SSL_CTX_get_options(ssl_cntx);
  flags |= SSL_OP_CIPHER_SERVER_PREFERENCE;
  SSL_CTX_set_options(ssl_cntx, flags);

  constexpr char kCiphers[] = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256";
  CHECK_EQ(1, SSL_CTX_set_cipher_list(ssl_cntx, kCiphers));
  CHECK_EQ(1, SSL_CTX_set_ecdh_auto(ssl_cntx, 1));

  return SslContextResult(std::move(cntx));
}

HttpsClient::HttpsClient(absl::string_view host, IoContext* context,
                         ::boost::asio::ssl::context* ssl_ctx)
    : io_context_(*context), ssl_cntx_(*ssl_ctx), host_name_(host) {
}

auto HttpsClient::Connect(unsigned msec) -> error_code {
  CHECK(io_context_.InContextThread());

  reconnect_msec_ = msec;

  return InitSslClient();
}

auto HttpsClient::InitSslClient() -> error_code {
  VLOG(2) << "Https::InitSslClient " << reconnect_needed_;

  error_code ec;
  if (!reconnect_needed_)
    return ec;
  client_.reset(new SslStream(FiberSyncSocket{host_name_, kPort, &io_context_}, ssl_cntx_));
  client_->next_layer().set_keep_alive(true);

  if (SSL_set_tlsext_host_name(client_->native_handle(), host_name_.c_str()) != 1) {
    char buf[128];
    ERR_error_string_n(::ERR_peek_last_error(), buf, sizeof(buf));

    LOG(FATAL) << "Could not set hostname: " << buf;
  }

  ec = SslConnect(client_.get(), reconnect_msec_);
  if (!ec) {
    reconnect_needed_ = false;
  } else {
    VLOG(1) << "Error connecting " << ec << ", socket " << client_->next_layer().native_handle();
  }
  return ec;
}

auto HttpsClient::DrainResponse(h2::response_parser<h2::buffer_body>* parser) -> error_code {
  constexpr size_t kBufSize = 1 << 16;
  std::unique_ptr<uint8_t[]> buf(new uint8_t[kBufSize]);
  auto& body = parser->get().body();
  error_code ec;
  size_t sz = 0;

  // Drain pending response completely to allow reusing the current connection.
  VLOG(1) << "parser: " << parser->got_some();
  while (!parser->is_done()) {
    body.data = buf.get();
    body.size = kBufSize;
    size_t raw_bytes = h2::read(*client_, tmp_buffer_, *parser, ec);
    if (ec && ec != h2::error::need_buffer) {
      VLOG(1) << "Error " << ec << "/" << ec.message();
      return ec;
    }
    sz += raw_bytes;

    VLOG(1) << "DrainResp: " << raw_bytes << "/" << body.size;
  }
  VLOG_IF(1, sz > 0) << "Drained " << sz << " bytes";

  return error_code{};
}

bool HttpsClient::HandleWriteError(const error_code& ec) {
  if (!ec)
    return true;

  LOG(WARNING) << "Write returned error " << ec << "/" << ec.message();
  reconnect_needed_ = true;

  return false;
}

}  // namespace http
}  // namespace util

max_stars_repo_name: dendisuhubdy/gaia

max_issues_repo_name: dendisuhubdy/gaia

max_forks_repo_name: dendisuhubdy/gaia


text:
#ifndef FPGA_CAFFE_TEST_TEST_FPGA_CAFFE_MAIN_HPP_
#define FPGA_CAFFE_TEST_TEST_FPGA_CAFFE_MAIN_HPP_

#include <glog/logging.h>
#include <gtest/gtest.h>
#include <cfloat>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <CL/opencl.h>
#include <fstream>
#include <string>
#include "time.h"
#include "fpga_caffe/layer.hpp"
#include "fpga_caffe/cpfp.hpp"

using std::cout;
using std::endl;

template <typename TypeParam>
class OCLDeviceTest : public ::testing::Test {
 public:
  typedef typename TypeParam::Dtype Dtype;
 protected:
  virtual ~OCLDeviceTest() {}
};

template <typename TypeParam>
struct OCLDevice {
  typedef TypeParam Dtype;
};

typedef ::testing::Types<OCLDevice<float> >TestOCLDtypesAndDevices;

class OCLUtil {
 public:
  OCLUtil(std::string xclbin, std::string xclkernel);
  void Setup();
  void Setup_Platform();
  cl_uint oclNumPlatforms;
  std::vector<cl_platform_id> oclPlatform;
  cl_device_id oclDevices;
  cl_context oclContext;
  cl_command_queue oclCommandQueue;
  cl_kernel oclKernel;
  std::string xcl_name;
  std::string kernel;
};

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

void ref_relu_layer(std::vector<float>& output);

void ref_pool_layer_hwcn(std::vector<float> input, std::vector<float>& output,
    std::vector<short>& sw_relu_vals, kernel_params params);

void ref_backward_pool_layer_hwcn(std::vector<float> input,
    std::vector<float>& output, std::vector<short> relu_vals,
    kernel_params params);

void ref_fc_layer(std::vector<float> input, std::vector<float> weights,
    std::vector<float> bias, std::vector<float>& output, kernel_params params);

void ref_backward_fc_layer(std::vector<float> input,
    std::vector<float> weights, std::vector<float>& output,
    kernel_params params);

void ref_conv_layer_hwcn(std::vector<float> input, std::vector<float> weights,
    std::vector<float> bias, std::vector<float>& output, kernel_params params,
    bool wino = false);

void ref_backward_conv_layer_hwcn(std::vector<float> input,
    std::vector<float> weights, std::vector<float>& output,
    kernel_params params);

void fillVector(std::vector<float>& input, float beg, float end);

void fillVectorCPFP(std::vector<float>& input, float beg, float end);

void copyVector(std::vector<float> input, std::vector<float>& output, int xsize,
    int xsize_pad);

void copyWeights(std::vector<float> w_input, std::vector<float>& w_output,
    int ksize, int padsize, kernel_params params);

void toCPFP(std::vector<float> input, std::vector<cpfp>& output);

void toFloat(std::vector<cpfp> input, std::vector<float>& output);

bool checkEQ(float expected, float result, float epsilon, float absError);

#endif  // FPGA_CAFFE_TEST_TEST_FPGA_CAFFE_MAIN_HPP_


text:
// Copyright 2020 Andreytorix

#include <boostf.hpp>
std::vector<Broker> Broker::brokerVector;
int main(int n, char* arr[]) {
    std::string path_to_ftp;
    if (n != 1){
    path_to_ftp = arr[1];
    } else {
    path_to_ftp = boost::filesystem::current_path().string();
    }
    if (boost::filesystem::exists(path_to_ftp)) {
    std::cout << path_to_ftp << std::endl;
    std::vector<std::string> vec;
    vec = recdir(path_to_ftp);
    std::cout << "number of files found " + vec.back() << std::endl;
    vec.pop_back();
    show_vector(vec);
    show_broker(Broker::ListBrokersv());
    } else {
    std::cout << "dir not exist" << std::endl;
    }
}


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 DBAUI_TYPEINFO_HXX
#define DBAUI_TYPEINFO_HXX

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNSEARCH_HPP_
#include <com/sun/star/sdbc/ColumnSearch.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#include <boost/shared_ptr.hpp>
#include <map>

namespace dbaui
{
//========================================================================
// Anhand dieser Ids werden die sprachabhaengigen ::rtl::OUString aus der Resource geholt
const sal_uInt16 TYPE_UNKNOWN	= 0;
const sal_uInt16 TYPE_TEXT		= 1;
const sal_uInt16 TYPE_NUMERIC	= 2;
const sal_uInt16 TYPE_DATETIME	= 3;
const sal_uInt16 TYPE_DATE		= 4;
const sal_uInt16 TYPE_TIME		= 5;
const sal_uInt16 TYPE_BOOL		= 6;
const sal_uInt16 TYPE_CURRENCY	= 7;
const sal_uInt16 TYPE_MEMO		= 8;
const sal_uInt16 TYPE_COUNTER	= 9;
const sal_uInt16 TYPE_IMAGE		= 10;
const sal_uInt16 TYPE_CHAR		= 11;
const sal_uInt16 TYPE_DECIMAL	= 12;
const sal_uInt16 TYPE_BINARY	= 13;
const sal_uInt16 TYPE_VARBINARY	= 14;
const sal_uInt16 TYPE_BIGINT	= 15;
const sal_uInt16 TYPE_DOUBLE	= 16;
const sal_uInt16 TYPE_FLOAT		= 17;
const sal_uInt16 TYPE_REAL		= 18;
const sal_uInt16 TYPE_INTEGER	= 19;
const sal_uInt16 TYPE_SMALLINT	= 20;
const sal_uInt16 TYPE_TINYINT	= 21;
const sal_uInt16 TYPE_SQLNULL	= 22;
const sal_uInt16 TYPE_OBJECT	= 23;
const sal_uInt16 TYPE_DISTINCT	= 24;
const sal_uInt16 TYPE_STRUCT	= 25;
const sal_uInt16 TYPE_ARRAY		= 26;
const sal_uInt16 TYPE_BLOB		= 27;
const sal_uInt16 TYPE_CLOB		= 28;
const sal_uInt16 TYPE_REF		= 29;
const sal_uInt16 TYPE_OTHER		= 30;
const sal_uInt16 TYPE_BIT		= 31;

	class OTypeInfo
	{
	public:
		::rtl::OUString	aUIName;		// the name which is the user see (a combination of resource text and aTypeName)
		::rtl::OUString	aTypeName;		// Name des Types in der Datenbank
		::rtl::OUString	aLiteralPrefix; // Prefix zum Quoten
		::rtl::OUString	aLiteralSuffix; // Suffix zum Quoten
		::rtl::OUString	aCreateParams;  // Parameter zum Erstellen
		::rtl::OUString	aLocalTypeName;

		sal_Int32		nPrecision;		// Laenge des Types
        sal_Int32		nType;			// Datenbanktyp

		sal_Int16		nMaximumScale;	// Nachkommastellen
		sal_Int16		nMinimumScale;  // Min Nachkommastellen

		sal_Int16		nSearchType;	// kann nach dem Typen gesucht werden

		sal_Bool		bCurrency		: 1,	// Waehrung
						bAutoIncrement	: 1,	// Ist es ein automatisch incrementierendes Feld
						bNullable		: 1,	// Kann das Feld NULL annehmen
						bCaseSensitive	: 1,	// Ist der Type Casesensitive
						bUnsigned		: 1;	// Ist der Type Unsigned

		OTypeInfo()
                :nPrecision(0)
				,nType(::com::sun::star::sdbc::DataType::OTHER)
				,nMaximumScale(0)
				,nMinimumScale(0)
				,nSearchType(::com::sun::star::sdbc::ColumnSearch::FULL)
				,bCurrency(sal_False)
				,bAutoIncrement(sal_False)
				,bNullable(sal_True)
				,bCaseSensitive(sal_False)
				,bUnsigned(sal_False)
		{}
		sal_Bool operator == (const OTypeInfo& lh) const { return lh.nType == nType; }
		sal_Bool operator != (const OTypeInfo& lh) const { return lh.nType != nType; }
		inline ::rtl::OUString	getDBName() const { return aTypeName; }

	};

	typedef ::boost::shared_ptr<OTypeInfo>			TOTypeInfoSP;
	typedef ::std::multimap<sal_Int32,TOTypeInfoSP>	OTypeInfoMap;
	/** return the most suitable typeinfo for a requested type
		@param	_rTypeInfo		contains a map of type to typeinfo
		@param	_nType			the requested type
		@param	_sTypeName		the typename
		@param	_sCreateParams	the create params
		@param	_nPrecision		the precision
		@param	_nScale			the	scale
		@param	_bAutoIncrement	if it is a auto increment
		@param	_brForceToType	true when type was found which has some differenes
	*/
	TOTypeInfoSP getTypeInfoFromType(const OTypeInfoMap& _rTypeInfo,
							   sal_Int32 _nType,
							   const ::rtl::OUString& _sTypeName,
							   const ::rtl::OUString& _sCreateParams,
							   sal_Int32 _nPrecision,
							   sal_Int32 _nScale,
							   sal_Bool _bAutoIncrement,
							   sal_Bool& _brForceToType);
}

#endif // DBAUI_TYPEINFO_HXX

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/*
 *          Copyright Andrey Semashev 2007 - 2015.
 * 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)
 */
/*!
 * \file   filter_parser.cpp
 * \author Andrey Semashev
 * \date   31.03.2008
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
 */

#ifndef BOOST_LOG_WITHOUT_SETTINGS_PARSERS

#include <cstddef>
#include <map>
#include <stack>
#include <string>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <boost/assert.hpp>
#include <boost/none.hpp>
#include <boost/move/core.hpp>
#include <boost/move/utility.hpp>
#include <boost/optional/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/bind/bind_function_object.hpp>
#include <boost/phoenix/operator/logical.hpp>
#include <boost/log/detail/singleton.hpp>
#include <boost/log/exceptions.hpp>
#include <boost/log/utility/setup/filter_parser.hpp>
#if !defined(BOOST_LOG_NO_THREADS)
#include <boost/log/detail/locks.hpp>
#include <boost/log/detail/light_rw_mutex.hpp>
#endif // !defined(BOOST_LOG_NO_THREADS)
#include "parser_utils.hpp"
#if !defined(BOOST_LOG_WITHOUT_DEFAULT_FACTORIES)
#include "default_filter_factory.hpp"
#endif
#include "spirit_encoding.hpp"
#include <boost/log/detail/header.hpp>

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

BOOST_LOG_ANONYMOUS_NAMESPACE {

//! Filter factories repository
template< typename CharT >
struct filters_repository :
    public log::aux::lazy_singleton< filters_repository< CharT > >
{
    typedef CharT char_type;
    typedef log::aux::lazy_singleton< filters_repository< char_type > > base_type;
    typedef std::basic_string< char_type > string_type;
    typedef filter_factory< char_type > filter_factory_type;

    //! Attribute name ordering predicate
    struct attribute_name_order
    {
        typedef bool result_type;
        result_type operator() (attribute_name const& left, attribute_name const& right) const
        {
            return left.id() < right.id();
        }
    };

    typedef std::map< attribute_name, shared_ptr< filter_factory_type >, attribute_name_order > factories_map;

#if !defined(BOOST_LOG_BROKEN_FRIEND_TEMPLATE_SPECIALIZATIONS)
    friend class log::aux::lazy_singleton< filters_repository< char_type > >;
#else
    friend class base_type;
#endif

#if !defined(BOOST_LOG_NO_THREADS)
    //! Synchronization mutex
    mutable log::aux::light_rw_mutex m_Mutex;
#endif
    //! The map of filter factories
    factories_map m_Map;
#if !defined(BOOST_LOG_WITHOUT_DEFAULT_FACTORIES)
    //! Default factory
    mutable aux::default_filter_factory< char_type > m_DefaultFactory;
#endif

    //! The method returns the filter factory for the specified attribute name
    filter_factory_type& get_factory(attribute_name const& name) const
    {
        typename factories_map::const_iterator it = m_Map.find(name);
        if (it != m_Map.end())
        {
            return *it->second;
        }
        else
        {
#if !defined(BOOST_LOG_WITHOUT_DEFAULT_FACTORIES)
            return m_DefaultFactory;
#else
            BOOST_LOG_THROW_DESCR(setup_error, "No filter factory registered for attribute " + name.string());
#endif
        }
    }

private:
    filters_repository()
    {
    }
};

//! Filter parser
template< typename CharT >
class filter_parser
{
private:
    typedef CharT char_type;
    typedef const char_type* iterator_type;
    typedef typename log::aux::encoding< char_type >::type encoding;
    typedef log::aux::encoding_specific< encoding > encoding_specific;
    typedef std::basic_string< char_type > string_type;
    typedef log::aux::char_constants< char_type > constants;
    typedef filter_factory< char_type > filter_factory_type;

    typedef filter (filter_factory_type::*comparison_relation_handler_t)(attribute_name const&, string_type const&);

private:
    //! Parsed attribute name
    mutable attribute_name m_AttributeName;
    //! The second operand of a relation
    mutable optional< string_type > m_Operand;
    //! Comparison relation handler
    comparison_relation_handler_t m_ComparisonRelation;
    //! The custom relation string
    mutable string_type m_CustomRelation;

    //! Filter subexpressions as they are parsed
    mutable std::stack< filter > m_Subexpressions;

public:
    //! Constructor
    filter_parser() :
        m_ComparisonRelation(NULL)
    {
    }

    //! The method returns the constructed filter
    filter get_filter()
    {
        if (m_Subexpressions.empty())
            return filter();
        return boost::move(m_Subexpressions.top());
    }

    //! The pethod parses filter from the string
    void parse(iterator_type& begin, iterator_type end, unsigned int depth = 0)
    {
        typedef void (filter_parser::*logical_op_t)();
        logical_op_t logical_op = NULL;
        iterator_type p = constants::trim_spaces_left(begin, end);
        while (p != end)
        {
            // Parse subexpression
            parse_subexpression(p, end, depth);
            if (logical_op)
            {
                // This was the right-hand subexpression. Compose the two top subexpressions into a single filter.
                (this->*logical_op)();
                logical_op = NULL;
            }

            p = constants::trim_spaces_left(p, end);
            if (p != end)
            {
                char_type c = *p;
                iterator_type next = p + 1;
                if (c == constants::char_paren_bracket_right)
                {
                    // The subexpression has ended
                    if (depth == 0)
                        BOOST_LOG_THROW_DESCR(parse_error, "Invalid filter definition: unmatched closing parenthesis");

                    p = next;
                    --depth;
                    break;
                }
                else if (c == constants::char_and || scan_keyword(p, end, next, constants::and_keyword()))
                {
                    logical_op = &filter_parser::on_and;
                }
                else if (c == constants::char_or || scan_keyword(p, end, next, constants::or_keyword()))
                {
                    logical_op = &filter_parser::on_or;
                }
                else
                {
                    BOOST_LOG_THROW_DESCR(parse_error, "Invalid filter definition: unexpected character encountered");
                }

                p = constants::trim_spaces_left(next, end);
            }
            else
                break;
        }

        if (logical_op)
        {
            BOOST_LOG_THROW_DESCR(parse_error, "Invalid filter definition: logical operation without the right-hand subexpression");
        }

        if (p == end && depth > 0)
        {
            BOOST_LOG_THROW_DESCR(parse_error, "Invalid filter definition: unterminated parenthesis");
        }

        begin = p;
    }

private:
    //! The method parses a single subexpression
    void parse_subexpression(iterator_type& begin, iterator_type end, unsigned int depth)
    {
        bool negated = false, negation_present = false, done = false;
        iterator_type p = begin;

        while (p != end)
        {
            char_type c = *p;
            iterator_type next = p + 1;
            if (c == constants::char_percent)
            {
                // We found an attribute placeholder
                iterator_type start = constants::trim_spaces_left(next, end);
                p = constants::scan_attr_placeholder(start, end);
                if (p == end)
                    BOOST_LOG_THROW_DESCR(parse_error, "Invalid attribute placeholder in the filter string");

                on_attribute_name(start, p);

                p = constants::trim_spaces_left(p, end);
                if (p == end || *p != constants::char_percent)
                    BOOST_LOG_THROW_DESCR(parse_error, "Invalid attribute placeholder in the filter string");

                // Skip the closing char_percent
                p = constants::trim_spaces_left(++p, end);

                // If the filter has negation operator, do not expect a relation (i.e. "!%attr% > 1" is not valid because "!%attr%" is interpreted as an attribute presence test)
                if (!negation_present)
                    p = parse_relation(p, end);
                else
                    on_relation_complete();
            }
            else if (c == constants::char_exclamation || scan_keyword(p, end, next, constants::not_keyword()))
            {
                // We found negation operation. Parse the subexpression to be negated.
                negated ^= true;
                negation_present = true;
                p = constants::trim_spaces_left(next, end);
                continue;
            }
            else if (c == constants::char_paren_bracket_left)
            {
                // We found a nested subexpression
                parse(next, end, depth + 1);
                p = next;
            }
            else
            {
                BOOST_LOG_THROW_DESCR(parse_error, "Invalid filter definition: unexpected character");
            }

            if (negated)
                on_negation();

            done = true;

            break;
        }

        if (negation_present && !done)
        {
            // This would happen if a filter consists of a single '!'
            BOOST_LOG_THROW_DESCR(parse_error, "Filter parsing error: negation operator applied to nothingness");
        }

        begin = p;
    }

    //! Parses filtering relation
    iterator_type parse_relation(iterator_type begin, iterator_type end)
    {
        iterator_type p = begin;
        if (p != end)
        {
            iterator_type next = p;
            if (scan_keyword(p, end, next, constants::equal_keyword()))
                m_ComparisonRelation = &filter_factory_type::on_equality_relation;
            else if (scan_keyword(p, end, next, constants::not_equal_keyword()))
                m_ComparisonRelation = &filter_factory_type::on_inequality_relation;
            else if (scan_keyword(p, end, next, constants::greater_keyword()))
                m_ComparisonRelation = &filter_factory_type::on_greater_relation;
            else if (scan_keyword(p, end, next, constants::less_keyword()))
                m_ComparisonRelation = &filter_factory_type::on_less_relation;
            else if (scan_keyword(p, end, next, constants::greater_or_equal_keyword()))
                m_ComparisonRelation = &filter_factory_type::on_greater_or_equal_relation;
            else if (scan_keyword(p, end, next, constants::less_or_equal_keyword()))
                m_ComparisonRelation = &filter_factory_type::on_less_or_equal_relation;
            else
            {
                // Check for custom relation
                while (next != end && (encoding::isalnum(*next) || *next == constants::char_underline))
                    ++next;
                if (p == next)
                    goto DoneL;
                m_CustomRelation.assign(p, next);
            }

            // We have parsed a relation operator, there must be an operand
            next = constants::trim_spaces_left(next, end);
            string_type operand;
            p = constants::parse_operand(next, end, operand);
            if (next == p)
                BOOST_LOG_THROW_DESCR(parse_error, "Missing operand for a relation in the filter string");

            m_Operand = boost::in_place(operand);
        }

    DoneL:
        // The relation can be as simple as a sole attribute placeholder (which means that only attribute presence has to be checked).
        // So regardless how we get here, the relation is parsed completely.
        on_relation_complete();

        return p;
    }

    //! Checks if the string contains a keyword
    static bool scan_keyword(iterator_type begin, iterator_type end, iterator_type& next, iterator_type keyword)
    {
        for (iterator_type p = begin; p != end; ++p, ++keyword)
        {
            char_type c1 = *p, c2 = *keyword;
            if (c2 == 0)
            {
                if (encoding::isspace(c1))
                {
                    next = p;
                    return true;
                }
                break;
            }
            if (c1 != c2)
                break;
        }

        return false;
    }

    //! The attribute name handler
    void on_attribute_name(iterator_type begin, iterator_type end)
    {
        if (begin == end)
            BOOST_LOG_THROW_DESCR(parse_error, "Empty attribute name encountered");
        m_AttributeName = attribute_name(log::aux::to_narrow(string_type(begin, end)));
    }

    //! The comparison relation handler
    void on_relation_complete()
    {
        if (!!m_AttributeName)
        {
            filters_repository< char_type > const& repo = filters_repository< char_type >::get();
            filter_factory_type& factory = repo.get_factory(m_AttributeName);

            if (!!m_Operand)
            {
                if (!!m_ComparisonRelation)
                {
                    m_Subexpressions.push((factory.*m_ComparisonRelation)(m_AttributeName, m_Operand.get()));
                    m_ComparisonRelation = NULL;
                }
                else if (!m_CustomRelation.empty())
                {
                    m_Subexpressions.push(factory.on_custom_relation(m_AttributeName, m_CustomRelation, m_Operand.get()));
                    m_CustomRelation.clear();
                }
                else
                {
                    // This should never happen
                    BOOST_ASSERT_MSG(false, "Filter parser internal error: the attribute name or subexpression operation is not set while trying to construct a relation");
                    BOOST_LOG_THROW_DESCR(parse_error, "Filter parser internal error: the attribute name or subexpression operation is not set while trying to construct a subexpression");
                }

                m_Operand = none;
            }
            else
            {
                // This branch is taken if the relation is a single attribute name, which is recognized as the attribute presence check
                BOOST_ASSERT_MSG(!m_ComparisonRelation && m_CustomRelation.empty(), "Filter parser internal error: the relation operation is set while operand is not");
                m_Subexpressions.push(factory.on_exists_test(m_AttributeName));
            }

            m_AttributeName = attribute_name();
        }
        else
        {
            // This should never happen
            BOOST_ASSERT_MSG(false, "Filter parser internal error: the attribute name is not set while trying to construct a relation");
            BOOST_LOG_THROW_DESCR(parse_error, "Filter parser internal error: the attribute name is not set while trying to construct a relation");
        }
    }

    //! The negation operation handler
    void on_negation()
    {
        if (!m_Subexpressions.empty())
        {
            m_Subexpressions.top() = !phoenix::bind(m_Subexpressions.top(), phoenix::placeholders::_1);
        }
        else
        {
            // This would happen if a filter consists of "!()"
            BOOST_LOG_THROW_DESCR(parse_error, "Filter parsing error: negation operator applied to an empty subexpression");
        }
    }

    //! The logical AND operation handler
    void on_and()
    {
        if (!m_Subexpressions.empty())
        {
            filter right = boost::move(m_Subexpressions.top());
            m_Subexpressions.pop();
            if (!m_Subexpressions.empty())
            {
                filter const& left = m_Subexpressions.top();
                m_Subexpressions.top() = phoenix::bind(left, phoenix::placeholders::_1) && phoenix::bind(right, phoenix::placeholders::_1);
                return;
            }
        }

        // This should never happen
        BOOST_LOG_THROW_DESCR(parse_error, "Filter parser internal error: the subexpression is not set while trying to construct a filter");
    }

    //! The logical OR operation handler
    void on_or()
    {
        if (!m_Subexpressions.empty())
        {
            filter right = boost::move(m_Subexpressions.top());
            m_Subexpressions.pop();
            if (!m_Subexpressions.empty())
            {
                filter const& left = m_Subexpressions.top();
                m_Subexpressions.top() = phoenix::bind(left, phoenix::placeholders::_1) || phoenix::bind(right, phoenix::placeholders::_1);
                return;
            }
        }

        // This should never happen
        BOOST_LOG_THROW_DESCR(parse_error, "Filter parser internal error: the subexpression is not set while trying to construct a filter");
    }

    //  Assignment and copying are prohibited
    BOOST_DELETED_FUNCTION(filter_parser(filter_parser const&))
    BOOST_DELETED_FUNCTION(filter_parser& operator= (filter_parser const&))
};

} // namespace

//! The function registers a filter factory object for the specified attribute name
template< typename CharT >
BOOST_LOG_SETUP_API void register_filter_factory(attribute_name const& name, shared_ptr< filter_factory< CharT > > const& factory)
{
    BOOST_ASSERT(!!name);
    BOOST_ASSERT(!!factory);

    filters_repository< CharT >& repo = filters_repository< CharT >::get();

    BOOST_LOG_EXPR_IF_MT(log::aux::exclusive_lock_guard< log::aux::light_rw_mutex > lock(repo.m_Mutex);)
    repo.m_Map[name] = factory;
}

//! The function parses a filter from the string
template< typename CharT >
BOOST_LOG_SETUP_API filter parse_filter(const CharT* begin, const CharT* end)
{
    typedef CharT char_type;
    typedef log::aux::encoding_specific< typename log::aux::encoding< char_type >::type > encoding_specific;

    filter_parser< char_type > parser;
    const char_type* p = begin;

    BOOST_LOG_EXPR_IF_MT(filters_repository< CharT >& repo = filters_repository< CharT >::get();)
    BOOST_LOG_EXPR_IF_MT(log::aux::shared_lock_guard< log::aux::light_rw_mutex > lock(repo.m_Mutex);)

    parser.parse(p, end);

    return parser.get_filter();
}

#ifdef BOOST_LOG_USE_CHAR

template BOOST_LOG_SETUP_API
void register_filter_factory< char >(attribute_name const& name, shared_ptr< filter_factory< char > > const& factory);
template BOOST_LOG_SETUP_API
filter parse_filter< char >(const char* begin, const char* end);

#endif // BOOST_LOG_USE_CHAR

#ifdef BOOST_LOG_USE_WCHAR_T

template BOOST_LOG_SETUP_API
void register_filter_factory< wchar_t >(attribute_name const& name, shared_ptr< filter_factory< wchar_t > > const& factory);
template BOOST_LOG_SETUP_API
filter parse_filter< wchar_t >(const wchar_t* begin, const wchar_t* end);

#endif // BOOST_LOG_USE_WCHAR_T

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>

#endif // BOOST_LOG_WITHOUT_SETTINGS_PARSERS


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

#include <iostream>
#include <utility>
#include <cmath>
#include <boost/numeric/mtl/mtl.hpp>

using namespace std;

template <typename Matrix>
void init(Matrix& A)
{
    A= 0.0;
    mtl::mat::inserter<Matrix>  ins(A);

    ins[0][1] << 3;  ins[1][4] << 7; ins[0][0] << 1; ins[4][4] << 17;
    ins[2][3] << -2; ins[2][4] << 5; ins[4][0] << 2; ins[4][1] <<  3;
    ins[3][2] << 4;
}

template <typename Coll>
void test(Coll& coll, const char* name)
{
    cout << "\n" << name << " =\n" << coll << "\n";

    Coll E(coll), F(coll); F=0;
    E= hessenberg(coll);
    F=tril(E,-2);
    std::cout<< "Hessenberg=\n" << E << "\n";
    std::cout<< "triu=\n" << F << "\n";

    MTL_THROW_IF(one_norm(F)>0.000004, mtl::runtime_error("No Hessenberg-Form"));
    F=extract_householder_hessenberg(coll);
    std::cout<< "extract_householder_hessenberg=\n" << F << "\n";
    F=extract_hessenberg(coll);
    std::cout<< "extract_hessenberg=\n" << F << "\n";
    F=householder_hessenberg(coll);
    std::cout<< "householder_hessenberg=\n" << F << "\n";
    F=hessenberg_factors(coll);
    std::cout<< "hessenberg_factors=\n" << F << "\n";
    //      F=hessenberg_q(coll);
    //      std::cout<< "hessenberg_q=\n" << F << "\n";
}

int main(int, char**)
{
    using namespace mtl;

    dense2D<double>       A(5, 5);
    init(A);
    compressed2D<double>  B(5, 5);
    init(B);

    test(A, "dense matrix");
//      test(B, "sparse matrix");  // TODO sparse Form

    return 0;
}


text:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

template<typename T, typename E>
bool contain(const T &c, E e)
{
    return std::find(c.begin(), c.end(), e) != c.end();
}

int main (void) {
    std::fstream file("input.txt");
    int counter = 0;
    for (std::string line; getline(file, line);) {
        std::vector<std::string> output;
        boost::split(output, line.substr(line.find('|') + 2), boost::is_any_of(" "));
        counter += std::count_if(output.begin(), output.end(),
        [sizes = {2, 3, 4, 7}](std::string s) { return contain(sizes, s.size()); });
    }
    std::cout << counter << '\n';
}