<commit_before>//---------------------------------------------------------------------------//
/*!
 * \file tstSamplingTools.cpp
 * \author Stuart R. Slattery
 * \brief Boost random number generator unit tests.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#include <cassert>

#include <Chimera_RNGTraits.hpp>
#include <Chimera_BoostRNG.hpp>
#include <Chimera_SamplingTools.hpp>

#include <boost/random/mersenne_twister.hpp>

#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_Tuple.hpp>

#include <Tpetra_Vector.hpp>

//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, uniform_stratify_sample_test )
{
    using namespace Chimera;

    // Setup parallel distribution.
    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();
    int comm_size = comm->getSize();

    // Setup linear operator distribution.
    int local_num_rows = 10;
    int global_num_rows = local_num_rows*comm_size;
    Teuchos::RCP<const Tpetra::Map<int> > row_map =
	Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );

    // Build the PDF in parallel.
    double pdf_val = 1.0;
    Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
	Tpetra::createVector<double,int>( row_map );
    pdf->putScalar( pdf_val );

    // Stratify sample the PDF.
    int num_histories = global_num_rows;
    Teuchos::ArrayRCP<int> histories_per_local_state =
	SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );

    // Check the sampling.
    TEST_ASSERT( histories_per_local_state.size() == local_num_rows );

    Teuchos::ArrayRCP<int>::const_iterator history_it;
    for ( history_it = histories_per_local_state.begin();
	  history_it != histories_per_local_state.end();
	  ++history_it )
    {
	TEST_ASSERT( *history_it == 1 );
    }
}

//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, nonuniform_stratify_sample_test )
{
    using namespace Chimera;

    // Setup parallel distribution.
    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();
    int comm_rank = comm->getRank();
    int comm_size = comm->getSize();

    // Setup linear operator distribution.
    int local_num_rows = 10;
    int global_num_rows = local_num_rows*comm_size;
    Teuchos::RCP<const Tpetra::Map<int> > row_map =
	Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );

    // Build the PDF in parallel.
    double pdf_val = comm_rank + 1.0;
    Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
	Tpetra::createVector<double,int>( row_map );
    pdf->putScalar( pdf_val );

    // Stratify sample the PDF.
    int num_histories = 0;
    for ( int i = 0; i < comm_size; ++i )
    {
	num_histories += local_num_rows*(i+1);
    }

    Teuchos::ArrayRCP<int> histories_per_local_state =
	SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );

    // Check the sampling.
    TEST_ASSERT( histories_per_local_state.size() == local_num_rows );

    Teuchos::ArrayRCP<int>::const_iterator history_it;
    for ( history_it = histories_per_local_state.begin();
	  history_it != histories_per_local_state.end();
	  ++history_it )
    {
	TEST_ASSERT( *history_it == pdf_val );
    }
}

//---------------------------------------------------------------------------//
// end tstBoostRNG.cpp
//---------------------------------------------------------------------------//

<commit_msg>adding local pdf sampling test. not finished yet<commit_after>//---------------------------------------------------------------------------//
/*!
 * \file tstSamplingTools.cpp
 * \author Stuart R. Slattery
 * \brief Boost random number generator unit tests.
 */
//---------------------------------------------------------------------------//

#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#include <cassert>

#include <Chimera_RNGTraits.hpp>
#include <Chimera_BoostRNG.hpp>
#include <Chimera_SamplingTools.hpp>

#include <boost/random/mersenne_twister.hpp>

#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_Tuple.hpp>

#include <Tpetra_Vector.hpp>

//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, uniform_stratify_sample_test )
{
    using namespace Chimera;

    // Setup parallel distribution.
    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();
    int comm_size = comm->getSize();

    // Setup linear operator distribution.
    int local_num_rows = 10;
    int global_num_rows = local_num_rows*comm_size;
    Teuchos::RCP<const Tpetra::Map<int> > row_map =
	Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );

    // Build the PDF in parallel.
    double pdf_val = 1.0;
    Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
	Tpetra::createVector<double,int>( row_map );
    pdf->putScalar( pdf_val );

    // Stratify sample the PDF.
    int num_histories = global_num_rows;
    Teuchos::ArrayRCP<int> histories_per_local_state =
	SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );

    // Check the sampling.
    TEST_ASSERT( histories_per_local_state.size() == local_num_rows );

    Teuchos::ArrayRCP<int>::const_iterator history_it;
    for ( history_it = histories_per_local_state.begin();
	  history_it != histories_per_local_state.end();
	  ++history_it )
    {
	TEST_ASSERT( *history_it == 1 );
    }
}

//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, nonuniform_stratify_sample_test )
{
    using namespace Chimera;

    // Setup parallel distribution.
    Teuchos::RCP<const Teuchos::Comm<int> > comm =
	Teuchos::DefaultComm<int>::getComm();
    int comm_rank = comm->getRank();
    int comm_size = comm->getSize();

    // Setup linear operator distribution.
    int local_num_rows = 10;
    int global_num_rows = local_num_rows*comm_size;
    Teuchos::RCP<const Tpetra::Map<int> > row_map =
	Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );

    // Build the PDF in parallel.
    double pdf_val = comm_rank + 1.0;
    Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
	Tpetra::createVector<double,int>( row_map );
    pdf->putScalar( pdf_val );

    // Stratify sample the PDF.
    int num_histories = 0;
    for ( int i = 0; i < comm_size; ++i )
    {
	num_histories += local_num_rows*(i+1);
    }

    Teuchos::ArrayRCP<int> histories_per_local_state =
	SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );

    // Check the sampling.
    TEST_ASSERT( histories_per_local_state.size() == local_num_rows );

    Teuchos::ArrayRCP<int>::const_iterator history_it;
    for ( history_it = histories_per_local_state.begin();
	  history_it != histories_per_local_state.end();
	  ++history_it )
    {
	TEST_ASSERT( *history_it == pdf_val );
    }
}

//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, uniform_local_pdf_sample_test )
{

}

//---------------------------------------------------------------------------//
// end tstBoostRNG.cpp
//---------------------------------------------------------------------------//

<|endoftext|>


<commit_before>/*
 Copyright (c) 2012 The WebM project authors. All Rights Reserved.

 Use of this source code is governed by a BSD-style license
 that can be found in the LICENSE file in the root of the source
 tree. An additional intellectual property rights grant can be found
 in the file PATENTS.  All contributing project authors may
 be found in the AUTHORS file in the root of the source tree.
 */

#include <cstdio>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
#include "test/md5_helper.h"
extern "C" {
#include "vpx_mem/vpx_mem.h"
}

namespace {
class TileIndependenceTest : public ::libvpx_test::EncoderTest,
    public ::libvpx_test::CodecTestWithParam<int> {
 protected:
  TileIndependenceTest() : EncoderTest(GET_PARAM(0)), n_tiles_(GET_PARAM(1)),
      md5_fw_order_(), md5_inv_order_() {
    init_flags_ = VPX_CODEC_USE_PSNR;
    vpx_codec_dec_cfg_t cfg;
    cfg.w = 704;
    cfg.h = 144;
    cfg.threads = 1;
    fw_dec_ = codec_->CreateDecoder(cfg, 0);
    inv_dec_ = codec_->CreateDecoder(cfg, 0);
    inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
  }

  virtual ~TileIndependenceTest() {
    delete fw_dec_;
    delete inv_dec_;
  }

  virtual void SetUp() {
    InitializeConfig();
    SetMode(libvpx_test::kTwoPassGood);
  }

  virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
                                  libvpx_test::Encoder *encoder) {
    if (video->frame() == 1) {
      encoder->Control(VP9E_SET_TILE_COLUMNS, n_tiles_);
    }
  }

  void UpdateMD5(::libvpx_test::Decoder *dec, const vpx_codec_cx_pkt_t *pkt,
                 ::libvpx_test::MD5 *md5) {
    dec->DecodeFrame((uint8_t *) pkt->data.frame.buf, pkt->data.frame.sz);
    const vpx_image_t *img = dec->GetDxData().Next();
    md5->Add(img);
  }

  virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
    UpdateMD5(fw_dec_, pkt, &md5_fw_order_);
    UpdateMD5(inv_dec_, pkt, &md5_inv_order_);
  }

 private:
  int n_tiles_;
 protected:
  ::libvpx_test::MD5 md5_fw_order_, md5_inv_order_;
  ::libvpx_test::Decoder *fw_dec_, *inv_dec_;
};

// run an encode with 2 or 4 tiles, and do the decode both in normal and
// inverted tile ordering. Ensure that the MD5 of the output in both cases
// is identical. If so, tiles are considered independent and the test passes.
TEST_P(TileIndependenceTest, MD5Match) {
  const vpx_rational timebase = { 33333333, 1000000000 };
  cfg_.g_timebase = timebase;
  cfg_.rc_target_bitrate = 500;
  cfg_.g_lag_in_frames = 25;
  cfg_.rc_end_usage = VPX_VBR;

  libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 704, 144,
                                     timebase.den, timebase.num, 0, 30);
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  const char *md5_fw_str  = md5_fw_order_.Get();
  const char *md5_inv_str = md5_inv_order_.Get();

  // could use ASSERT_EQ(!memcmp(.., .., 16) here, but this gives nicer
  // output if it fails. Not sure if it's helpful since it's really just
  // a MD5...
  ASSERT_STREQ(md5_fw_str, md5_inv_str);
}

VP9_INSTANTIATE_TEST_CASE(TileIndependenceTest,
                          ::testing::Range(0, 2, 1));

}  // namespace
<commit_msg>test/tile_independence_test: check decode return<commit_after>/*
 Copyright (c) 2012 The WebM project authors. All Rights Reserved.

 Use of this source code is governed by a BSD-style license
 that can be found in the LICENSE file in the root of the source
 tree. An additional intellectual property rights grant can be found
 in the file PATENTS.  All contributing project authors may
 be found in the AUTHORS file in the root of the source tree.
 */

#include <cstdio>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
#include "test/md5_helper.h"
extern "C" {
#include "vpx_mem/vpx_mem.h"
}

namespace {
class TileIndependenceTest : public ::libvpx_test::EncoderTest,
    public ::libvpx_test::CodecTestWithParam<int> {
 protected:
  TileIndependenceTest() : EncoderTest(GET_PARAM(0)), n_tiles_(GET_PARAM(1)),
      md5_fw_order_(), md5_inv_order_() {
    init_flags_ = VPX_CODEC_USE_PSNR;
    vpx_codec_dec_cfg_t cfg;
    cfg.w = 704;
    cfg.h = 144;
    cfg.threads = 1;
    fw_dec_ = codec_->CreateDecoder(cfg, 0);
    inv_dec_ = codec_->CreateDecoder(cfg, 0);
    inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
  }

  virtual ~TileIndependenceTest() {
    delete fw_dec_;
    delete inv_dec_;
  }

  virtual void SetUp() {
    InitializeConfig();
    SetMode(libvpx_test::kTwoPassGood);
  }

  virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
                                  libvpx_test::Encoder *encoder) {
    if (video->frame() == 1) {
      encoder->Control(VP9E_SET_TILE_COLUMNS, n_tiles_);
    }
  }

  void UpdateMD5(::libvpx_test::Decoder *dec, const vpx_codec_cx_pkt_t *pkt,
                 ::libvpx_test::MD5 *md5) {
    const vpx_codec_err_t res =
        dec->DecodeFrame(reinterpret_cast<uint8_t*>(pkt->data.frame.buf),
                         pkt->data.frame.sz);
    if (res != VPX_CODEC_OK) {
      abort_ = true;
      ASSERT_EQ(VPX_CODEC_OK, res);
    }
    const vpx_image_t *img = dec->GetDxData().Next();
    md5->Add(img);
  }

  virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
    UpdateMD5(fw_dec_, pkt, &md5_fw_order_);
    UpdateMD5(inv_dec_, pkt, &md5_inv_order_);
  }

 private:
  int n_tiles_;
 protected:
  ::libvpx_test::MD5 md5_fw_order_, md5_inv_order_;
  ::libvpx_test::Decoder *fw_dec_, *inv_dec_;
};

// run an encode with 2 or 4 tiles, and do the decode both in normal and
// inverted tile ordering. Ensure that the MD5 of the output in both cases
// is identical. If so, tiles are considered independent and the test passes.
TEST_P(TileIndependenceTest, MD5Match) {
  const vpx_rational timebase = { 33333333, 1000000000 };
  cfg_.g_timebase = timebase;
  cfg_.rc_target_bitrate = 500;
  cfg_.g_lag_in_frames = 25;
  cfg_.rc_end_usage = VPX_VBR;

  libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 704, 144,
                                     timebase.den, timebase.num, 0, 30);
  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));

  const char *md5_fw_str  = md5_fw_order_.Get();
  const char *md5_inv_str = md5_inv_order_.Get();

  // could use ASSERT_EQ(!memcmp(.., .., 16) here, but this gives nicer
  // output if it fails. Not sure if it's helpful since it's really just
  // a MD5...
  ASSERT_STREQ(md5_fw_str, md5_inv_str);
}

VP9_INSTANTIATE_TEST_CASE(TileIndependenceTest,
                          ::testing::Range(0, 2, 1));

}  // namespace
<|endoftext|>


<commit_before>// RUN: %clang_tsan %s -pie -fPIE -o %t && %run setarch x86_64 -R %t

int main() {
  return 0;
}
<commit_msg>tsan: fix pie_no_aslr test<commit_after>// RUN: %clang_tsan %s -pie -fPIE -o %t && %run setarch x86_64 -R %t
// REQUIRES: x86_64-target-arch

int main() {
  return 0;
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <ros/console.h>

#include <math.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int8.h>
#include <std_msgs/UInt16MultiArray.h>
#include <std_msgs/Int32MultiArray.h>

// Customized message
#include <drv_msgs/target_info.h>

#include <stdio.h>

#include "targetselecter.h"
#include "facelistener.h"
#include "targetlistener.h"

using namespace std;
using namespace std_msgs;

/* Global params */
// Feedback
// 0:not working, 1:working, 2:failed, 3:finished with success
string param_vision_feedback = "/comm/param/feedback/vision/overall";
// 0:wandering, 1:searching, 2:tracking
string param_vision_feedback_mode = "/comm/param/feedback/vision/mode";
// 0:no search, 1:found, -1:current not found. -2:around not found
string param_vision_feedback_search = "/comm/param/feedback/vision/search";
// 0:no track, 1:tracking, -1:lost
string param_vision_feedback_track = "/comm/param/feedback/vision/track";
// 0:no grasp, 1:found location, -1:can't find location
string param_vision_feedback_grasp = "/comm/param/feedback/vision/grasp";
// 0:no face recognize, 1:found faces, -1:failed to recognize
string param_vision_feedback_face = "/comm/param/feedback/vision/face";
// vision shared
// true:switch on to execute tasks, false:switch off and run in wander mode
string param_vision_shared_switch = "/comm/param/shared/vision/switch";

bool centralSwitch_ = true; // main switch

// Target properties
bool targetSetTemp_ = false;
string param_target_label = "/vision/target/label";
enum TargetType{t_null, t_onTable, t_onGround, t_onHead, t_onHand};
string targetTypeName[5] = {"in air", "on the table", "on the ground",
                            "on the face", "in the hand"};
int tgtType_ = t_null;
string param_target_type = "/status/target/type";

string param_comm_target_set =   "/comm/param/control/target/is_set";
string param_comm_target_label = "/comm/param/control/target/label";

// Target status control
string targetLabel_ = "";
bool isTargetSet_ = false;

// Target status feedback
bool foundTarget_ = false;

// Publish servo initial position
ros::Publisher servoPub_;
bool servo_initialized_ = false;

// Servo initial angles
int pitchAngle_ = 70;
int yawAngle_ = 90;
// Range of servo angles
int pitch_min_ = 60;
int pitch_max_ = 140;
int yaw_min_ = 0;
int yaw_max_ = 180;
// The rosparam that store pitch and yaw values
string param_servo_pitch = "/status/servo/pitch";
string param_servo_yaw = "/status/servo/yaw";

// Mode control params
enum ModeType{m_wander, m_search, m_track};
int modeType_ = m_wander;
int modeTypeTemp_ = -1;
string modeName[3] = {"wandering", "searching", "tracking"};
string param_running_mode = "/status/running_mode";
ros::Publisher drvPubMode_; // vision system mode publisher

// General infomation publisher
ros::Publisher drvPubInfo_;

void resetStatus()
{
  // Reset global params
  ros::param::set(param_vision_feedback, 0);
  ros::param::set(param_vision_feedback_search, 0);
  ros::param::set(param_vision_feedback_track, 0);
  ros::param::set(param_vision_feedback_grasp, 0);
  ros::param::set(param_vision_feedback_face, 0);

  tgtType_ = t_null;
  targetLabel_ = "";

  isTargetSet_ = false;
  foundTarget_ = false;

  modeType_ = m_wander;

  ros::param::set(param_comm_target_set, false);
  ros::param::set(param_comm_target_label, "");
}

/* This function is used for servo initialization and
 * publishing servo angles received from cellphone
 */
void pubServo(int pitch_angle, int yaw_angle, int power)
{
  std_msgs::UInt16MultiArray array;
  array.data.push_back(pitch_angle);
  array.data.push_back(yaw_angle);
  array.data.push_back(50 * power);
  servoPub_.publish(array);
}

void pubInfo(string info)
{
  ROS_INFO(info.c_str());
  String msg;
  msg.data = info;
  drvPubInfo_.publish(msg);
}

void teleOpCallback(const Int32MultiArrayConstPtr &msg)
{
  if (msg->data.empty() || (msg->data[0] == 0 && msg->data[1] == 0))
    return;

  int pitch_temp = pitchAngle_ + msg->data[0];
  if (pitch_temp < pitch_min_ || pitch_temp > pitch_max_)
    return;
  else
    pitchAngle_ = pitch_temp;

  int yaw_temp = yawAngle_ - msg->data[1];
  if (yaw_temp < yaw_min_ || yaw_temp > yaw_max_)
    return;
  else
    yawAngle_ = yaw_temp;

  int power = 2;
  pubServo(pitchAngle_, yawAngle_, power);
}

void servoCallback(const UInt16MultiArrayConstPtr &msg)
{
  // This callback should always active
  pitchAngle_ = msg->data[0];
  yawAngle_ = msg->data[1];

  ros::param::set(param_servo_pitch, pitchAngle_);
  ros::param::set(param_servo_yaw, yawAngle_);
}

void searchCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_search) {
    if (msg->data == -1) {
      pubInfo("Search around didn't get target, continue searching...");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_search, -2);
      ros::param::set(param_vision_feedback, 2);
    }
    else if (msg->data == 0) {
      pubInfo("Currently didn't find target, continue searching...");
      ros::param::set(param_vision_feedback_search, -1);
      ros::param::set(param_vision_feedback, 1);
      foundTarget_ = false;
    }
    else {
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_search, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void trackCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO("Track report: Target lost!");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_track, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO_THROTTLE(7, "Track report: Tracking...");
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_track, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void graspCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO_THROTTLE(3, "Grasp report: Failed.");
      ros::param::set(param_vision_feedback_grasp, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else if (msg->data == 1) {
      ROS_INFO_THROTTLE(3, "Grasp report: Reaching to the target...");
      ros::param::set(param_vision_feedback_grasp, 1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO("Grasp report: Target in reach.");
      // Reset if grasping has been performed
      resetStatus();
    }
  }
}

void faceRecognizeCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_wander) {
    if (!msg->data) {
      pubInfo("Face report: Failed.");
      ros::param::set(param_vision_feedback_face, -1);
      ros::param::set(param_vision_feedback, 2);
    }
    else {
      pubInfo("Face report: Successed.");
      ros::param::set(param_vision_feedback_face, 1);
      ros::param::set(param_vision_feedback, 3);
    }
  }
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "drv_brain");

  ros::NodeHandle nh;
  ros::NodeHandle pnh("~");

  pnh.getParam("pitch_min", pitch_min_);
  pnh.getParam("pitch_max", pitch_max_);
  pnh.getParam("yaw_min", yaw_min_);
  pnh.getParam("yaw_max", yaw_max_);

  servoPub_ = nh.advertise<UInt16MultiArray>("servo", 1, true);
  // For publishing mode info
  drvPubMode_ = nh.advertise<String>("/comm/msg/vision/mode", 1);
  drvPubInfo_ = nh.advertise<String>("/comm/msg/vision/info", 1);

  // Don't change the order without reason
  ros::Subscriber sub_servo_ctrl = nh.subscribe<Int32MultiArray>("/joy_teleop/servo", 1, teleOpCallback);
  ros::Subscriber sub_servo = nh.subscribe<UInt16MultiArray>("servo", 1, servoCallback);
  //ros::Subscriber sub_tgt = nh.subscribe<drv_msgs::target_info>("recognize/target", 1, targetCallback);
  ros::Subscriber sub_sh = nh.subscribe<Int8>("status/search/feedback", 1, searchCallback);
  ros::Subscriber sub_tk = nh.subscribe<Bool>("status/track/feedback", 1, trackCallback);
  ros::Subscriber sub_gp = nh.subscribe<Int8>("status/grasp/feedback", 1, graspCallback);
  ros::Subscriber sub_fr = nh.subscribe<Bool>("status/face/feedback", 1, faceRecognizeCallback);

  FaceListener fl;
  TargetListener tl;
  TargetSelecter ts;

  resetStatus();

  pubInfo("Deep Robot Vision system initialized!");

  while (ros::ok()) {
    // Main on/off control
    if (ros::param::has(param_vision_shared_switch)) {
      bool temp = true;
      ros::param::get(param_vision_shared_switch, temp);
      if (temp)
        ROS_WARN_COND(!centralSwitch_, "Central switch is ON.");
      centralSwitch_ = temp;
    }

    if (!centralSwitch_) {
      ROS_WARN_THROTTLE(9, "Central switch is OFF.");
      resetStatus();
      continue;
    }

    // Initialize servo position
    if (!servo_initialized_) {
      pubServo(90, 90, 1);
      servo_initialized_ = true;
      ROS_INFO("Servo reset.");
    }

    // Get feedback to determine whether target were found
    ros::spinOnce();

    // Get target label if the params were set
    tl.getTargetStatus(isTargetSet_, targetLabel_);
    ros::param::set(param_target_label, targetLabel_);

    if (isTargetSet_ != targetSetTemp_) {
      if (isTargetSet_)
        pubInfo("Target set to be '" + targetLabel_ + "'.");
      else {
        pubInfo("Target cancelled.");
        resetStatus();
      }
      targetSetTemp_ = isTargetSet_;
    }

    // If user selects target on cellphone, publish the target
    ts.publishOnceIfTargetSelected(isTargetSet_, foundTarget_);

    // Mode selection, notice that modeType_ should only be set by central control
    if (isTargetSet_) {
      if (foundTarget_) {
        // No matter whether the target is searched or selected by user,
        // as long as it was found, track it.
        modeType_ = m_track;
      }
      else {
        if (targetLabel_ == "user selected object") {
          // If the target is selected by user but no more been found,
          // which means tracking has lost it, reset.
          pubInfo("Tracking did not follow.");
          resetStatus();
        }
        else
          modeType_ = m_search;
      }
    }
    else {
      modeType_ = m_wander;
      fl.isNeedRecognizeFace(); // Only recognize face in wander mode
    }

    // Set running mode
    ros::param::set(param_running_mode, modeType_);

    if (modeType_ != modeTypeTemp_) {
      String mode_msg;
      mode_msg.data = modeName[modeType_];
      drvPubMode_.publish(mode_msg);
      ROS_INFO("Current mode: %s.", modeName[modeType_].c_str());
      modeTypeTemp_ = modeType_;
      if (modeType_ == m_wander) {
        // Reset head pose
        servo_initialized_ = false;
      }
    }
  }

  return 0;
}

<commit_msg>adjust speed<commit_after>#include <ros/ros.h>
#include <ros/console.h>

#include <math.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int8.h>
#include <std_msgs/UInt16MultiArray.h>
#include <std_msgs/Int32MultiArray.h>

// Customized message
#include <drv_msgs/target_info.h>

#include <stdio.h>

#include "targetselecter.h"
#include "facelistener.h"
#include "targetlistener.h"

using namespace std;
using namespace std_msgs;

/* Global params */
// Feedback
// 0:not working, 1:working, 2:failed, 3:finished with success
string param_vision_feedback = "/comm/param/feedback/vision/overall";
// 0:wandering, 1:searching, 2:tracking
string param_vision_feedback_mode = "/comm/param/feedback/vision/mode";
// 0:no search, 1:found, -1:current not found. -2:around not found
string param_vision_feedback_search = "/comm/param/feedback/vision/search";
// 0:no track, 1:tracking, -1:lost
string param_vision_feedback_track = "/comm/param/feedback/vision/track";
// 0:no grasp, 1:found location, -1:can't find location
string param_vision_feedback_grasp = "/comm/param/feedback/vision/grasp";
// 0:no face recognize, 1:found faces, -1:failed to recognize
string param_vision_feedback_face = "/comm/param/feedback/vision/face";
// vision shared
// true:switch on to execute tasks, false:switch off and run in wander mode
string param_vision_shared_switch = "/comm/param/shared/vision/switch";

bool centralSwitch_ = true; // main switch

// Target properties
bool targetSetTemp_ = false;
string param_target_label = "/vision/target/label";
enum TargetType{t_null, t_onTable, t_onGround, t_onHead, t_onHand};
string targetTypeName[5] = {"in air", "on the table", "on the ground",
                            "on the face", "in the hand"};
int tgtType_ = t_null;
string param_target_type = "/status/target/type";

string param_comm_target_set =   "/comm/param/control/target/is_set";
string param_comm_target_label = "/comm/param/control/target/label";

// Target status control
string targetLabel_ = "";
bool isTargetSet_ = false;

// Target status feedback
bool foundTarget_ = false;

// Publish servo initial position
ros::Publisher servoPub_;
bool servo_initialized_ = false;

// Servo initial angles
int pitchAngle_ = 70;
int yawAngle_ = 90;
// Range of servo angles
int pitch_min_ = 60;
int pitch_max_ = 140;
int yaw_min_ = 0;
int yaw_max_ = 180;
// The rosparam that store pitch and yaw values
string param_servo_pitch = "/status/servo/pitch";
string param_servo_yaw = "/status/servo/yaw";

// Mode control params
enum ModeType{m_wander, m_search, m_track};
int modeType_ = m_wander;
int modeTypeTemp_ = -1;
string modeName[3] = {"wandering", "searching", "tracking"};
string param_running_mode = "/status/running_mode";
ros::Publisher drvPubMode_; // vision system mode publisher

// General infomation publisher
ros::Publisher drvPubInfo_;

void resetStatus()
{
  // Reset global params
  ros::param::set(param_vision_feedback, 0);
  ros::param::set(param_vision_feedback_search, 0);
  ros::param::set(param_vision_feedback_track, 0);
  ros::param::set(param_vision_feedback_grasp, 0);
  ros::param::set(param_vision_feedback_face, 0);

  tgtType_ = t_null;
  targetLabel_ = "";

  isTargetSet_ = false;
  foundTarget_ = false;

  modeType_ = m_wander;

  ros::param::set(param_comm_target_set, false);
  ros::param::set(param_comm_target_label, "");
}

/* This function is used for servo initialization and
 * publishing servo angles received from cellphone
 */
void pubServo(int pitch_angle, int yaw_angle, int power)
{
  std_msgs::UInt16MultiArray array;
  array.data.push_back(pitch_angle);
  array.data.push_back(yaw_angle);
  array.data.push_back(20 * power);
  servoPub_.publish(array);
}

void pubInfo(string info)
{
  ROS_INFO(info.c_str());
  String msg;
  msg.data = info;
  drvPubInfo_.publish(msg);
}

void teleOpCallback(const Int32MultiArrayConstPtr &msg)
{
  if (msg->data.empty() || (msg->data[0] == 0 && msg->data[1] == 0))
    return;

  int pitch_temp = pitchAngle_ + msg->data[0];
  if (pitch_temp < pitch_min_ || pitch_temp > pitch_max_)
    return;
  else
    pitchAngle_ = pitch_temp;

  int yaw_temp = yawAngle_ - msg->data[1];
  if (yaw_temp < yaw_min_ || yaw_temp > yaw_max_)
    return;
  else
    yawAngle_ = yaw_temp;

  int power = 2;
  pubServo(pitchAngle_, yawAngle_, power);
}

void servoCallback(const UInt16MultiArrayConstPtr &msg)
{
  // This callback should always active
  pitchAngle_ = msg->data[0];
  yawAngle_ = msg->data[1];

  ros::param::set(param_servo_pitch, pitchAngle_);
  ros::param::set(param_servo_yaw, yawAngle_);
}

void searchCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_search) {
    if (msg->data == -1) {
      pubInfo("Search around didn't get target, continue searching...");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_search, -2);
      ros::param::set(param_vision_feedback, 2);
    }
    else if (msg->data == 0) {
      pubInfo("Currently didn't find target, continue searching...");
      ros::param::set(param_vision_feedback_search, -1);
      ros::param::set(param_vision_feedback, 1);
      foundTarget_ = false;
    }
    else {
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_search, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void trackCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO("Track report: Target lost!");
      foundTarget_ = false;
      ros::param::set(param_vision_feedback_track, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO_THROTTLE(7, "Track report: Tracking...");
      foundTarget_ = true;
      ros::param::set(param_vision_feedback_track, 1);
      ros::param::set(param_vision_feedback, 1);
    }
  }
}

void graspCallback(const Int8ConstPtr &msg)
{
  if (modeType_ == m_track) {
    if (!msg->data) {
      ROS_INFO_THROTTLE(3, "Grasp report: Failed.");
      ros::param::set(param_vision_feedback_grasp, -1);
      ros::param::set(param_vision_feedback, 1);
    }
    else if (msg->data == 1) {
      ROS_INFO_THROTTLE(3, "Grasp report: Reaching to the target...");
      ros::param::set(param_vision_feedback_grasp, 1);
      ros::param::set(param_vision_feedback, 1);
    }
    else {
      ROS_INFO("Grasp report: Target in reach.");
      // Reset if grasping has been performed
      resetStatus();
    }
  }
}

void faceRecognizeCallback(const BoolConstPtr &msg)
{
  if (modeType_ == m_wander) {
    if (!msg->data) {
      pubInfo("Face report: Failed.");
      ros::param::set(param_vision_feedback_face, -1);
      ros::param::set(param_vision_feedback, 2);
    }
    else {
      pubInfo("Face report: Successed.");
      ros::param::set(param_vision_feedback_face, 1);
      ros::param::set(param_vision_feedback, 3);
    }
  }
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "drv_brain");

  ros::NodeHandle nh;
  ros::NodeHandle pnh("~");

  pnh.getParam("pitch_min", pitch_min_);
  pnh.getParam("pitch_max", pitch_max_);
  pnh.getParam("yaw_min", yaw_min_);
  pnh.getParam("yaw_max", yaw_max_);

  servoPub_ = nh.advertise<UInt16MultiArray>("servo", 1, true);
  // For publishing mode info
  drvPubMode_ = nh.advertise<String>("/comm/msg/vision/mode", 1);
  drvPubInfo_ = nh.advertise<String>("/comm/msg/vision/info", 1);

  // Don't change the order without reason
  ros::Subscriber sub_servo_ctrl = nh.subscribe<Int32MultiArray>("/joy_teleop/servo", 1, teleOpCallback);
  ros::Subscriber sub_servo = nh.subscribe<UInt16MultiArray>("servo", 1, servoCallback);
  //ros::Subscriber sub_tgt = nh.subscribe<drv_msgs::target_info>("recognize/target", 1, targetCallback);
  ros::Subscriber sub_sh = nh.subscribe<Int8>("status/search/feedback", 1, searchCallback);
  ros::Subscriber sub_tk = nh.subscribe<Bool>("status/track/feedback", 1, trackCallback);
  ros::Subscriber sub_gp = nh.subscribe<Int8>("status/grasp/feedback", 1, graspCallback);
  ros::Subscriber sub_fr = nh.subscribe<Bool>("status/face/feedback", 1, faceRecognizeCallback);

  FaceListener fl;
  TargetListener tl;
  TargetSelecter ts;

  resetStatus();

  pubInfo("Deep Robot Vision system initialized!");

  while (ros::ok()) {
    // Main on/off control
    if (ros::param::has(param_vision_shared_switch)) {
      bool temp = true;
      ros::param::get(param_vision_shared_switch, temp);
      if (temp)
        ROS_WARN_COND(!centralSwitch_, "Central switch is ON.");
      centralSwitch_ = temp;
    }

    if (!centralSwitch_) {
      ROS_WARN_THROTTLE(9, "Central switch is OFF.");
      resetStatus();
      continue;
    }

    // Initialize servo position
    if (!servo_initialized_) {
      pubServo(90, 90, 1);
      servo_initialized_ = true;
      ROS_INFO("Servo reset.");
    }

    // Get feedback to determine whether target were found
    ros::spinOnce();

    // Get target label if the params were set
    tl.getTargetStatus(isTargetSet_, targetLabel_);
    ros::param::set(param_target_label, targetLabel_);

    if (isTargetSet_ != targetSetTemp_) {
      if (isTargetSet_)
        pubInfo("Target set to be '" + targetLabel_ + "'.");
      else {
        pubInfo("Target cancelled.");
        resetStatus();
      }
      targetSetTemp_ = isTargetSet_;
    }

    // If user selects target on cellphone, publish the target
    ts.publishOnceIfTargetSelected(isTargetSet_, foundTarget_);

    // Mode selection, notice that modeType_ should only be set by central control
    if (isTargetSet_) {
      if (foundTarget_) {
        // No matter whether the target is searched or selected by user,
        // as long as it was found, track it.
        modeType_ = m_track;
      }
      else {
        if (targetLabel_ == "user selected object") {
          // If the target is selected by user but no more been found,
          // which means tracking has lost it, reset.
          pubInfo("Tracking did not follow.");
          resetStatus();
        }
        else
          modeType_ = m_search;
      }
    }
    else {
      modeType_ = m_wander;
      fl.isNeedRecognizeFace(); // Only recognize face in wander mode
    }

    // Set running mode
    ros::param::set(param_running_mode, modeType_);

    if (modeType_ != modeTypeTemp_) {
      String mode_msg;
      mode_msg.data = modeName[modeType_];
      drvPubMode_.publish(mode_msg);
      ROS_INFO("Current mode: %s.", modeName[modeType_].c_str());
      modeTypeTemp_ = modeType_;
      if (modeType_ == m_wander) {
        // Reset head pose
        servo_initialized_ = false;
      }
    }
  }

  return 0;
}

<|endoftext|>


<commit_before>//
//  IMUOSCHandlers.cpp
//  IMU2OSC
//
//  Created by Jamie Bullock on 18/05/2012.
//  Copyright (c) 2012 Jamie Bullock. All rights reserved.
//

#include <iostream>

#include "osc/OscOutboundPacketStream.h"
#include "ip/UdpSocket.h"
//#include "IpEndpointName.h"

#define OUTPUT_BUFFER_SIZE  1024
#define ADDRESS "127.0.0.1"
#define PORT 7000

UdpTransmitSocket transmitSocket(IpEndpointName(ADDRESS, PORT));

//void osc_init(const char *address, unsigned int port)
//{
//    IpEndpointName endpointName(
//}

void osc_init(const char *address, unsigned int port)
{
    UdpTransmitSocket newTransmitSocket(IpEndpointName(address, port));
    transmitSocket = newTransmitSocket;
}

void osc_send_euler(double *euler) {

    char buffer[OUTPUT_BUFFER_SIZE];
    osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

    p << osc::BeginMessage( "/x-imu/euler" ) << (float)euler[0] << (float)euler[1] << (float)euler[2] << osc::EndMessage;
    transmitSocket.Send( p.Data(), p.Size() );
    p.Clear();

}

void osc_send_cal(double *gyro, double *accel, double *mag) {

    char buffer[OUTPUT_BUFFER_SIZE];
    osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

    p << osc::BeginMessage( "/x-imu/calibrated" ) << (float)gyro[0] << (float)gyro[1] << (float)gyro[2] << (float)accel[0] << (float)accel[1] << (float)accel[2] << (float)mag[0] << (float)mag[1] << (float)mag[2] << osc::EndMessage;
    transmitSocket.Send( p.Data(), p.Size() );
    p.Clear();

}
<commit_msg>Dynamically allocate UDP transmit socket<commit_after>//
//  IMUOSCHandlers.cpp
//  IMU2OSC
//
//  Created by Jamie Bullock on 18/05/2012.
//  Copyright (c) 2012 Jamie Bullock. All rights reserved.
//

#include <iostream>

#include "osc/OscOutboundPacketStream.h"
#include "ip/UdpSocket.h"
//#include "IpEndpointName.h"

#define OUTPUT_BUFFER_SIZE  1024
#define ADDRESS "127.0.0.1"
#define PORT 7000

UdpTransmitSocket *transmitSocket = NULL;

void osc_init(const char *address, unsigned int port)
{
//    UdpTransmitSocket newTransmitSocket(IpEndpointName(address, port));
    if (transmitSocket != NULL)
    {
        delete transmitSocket;
    }

    transmitSocket = new UdpTransmitSocket(IpEndpointName(address, port));
}

void osc_send_euler(double *euler) {

    char buffer[OUTPUT_BUFFER_SIZE];
    osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

    p << osc::BeginMessage( "/x-imu/euler" ) << (float)euler[0] << (float)euler[1] << (float)euler[2] << osc::EndMessage;

    if (transmitSocket->IsConnected())
    {
        transmitSocket->Send( p.Data(), p.Size() );
    }
    else
    {
        printf("No OSC connection\n");
    }
    p.Clear();

}

void osc_send_cal(double *gyro, double *accel, double *mag) {

    char buffer[OUTPUT_BUFFER_SIZE];
    osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE );

    p << osc::BeginMessage( "/x-imu/calibrated" ) << (float)gyro[0] << (float)gyro[1] << (float)gyro[2] << (float)accel[0] << (float)accel[1] << (float)accel[2] << (float)mag[0] << (float)mag[1] << (float)mag[2] << osc::EndMessage;

    if (transmitSocket->IsConnected())
    {
        transmitSocket->Send( p.Data(), p.Size() );
    }
    p.Clear();

}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>

#include "dll/rbm.hpp"
#include "dll/ocv_visualizer.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

int main(int /*argc*/, char* /*argv*/[]){
    dll::rbm_desc<
            28 * 28, 10*10,
            dll::momentum,
            dll::trainer<dll::pcd1_trainer_t>,
            dll::batch_size<50>,
            dll::visible<dll::unit_type::GAUSSIAN>,
            dll::watcher<dll::opencv_rbm_visualizer>>::rbm_t rbm;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>();

    mnist::normalize_dataset(dataset);

    rbm.train(dataset.training_images, 500, dll::init_watcher, 10);

    return 0;
}
<commit_msg>Adapt sample<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>

#include "dll/rbm.hpp"
#include "dll/ocv_visualizer.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

int main(int /*argc*/, char* /*argv*/[]){
    dll::rbm_desc<
            28 * 28, 10*10,
            dll::momentum,
            dll::trainer<dll::pcd1_trainer_t>,
            dll::batch_size<50>,
            dll::visible<dll::unit_type::GAUSSIAN>,
            dll::watcher<dll::opencv_rbm_visualizer>>::rbm_t rbm;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>();

    mnist::normalize_dataset(dataset);

    rbm.train(dataset.training_images, 500);

    return 0;
}
<|endoftext|>


<commit_before>#include "cqts_engine.h"
#include <QFile>
#include <QDir>

#include <QStringList>
#include <QTextStream>

#include <QDebug>

CQTs_engine::CQTs_engine()
{
}

/*****class handler*****/
/*ClassFile structure:
 *Class Name
 *lv max
 *datanumber
 *endofile
 */

CQTs_Class::CQTs_Class(QString classLink){
    QFile file(classLink+".ClC");
    int data;//data-sink for bab and ST
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        Name="error";
        data=0;
        lmax=-1;
    //add an alert!
       }
       else{
        int data;
        QTextStream in(&file);
        Name= in.readLine();
        in >> lmax;
        in >> data;
    }

}

/*****utilities*****/

QStringList extensionFind(QString ext,QString dir){
    QDir workDir(dir);

    QStringList filelist;
    filelist = workDir.entryList(QStringList(ext),QDir::Files | QDir::NoSymLinks);
    return filelist;
}

QStringList extensionFind(QString ext){
    return extensionFind(ext,"./");
}
<commit_msg>need to test constructor for classhandler<commit_after>#include "cqts_engine.h"
#include <QFile>
#include <QDir>

#include <QStringList>
#include <QTextStream>

#include <QDebug>

CQTs_engine::CQTs_engine()
{
}

/*****class handler*****/
/*ClassFile structure:
 *Class Name
 *lv max
 *datanumber
 *endofile
 */

CQTs_Class::CQTs_Class(QString classLink){
    QFile file(classLink+".ClC");//temporary
    int data;//data-sink for bab and ST
    int F=16, R=8, W=4, bab=3;//mask for ST&BAB
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        Name="error";
        data=0;
        lmax=-1;
    //add an alert!
       }
       else{
        int data;
        QTextStream in(&file);
        Name= in.readLine();
        in >> lmax;
        in >> data;
    }
    fort = (data & F)/F;
    ref = (data & R)/R;
    will = (data & W)/W;
    fort = (data & F)/F;
    bab = (data & bab)/bab;

}

/*****utilities*****/

QStringList extensionFind(QString ext,QString dir){
    QDir workDir(dir);

    QStringList filelist;
    filelist = workDir.entryList(QStringList(ext),QDir::Files | QDir::NoSymLinks);
    return filelist;
}

QStringList extensionFind(QString ext){
    return extensionFind(ext,"./");
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONAL_BASE_HH
#define DUNE_GDT_FUNCTIONAL_BASE_HH

#include <dune/common/dynvector.hh>

#include <dune/gdt/assembler/gridwalker.hh>
#include <dune/gdt/assembler/local/codim0.hh>
#include <dune/gdt/assembler/local/codim1.hh>

#include "interfaces.hh"

namespace Dune {
namespace GDT {
namespace Functional {

// forward, to be used in the traits
template <class ImpTraits>
class AssemblableVolumeBase;

template <class ImpTraits>
class AssemblableVolumeBaseTraits
{
public:
  typedef typename ImpTraits::derived_type derived_type;
  typedef typename ImpTraits::GridViewType GridViewType;
  typedef typename ImpTraits::SpaceType SpaceType;
  typedef typename ImpTraits::VectorType VectorType;
  typedef typename ImpTraits::ScalarType ScalarType;
}; // class AssemblableVolumeBaseTraits

template <class ImpTraits>
class AssemblableVolumeBase : public AssemblableFunctionalInterface<ImpTraits>,
                              public Functor::Codim0<typename ImpTraits::GridViewType>
{
  typedef AssemblableFunctionalInterface<ImpTraits> InterfaceType;
  typedef AssemblableVolumeBaseTraits<ImpTraits> Traits;

public:
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::ScalarType ScalarType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;

private:
  typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType;
  typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType;

public:
  AssemblableVolumeBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view)
    : vector_(vector)
    , space_(space)
    , grid_view_(grid_view)
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  AssemblableVolumeBase(VectorType& vector, const SpaceType& space)
    : vector_(vector)
    , space_(space)
    , grid_view_(*(space.grid_view()))
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  VectorType& vector()
  {
    return vector_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

private:
  virtual const LocalFunctionalType& local_functional() const = 0;

public:
  virtual void prepare()
  {
    if (!assembled_ && !prepared_) {
      local_assembler_                    = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional()));
      const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired();
      const size_t max_local_size         = space_.mapper().maxNumDofs();
      tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0],
                                                                   DynamicVector<ScalarType>(max_local_size)),
                            std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1],
                                                                   DynamicVector<ScalarType>(max_local_size))};
      tmp_indices_ = DynamicVector<size_t>(max_local_size, 0);
      prepared_    = true;
    }
  } // ... prepare()

  virtual void apply_local(const EntityType& entity)
  {
    assert(prepared_);
    local_assembler_->assembleLocal(space_, entity, vector_, tmp_local_vectors_, tmp_indices_);
  } // ... apply_local(...)

  void assemble()
  {
    if (!assembled_) {
      GridWalker<GridViewType> grid_walker(grid_view_);
      grid_walker.add(*this);
      grid_walker.walk();
      assembled_ = true;
    }
  } // ... assemble()

  template <class S>
  ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const
  {
    assemble();
    return vector_.dot(source);
  } // ... apply(...)

private:
  VectorType& vector_;
  const SpaceType& space_;
  const GridViewType& grid_view_;
  std::unique_ptr<LocalAssemblerType> local_assembler_;
  bool prepared_;
  bool assembled_;
  std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_;
  DynamicVector<size_t> tmp_indices_;
}; // class AssemblableVolumeBase

// forward, to be used in the traits
template <class ImpTraits>
class AssemblableFaceBase;

template <class ImpTraits>
class AssemblableFaceBaseTraits
{
public:
  typedef typename ImpTraits::derived_type derived_type;
  typedef typename ImpTraits::GridViewType GridViewType;
  typedef typename ImpTraits::SpaceType SpaceType;
  typedef typename ImpTraits::VectorType VectorType;
  typedef typename ImpTraits::ScalarType ScalarType;
}; // class AssemblableFaceBaseTraits

template <class ImpTraits>
class AssemblableFaceBase : public AssemblableFunctionalInterface<ImpTraits>,
                            public Functor::Codim1<typename ImpTraits::GridViewType>
{
  typedef AssemblableFunctionalInterface<AssemblableFaceBaseTraits<ImpTraits>> InterfaceType;
  typedef AssemblableFaceBaseTraits<ImpTraits> Traits;

public:
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::ScalarType ScalarType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

private:
  typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType;

public:
  AssemblableFaceBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view)
    : vector_(vector)
    , space_(space)
    , grid_view_(grid_view)
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  AssemblableFaceBase(VectorType& vector, const SpaceType& space)
    : vector_(vector)
    , space_(space)
    , grid_view_(*(space.grid_view()))
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  VectorType& vector()
  {
    assemble();
    return vector_;
  }

  const VectorType& vector() const
  {
    assemble();
    return vector_;
  }

private:
  virtual const LocalFunctionalType& local_functional() const = 0;

public:
  virtual void prepare()
  {
    if (!assembled_ && !prepared_) {
      local_assembler_                    = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional()));
      const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired();
      const size_t max_local_size         = space_.mapper().maxNumDofs();
      tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0],
                                                                   DynamicVector<ScalarType>(max_local_size)),
                            std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1],
                                                                   DynamicVector<ScalarType>(max_local_size))};
      tmp_indices_ = DynamicVector<size_t>(max_local_size, 0);
      prepared_    = true;
    }
  } // ... prepare()

  virtual void apply_local(const IntersectionType& intersection)
  {
    assert(prepared_);
    local_assembler_->assembleLocal(space_, intersection, vector_, tmp_local_vectors_, tmp_indices_);
  } // ... apply_local(...)

  void assemble()
  {
    if (!assembled_) {
      GridWalker<GridViewType> grid_walker(grid_view_);
      grid_walker.add(*this);
      grid_walker.walk();
      assembled_ = true;
    }
  } // ... assemble()

  template <class S>
  ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const
  {
    assemble();
    return vector_.dot(source);
  } // ... apply(...)

private:
  VectorType& vector_;
  const SpaceType& space_;
  const GridViewType& grid_view_;
  std::unique_ptr<LocalAssemblerType> local_assembler_;
  bool prepared_;
  bool assembled_;
  std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_;
  DynamicVector<size_t> tmp_indices_;
}; // class AssemblableFaceBase

} // namespace Functional
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONAL_BASE_HH
<commit_msg>[functional.base]<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONAL_BASE_HH
#define DUNE_GDT_FUNCTIONAL_BASE_HH

#include <dune/common/dynvector.hh>

#include <dune/gdt/assembler/gridwalker.hh>
#include <dune/gdt/assembler/local/codim0.hh>
#include <dune/gdt/assembler/local/codim1.hh>

#include "interfaces.hh"

namespace Dune {
namespace GDT {
namespace Functional {

// forward, to be used in the traits
template <class ImpTraits>
class AssemblableVolumeBase;

template <class ImpTraits>
class AssemblableVolumeBaseTraits
{
public:
  typedef typename ImpTraits::derived_type derived_type;
  typedef typename ImpTraits::GridViewType GridViewType;
  typedef typename ImpTraits::SpaceType SpaceType;
  typedef typename ImpTraits::VectorType VectorType;
  typedef typename ImpTraits::ScalarType ScalarType;
}; // class AssemblableVolumeBaseTraits

template <class ImpTraits>
class AssemblableVolumeBase : public AssemblableFunctionalInterface<ImpTraits>,
                              public Functor::Codim0<typename ImpTraits::GridViewType>
{
  typedef AssemblableFunctionalInterface<ImpTraits> InterfaceType;
  typedef AssemblableVolumeBaseTraits<ImpTraits> Traits;

public:
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::ScalarType ScalarType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;

private:
  typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType;
  typedef LocalAssembler::Codim0Vector<LocalFunctionalType> LocalAssemblerType;

public:
  AssemblableVolumeBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view)
    : vector_(vector)
    , space_(space)
    , grid_view_(grid_view)
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  AssemblableVolumeBase(VectorType& vector, const SpaceType& space)
    : vector_(vector)
    , space_(space)
    , grid_view_(*(space.grid_view()))
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  VectorType& vector()
  {
    return vector_;
  }

  const VectorType& vector() const
  {
    return vector_;
  }

private:
  virtual const LocalFunctionalType& local_functional() const = 0;

public:
  virtual void prepare()
  {
    if (!assembled_ && !prepared_) {
      local_assembler_                    = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional()));
      const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired();
      const size_t max_local_size         = space_.mapper().maxNumDofs();
      tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0],
                                                                   DynamicVector<ScalarType>(max_local_size)),
                            std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1],
                                                                   DynamicVector<ScalarType>(max_local_size))};
      tmp_indices_ = DynamicVector<size_t>(max_local_size, 0);
      prepared_    = true;
    }
  } // ... prepare()

  virtual void apply_local(const EntityType& entity)
  {
    assert(prepared_);
    local_assembler_->assembleLocal(space_, entity, vector_, tmp_local_vectors_, tmp_indices_);
  } // ... apply_local(...)

  void assemble()
  {
    if (!assembled_) {
      GridWalker<GridViewType> grid_walker(grid_view_);
      grid_walker.add(*this);
      grid_walker.walk();
      assembled_ = true;
    }
  } // ... assemble()

  template <class S>
  ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const
  {
    assemble();
    return vector_.dot(source);
  } // ... apply(...)

private:
  VectorType& vector_;
  const SpaceType& space_;
  const GridViewType& grid_view_;
  std::unique_ptr<LocalAssemblerType> local_assembler_;
  bool prepared_;
  bool assembled_;
  std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_;
  DynamicVector<size_t> tmp_indices_;
}; // class AssemblableVolumeBase

// forward, to be used in the traits
template <class ImpTraits>
class AssemblableFaceBase;

template <class ImpTraits>
class AssemblableFaceBaseTraits
{
public:
  typedef typename ImpTraits::derived_type derived_type;
  typedef typename ImpTraits::GridViewType GridViewType;
  typedef typename ImpTraits::SpaceType SpaceType;
  typedef typename ImpTraits::VectorType VectorType;
  typedef typename ImpTraits::ScalarType ScalarType;
}; // class AssemblableFaceBaseTraits

template <class ImpTraits>
class AssemblableFaceBase : public AssemblableFunctionalInterface<ImpTraits>,
                            public Functor::Codim1<typename ImpTraits::GridViewType>
{
  typedef AssemblableFunctionalInterface<AssemblableFaceBaseTraits<ImpTraits>> InterfaceType;
  typedef AssemblableFaceBaseTraits<ImpTraits> Traits;

public:
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::SpaceType SpaceType;
  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::ScalarType ScalarType;

  typedef typename GridViewType::template Codim<0>::Entity EntityType;
  typedef typename GridViewType::Intersection IntersectionType;

private:
  typedef typename ImpTraits::LocalFunctionalType LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector<LocalFunctionalType> LocalAssemblerType;

public:
  AssemblableFaceBase(VectorType& vector, const SpaceType& space, const GridViewType& grid_view)
    : vector_(vector)
    , space_(space)
    , grid_view_(grid_view)
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  AssemblableFaceBase(VectorType& vector, const SpaceType& space)
    : vector_(vector)
    , space_(space)
    , grid_view_(*(space.grid_view()))
    , local_assembler_(nullptr)
    , prepared_(false)
    , assembled_(false)
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const SpaceType& space() const
  {
    return space_;
  }

  VectorType& vector()
  {
    assemble();
    return vector_;
  }

  const VectorType& vector() const
  {
    assemble();
    return vector_;
  }

private:
  virtual const LocalFunctionalType& local_functional() const = 0;

public:
  virtual void prepare()
  {
    if (!assembled_ && !prepared_) {
      local_assembler_                    = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_functional()));
      const auto num_tmp_objects_required = local_assembler_->numTmpObjectsRequired();
      const size_t max_local_size         = space_.mapper().maxNumDofs();
      tmp_local_vectors_ = {std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[0],
                                                                   DynamicVector<ScalarType>(max_local_size)),
                            std::vector<DynamicVector<ScalarType>>(num_tmp_objects_required[1],
                                                                   DynamicVector<ScalarType>(max_local_size))};
      tmp_indices_ = DynamicVector<size_t>(max_local_size, 0);
      prepared_    = true;
    }
  } // ... prepare()

  virtual void apply_local(const IntersectionType& intersection)
  {
    assert(prepared_);
    assert(local_assembler_);
    local_assembler_->assembleLocal(space_, intersection, vector_, tmp_local_vectors_, tmp_indices_);
  } // ... apply_local(...)

  void assemble()
  {
    if (!assembled_) {
      GridWalker<GridViewType> grid_walker(grid_view_);
      grid_walker.add(*this);
      grid_walker.walk();
      assembled_ = true;
    }
  } // ... assemble()

  template <class S>
  ScalarType apply(const Stuff::LA::VectorInterface<S>& source) const
  {
    assemble();
    return vector_.dot(source);
  } // ... apply(...)

private:
  VectorType& vector_;
  const SpaceType& space_;
  const GridViewType& grid_view_;
  std::unique_ptr<LocalAssemblerType> local_assembler_;
  bool prepared_;
  bool assembled_;
  std::vector<std::vector<DynamicVector<ScalarType>>> tmp_local_vectors_;
  DynamicVector<size_t> tmp_indices_;
}; // class AssemblableFaceBase

} // namespace Functional
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONAL_BASE_HH
<|endoftext|>


<commit_before>/**
 * @file   PathTest.cpp
 * @brief  Path class tester.
 * @author zer0
 * @date   2016-04-07
 */

#include <gtest/gtest.h>
#include <libtbag/filesystem/Path.hpp>

using namespace libtbag;
using namespace libtbag::filesystem;

TEST(PathStaticTest, StyleChecker)
{
#if defined(WIN32) || defined(_WIN32)
    ASSERT_TRUE(Path::isWindowsStyle());
    ASSERT_FALSE(Path::isPosixStyle());
#else
    ASSERT_FALSE(Path::isWindowsStyle());
    ASSERT_TRUE(Path::isPosixStyle());
#endif
}

TEST(PathStaticTest, Constructors)
{
    char const * const TEMP = "TEMP";

    Path p0;
    Path p1 = Path(TEMP);
    Path p2 = Path(std::string(TEMP));
    Path p3 = Path(TEMP, Path::update_generic());
    Path p4 = Path(std::string(TEMP), Path::update_generic());
    Path p5 = p1;
    Path p6_move = Path(TEMP);
    Path p6 = std::move(p6_move);

    ASSERT_STREQ(p0.getString().c_str(), "");
    ASSERT_STREQ(p1.getString().c_str(), TEMP);
    ASSERT_STREQ(p2.getString().c_str(), TEMP);
    ASSERT_STREQ(p3.getString().c_str(), TEMP);
    ASSERT_STREQ(p4.getString().c_str(), TEMP);
    ASSERT_STREQ(p5.getString().c_str(), TEMP);
    ASSERT_STREQ(p6.getString().c_str(), TEMP);
}

TEST(PathStaticTest, initializer_list)
{
    Path p0 = {"/", "TE", "M", "P"};
    ASSERT_EQ(p0.getString(), Path::BaseString("/TE/M/P"));
}

TEST(PathStaticTest, AssignOperators)
{
    char const * const TEMP = "TEMP";

    auto rvalue_test = [&]() -> Path {
        return Path(TEMP);
    };

    Path const TEMP_PATH = Path(TEMP);
    std::string const TEMP_STRING = TEMP;
    ASSERT_STREQ(TEMP_PATH.getString().c_str(), TEMP);

    Path p0;

    p0.setString("");
    p0 = TEMP;
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0.setString("");
    p0 = TEMP_STRING;
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0.setString("");
    p0 = std::string(TEMP);
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0.setString("");
    p0 = TEMP_PATH;
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0.setString("");
    p0 = rvalue_test();
    ASSERT_STREQ(p0.getString().c_str(), TEMP);
}

TEST(PathStaticTest, isProhibitedFilename)
{
    std::string const FILENAME1 = "TEMP";
    ASSERT_FALSE(Path::isProhibitedFilenameOfWindows(FILENAME1));
    ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME1));

    std::string const FILENAME2 = "TE\\MP";
    ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME2));
    ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME2));

    std::string const FILENAME3 = "TE/MP";
    ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME3));
    ASSERT_TRUE(Path::isProhibitedFilenameOfPosix(FILENAME3));
}

TEST(PathStaticTest, removeLastSeparator)
{
    std::string const PREFIX = "\\/TE/\\MP";
    std::string const WINDOWS_SUFFIX = "\\\\";
    std::string const TEMP = PREFIX + WINDOWS_SUFFIX + "//";

    Path::BaseString windows = Path::removeLastSeparatorOfWindows(TEMP);
    Path::BaseString posix   = Path::removeLastSeparatorOfPosix(TEMP);

    ASSERT_EQ(windows, PREFIX);
    ASSERT_EQ(posix, PREFIX + WINDOWS_SUFFIX);
}

TEST(PathStaticTest, replaceHomeDirectoryShortcut_1)
{
    std::string const HOME = Common::getHomeDir();
    std::string const TEMP = "~";
    ASSERT_EQ(Path::replaceHomeDirectoryShortcut(TEMP), HOME);
}

TEST(PathStaticTest, replaceHomeDirectoryShortcut_2)
{
    std::string const HOME = Common::getHomeDir();
    std::string const TEMP = "TEMP";
    std::string const TEST = std::string("~/") + TEMP;

    Path p1 = Path(Path::replaceHomeDirectoryShortcut(TEMP), Path::update_generic());
    Path p2 = Path(Common::getHomeDir(), Path::update_generic());
    p2.append(TEMP);
    ASSERT_EQ(p2.getNative(), p2.getNative());
}

// Fixture.

class PathTest : public ::testing::Test
{
public:
    std::string ws;
    std::string ps;
    std::string gs;
    std::string s;

    std::string depth0;
    std::string depth1;
    std::string depth2;
    std::string depth3;
    std::string depth4;
    std::string depth5;

    std::string test_path;
    std::string windows_path;
    std::string posix_path;
    std::string generic_path;
    std::string canonical_path;

    Path path;

public:
    PathTest() {
        ws = PATH_SEPARATOR_STRING_OF_WINDOWS;
        ps = PATH_SEPARATOR_STRING_OF_POSIX;
        gs = GetGenericPathSeparatorString();
        s  = GetPathSeparatorString();
    }

    virtual ~PathTest() {
        __EMPTY_BLOCK__
    }

public:
    virtual void SetUp() override {
        __EMPTY_BLOCK__
    }

    virtual void TearDown() override {
        __EMPTY_BLOCK__
    }

public:
    void setupOfWindows() {
        depth0 = "O:";
        depth1 = "Temp";
        depth2 = "Directory";
        depth3 = "..";
        depth4 = ".";
        depth5 = "File.tmp";

        test_path       = R"(O:\\Temp\Directory/..\.//\\/File.tmp\/)";
        windows_path    = R"(O:\Temp\File.tmp)";
        posix_path      = R"(O:/Temp/Directory/.././File.tmp)";
        generic_path    = R"(O:/Temp/Directory/.././File.tmp)";
        canonical_path  = R"(O:/Temp/File.tmp)";

        path = Path(test_path);
    }

    void setupOfPosix() {
        depth0 = "/";
        depth1 = "Temp";
        depth2 = "\\Directory";
        depth3 = "..";
        depth4 = ".";
        depth5 = "File.tmp";

        test_path       = R"(/Temp/\Directory/.././////File.tmp//)";
        windows_path    = R"(/Temp/File.tmp)";
        posix_path      = R"(/Temp/\Directory/.././File.tmp)";
        generic_path    = R"(/Temp/\Directory/.././File.tmp)";
        canonical_path  = R"(/Temp/File.tmp)";

        path = Path(test_path);
    }
};

TEST_F(PathTest, getGeneric)
{
    setupOfWindows();
    ASSERT_EQ(Path::getGenericOfWindows(test_path), generic_path);

    setupOfPosix();
    ASSERT_EQ(Path::getGenericOfPosix(test_path), generic_path);
}

TEST_F(PathTest, getNative)
{
#if defined(WIN32) || defined(_WIN32)
    setupOfWindows();
    ASSERT_EQ(path.getNative(), windows_path);
#else
    setupOfPosix();
    ASSERT_EQ(path.getNative(), posix_path);
#endif
}

TEST_F(PathTest, getRootDir)
{
    setupOfWindows();
    ASSERT_EQ(Path::getRootDirOfWindows(test_path), depth0);

    setupOfPosix();
    ASSERT_EQ(Path::getRootDirOfPosix(test_path), depth0);
}

TEST_F(PathTest, isAbsolute)
{
    setupOfWindows();
    ASSERT_TRUE(Path::isAbsoluteOfWindows(test_path));
    ASSERT_FALSE(Path::isAbsoluteOfPosix(test_path));

    setupOfPosix();
    ASSERT_TRUE(Path::isAbsoluteOfPosix(test_path));
    ASSERT_FALSE(Path::isAbsoluteOfWindows(test_path));
}

TEST_F(PathTest, append)
{
    Path p0;
    p0.append(depth0);
    p0.append(depth1, Path::BaseString(GetGenericPathSeparatorString()));
    p0 /= depth2;
    p0 += depth3;
    p0.append(depth4);
    p0.append(depth5);
    ASSERT_EQ(p0.getGeneric(), generic_path);

    p0 = "";
    p0.append("/");
    ASSERT_EQ(p0.getString(), Path::BaseString("/"));
}

TEST_F(PathTest, getParentOfWindows)
{
    setupOfWindows();
    Path::BaseString test1 = Path::getParentOfWindows(test_path);
    Path::BaseString test2 = R"(O:\\Temp\Directory/..\.//\\)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\\Temp\Directory/..)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\\Temp\Directory)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\\Temp)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = "";
    ASSERT_EQ(test1, test2);

    // OTHER.
    test1 = Path::getParentOfWindows("TEST_PATH");
    test2 = "";
    ASSERT_EQ(test1, test2);
}

TEST_F(PathTest, getParentOfPosix)
{
    setupOfPosix();
    Path::BaseString test1 = Path::getParentOfPosix(test_path);
    Path::BaseString test2 = R"(/Temp/\Directory/.././///)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = R"(/Temp/\Directory/..)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = R"(/Temp/\Directory)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = R"(/Temp)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = "/";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = "";
    ASSERT_EQ(test1, test2);

    // OTHER.
    test1 = Path::getParentOfPosix("TEST_PATH");
    test2 = "";
    ASSERT_EQ(test1, test2);
}

TEST_F(PathTest, splitNodes)
{
    setupOfWindows();
    Path::Nodes nodes = Path::splitNodesOfWindows(test_path);
    ASSERT_EQ(nodes.size(), 6U);
    ASSERT_EQ(nodes[0], depth0);
    ASSERT_EQ(nodes[1], depth1);
    ASSERT_EQ(nodes[2], depth2);
    ASSERT_EQ(nodes[3], depth3);
    ASSERT_EQ(nodes[4], depth4);
    ASSERT_EQ(nodes[5], depth5);

    setupOfPosix();
    nodes = Path::splitNodesOfPosix(test_path);
    ASSERT_EQ(nodes.size(), 6U);
    ASSERT_EQ(nodes[0], depth0);
    ASSERT_EQ(nodes[1], depth1);
    ASSERT_EQ(nodes[2], depth2);
    ASSERT_EQ(nodes[3], depth3);
    ASSERT_EQ(nodes[4], depth4);
    ASSERT_EQ(nodes[5], depth5);
}

<commit_msg>Code refactoring.<commit_after>/**
 * @file   PathTest.cpp
 * @brief  Path class tester.
 * @author zer0
 * @date   2016-04-07
 */

#include <gtest/gtest.h>
#include <libtbag/filesystem/Path.hpp>

using namespace libtbag;
using namespace libtbag::filesystem;

TEST(PathStaticTest, StyleChecker)
{
#if defined(WIN32) || defined(_WIN32)
    ASSERT_TRUE(Path::isWindowsStyle());
    ASSERT_FALSE(Path::isPosixStyle());
#else
    ASSERT_FALSE(Path::isWindowsStyle());
    ASSERT_TRUE(Path::isPosixStyle());
#endif
}

TEST(PathStaticTest, Constructors)
{
    char const * const TEMP = "TEMP";

    Path p0;
    Path p1 = Path(TEMP);
    Path p2 = Path(std::string(TEMP));
    Path p3 = Path(TEMP, Path::update_generic());
    Path p4 = Path(std::string(TEMP), Path::update_generic());
    Path p5 = p1;
    Path p6_move = Path(TEMP);
    Path p6 = std::move(p6_move);

    ASSERT_STREQ(p0.getString().c_str(), "");
    ASSERT_STREQ(p1.getString().c_str(), TEMP);
    ASSERT_STREQ(p2.getString().c_str(), TEMP);
    ASSERT_STREQ(p3.getString().c_str(), TEMP);
    ASSERT_STREQ(p4.getString().c_str(), TEMP);
    ASSERT_STREQ(p5.getString().c_str(), TEMP);
    ASSERT_STREQ(p6.getString().c_str(), TEMP);
}

TEST(PathStaticTest, initializer_list)
{
    Path p0 = {"/", "TE", "M", "P"};
    ASSERT_EQ(p0.getString(), Path::BaseString("/TE/M/P"));
}

TEST(PathStaticTest, AssignOperators)
{
    char const * const TEMP = "TEMP";

    auto rvalue_test = [&]() -> Path {
        return Path(TEMP);
    };

    Path const TEMP_PATH = Path(TEMP);
    std::string const TEMP_STRING = TEMP;
    ASSERT_STREQ(TEMP_PATH.getString().c_str(), TEMP);

    Path p0;

    p0 = TEMP;
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0 = TEMP_STRING;
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0 = std::string(TEMP);
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0 = TEMP_PATH;
    ASSERT_STREQ(p0.getString().c_str(), TEMP);

    p0 = rvalue_test();
    ASSERT_STREQ(p0.getString().c_str(), TEMP);
}

TEST(PathStaticTest, isProhibitedFilename)
{
    std::string const FILENAME1 = "TEMP";
    ASSERT_FALSE(Path::isProhibitedFilenameOfWindows(FILENAME1));
    ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME1));

    std::string const FILENAME2 = "TE\\MP";
    ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME2));
    ASSERT_FALSE(Path::isProhibitedFilenameOfPosix(FILENAME2));

    std::string const FILENAME3 = "TE/MP";
    ASSERT_TRUE(Path::isProhibitedFilenameOfWindows(FILENAME3));
    ASSERT_TRUE(Path::isProhibitedFilenameOfPosix(FILENAME3));
}

TEST(PathStaticTest, removeLastSeparator)
{
    std::string const PREFIX = "\\/TE/\\MP";
    std::string const WINDOWS_SUFFIX = "\\\\";
    std::string const TEMP = PREFIX + WINDOWS_SUFFIX + "//";

    Path::BaseString windows = Path::removeLastSeparatorOfWindows(TEMP);
    Path::BaseString posix   = Path::removeLastSeparatorOfPosix(TEMP);

    ASSERT_EQ(windows, PREFIX);
    ASSERT_EQ(posix, PREFIX + WINDOWS_SUFFIX);
}

TEST(PathStaticTest, replaceHomeDirectoryShortcut_1)
{
    std::string const HOME = Common::getHomeDir();
    std::string const TEMP = "~";
    ASSERT_EQ(Path::replaceHomeDirectoryShortcut(TEMP), HOME);
}

TEST(PathStaticTest, replaceHomeDirectoryShortcut_2)
{
    std::string const HOME = Common::getHomeDir();
    std::string const TEMP = "TEMP";
    std::string const TEST = std::string("~/") + TEMP;

    Path p1 = Path(Path::replaceHomeDirectoryShortcut(TEMP), Path::update_generic());
    Path p2 = Path(Common::getHomeDir(), Path::update_generic());
    p2.append(TEMP);
    ASSERT_EQ(p2.getNative(), p2.getNative());
}

// Fixture.

class PathTest : public ::testing::Test
{
public:
    std::string ws;
    std::string ps;
    std::string gs;
    std::string s;

    std::string depth0;
    std::string depth1;
    std::string depth2;
    std::string depth3;
    std::string depth4;
    std::string depth5;

    std::string test_path;
    std::string windows_path;
    std::string posix_path;
    std::string generic_path;
    std::string canonical_path;

    Path path;

public:
    PathTest() {
        ws = PATH_SEPARATOR_STRING_OF_WINDOWS;
        ps = PATH_SEPARATOR_STRING_OF_POSIX;
        gs = GetGenericPathSeparatorString();
        s  = GetPathSeparatorString();
    }

    virtual ~PathTest() {
        __EMPTY_BLOCK__
    }

public:
    virtual void SetUp() override {
        __EMPTY_BLOCK__
    }

    virtual void TearDown() override {
        __EMPTY_BLOCK__
    }

public:
    void setupOfWindows() {
        depth0 = "O:";
        depth1 = "Temp";
        depth2 = "Directory";
        depth3 = "..";
        depth4 = ".";
        depth5 = "File.tmp";

        test_path       = R"(O:\\Temp\Directory/..\.//\\/File.tmp\/)";
        windows_path    = R"(O:\Temp\File.tmp)";
        posix_path      = R"(O:/Temp/Directory/.././File.tmp)";
        generic_path    = R"(O:/Temp/Directory/.././File.tmp)";
        canonical_path  = R"(O:/Temp/File.tmp)";

        path = Path(test_path);
    }

    void setupOfPosix() {
        depth0 = "/";
        depth1 = "Temp";
        depth2 = "\\Directory";
        depth3 = "..";
        depth4 = ".";
        depth5 = "File.tmp";

        test_path       = R"(/Temp/\Directory/.././////File.tmp//)";
        windows_path    = R"(/Temp/File.tmp)";
        posix_path      = R"(/Temp/\Directory/.././File.tmp)";
        generic_path    = R"(/Temp/\Directory/.././File.tmp)";
        canonical_path  = R"(/Temp/File.tmp)";

        path = Path(test_path);
    }
};

TEST_F(PathTest, getGeneric)
{
    setupOfWindows();
    ASSERT_EQ(Path::getGenericOfWindows(test_path), generic_path);

    setupOfPosix();
    ASSERT_EQ(Path::getGenericOfPosix(test_path), generic_path);
}

TEST_F(PathTest, getNative)
{
#if defined(WIN32) || defined(_WIN32)
    setupOfWindows();
    ASSERT_EQ(path.getNative(), windows_path);
#else
    setupOfPosix();
    ASSERT_EQ(path.getNative(), posix_path);
#endif
}

TEST_F(PathTest, getRootDir)
{
    setupOfWindows();
    ASSERT_EQ(Path::getRootDirOfWindows(test_path), depth0);

    setupOfPosix();
    ASSERT_EQ(Path::getRootDirOfPosix(test_path), depth0);
}

TEST_F(PathTest, isAbsolute)
{
    setupOfWindows();
    ASSERT_TRUE(Path::isAbsoluteOfWindows(test_path));
    ASSERT_FALSE(Path::isAbsoluteOfPosix(test_path));

    setupOfPosix();
    ASSERT_TRUE(Path::isAbsoluteOfPosix(test_path));
    ASSERT_FALSE(Path::isAbsoluteOfWindows(test_path));
}

TEST_F(PathTest, append)
{
    Path p0;
    p0.append(depth0);
    p0.append(depth1, Path::BaseString(GetGenericPathSeparatorString()));
    p0 /= depth2;
    p0 += depth3;
    p0.append(depth4);
    p0.append(depth5);
    ASSERT_EQ(p0.getGeneric(), generic_path);

    p0 = "";
    p0.append("/");
    ASSERT_EQ(p0.getString(), Path::BaseString("/"));
}

TEST_F(PathTest, getParentOfWindows)
{
    setupOfWindows();
    Path::BaseString test1 = Path::getParentOfWindows(test_path);
    Path::BaseString test2 = R"(O:\\Temp\Directory/..\.//\\)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\\Temp\Directory/..)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\\Temp\Directory)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\\Temp)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = R"(O:\)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfWindows(test1);
    test2 = "";
    ASSERT_EQ(test1, test2);

    // OTHER.
    test1 = Path::getParentOfWindows("TEST_PATH");
    test2 = "";
    ASSERT_EQ(test1, test2);
}

TEST_F(PathTest, getParentOfPosix)
{
    setupOfPosix();
    Path::BaseString test1 = Path::getParentOfPosix(test_path);
    Path::BaseString test2 = R"(/Temp/\Directory/.././///)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = R"(/Temp/\Directory/..)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = R"(/Temp/\Directory)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = R"(/Temp)";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = "/";
    ASSERT_EQ(test1, test2);

    test1 = Path::getParentOfPosix(test1);
    test2 = "";
    ASSERT_EQ(test1, test2);

    // OTHER.
    test1 = Path::getParentOfPosix("TEST_PATH");
    test2 = "";
    ASSERT_EQ(test1, test2);
}

TEST_F(PathTest, splitNodesOfWindows)
{
    setupOfWindows();
    Path::Nodes nodes = Path::splitNodesOfWindows(test_path);
    ASSERT_EQ(nodes.size(), 6U);
    ASSERT_EQ(nodes[0], depth0);
    ASSERT_EQ(nodes[1], depth1);
    ASSERT_EQ(nodes[2], depth2);
    ASSERT_EQ(nodes[3], depth3);
    ASSERT_EQ(nodes[4], depth4);
    ASSERT_EQ(nodes[5], depth5);
}

TEST_F(PathTest, splitNodesOfPosix)
{
    setupOfPosix();
    Path::Nodes nodes = Path::splitNodesOfPosix(test_path);
    ASSERT_EQ(nodes.size(), 6U);
    ASSERT_EQ(nodes[0], depth0);
    ASSERT_EQ(nodes[1], depth1);
    ASSERT_EQ(nodes[2], depth2);
    ASSERT_EQ(nodes[3], depth3);
    ASSERT_EQ(nodes[4], depth4);
    ASSERT_EQ(nodes[5], depth5);
}

<|endoftext|>


<commit_before>
// CopyBlocks.cpp

// Implements the test for cChunkData::CopyBlockTypes() range copying

#include "Globals.h"
#include "ChunkData.h"

int main(int argc, char ** argv)
{
	// Set up a cChunkData with known contents - all blocks 0x01, all metas 0x02:
	cChunkData Data;
	cChunkDef::BlockTypes   BlockTypes;
	cChunkDef::BlockNibbles BlockMetas;
	memset(BlockTypes, 0x01, sizeof(BlockTypes));
	memset(BlockMetas, 0x02, sizeof(BlockMetas));
	Data.SetBlockTypes(BlockTypes);
	Data.SetMetas(BlockMetas);

	// Try to read varying amounts of blocktypes from the cChunkData.
	// Verify that the exact amount of memory is copied, by copying to a larger buffer and checking its boundaries
	BLOCKTYPE TestBuffer[5 * cChunkDef::NumBlocks];
	size_t WritePosIdx = 2 * cChunkDef::NumBlocks;
	BLOCKTYPE * WritePosition = &TestBuffer[WritePosIdx];
	for (size_t idx = 0; idx < 5000; idx++)
	{
		for (size_t len = 1; len < 1000; len += 15)
		{
			//printf("Testing copying %u blocks from index %u\n", (unsigned)len, (unsigned)idx);

			//initalize buffer
			memset(TestBuffer, 0x03, sizeof(TestBuffer));

			Data.CopyBlockTypes(WritePosition, idx, len);

			// Verify the data copied:
			for (size_t i = 0; i < len; i++)
			{
				assert_test(WritePosition[i] == 0x01);
			}
			// Verify the space before the copied data hasn't been changed:
			for (size_t i = 0; i < WritePosIdx; i++)
			{
				assert_test(TestBuffer[i] == 0x03);
			}
			// Verify the space after the copied data hasn't been changed:
			for (size_t i = WritePosIdx + idx + len; i < ARRAYCOUNT(TestBuffer); i++)
			{
				assert_test(TestBuffer[i] == 0x03);
			}
		}
	}  // for idx
	return 0;
}

<commit_msg>Reduced the number of cChunkData::CopyBlockTypes() tests, added progress.<commit_after>
// CopyBlocks.cpp

// Implements the test for cChunkData::CopyBlockTypes() range copying

#include "Globals.h"
#include "ChunkData.h"

int main(int argc, char ** argv)
{
	// Set up a cChunkData with known contents - all blocks 0x01, all metas 0x02:
	cChunkData Data;
	cChunkDef::BlockTypes   BlockTypes;
	cChunkDef::BlockNibbles BlockMetas;
	memset(BlockTypes, 0x01, sizeof(BlockTypes));
	memset(BlockMetas, 0x02, sizeof(BlockMetas));
	Data.SetBlockTypes(BlockTypes);
	Data.SetMetas(BlockMetas);

	// Try to read varying amounts of blocktypes from the cChunkData.
	// Verify that the exact amount of memory is copied, by copying to a larger buffer and checking its boundaries
	BLOCKTYPE TestBuffer[5 * cChunkDef::NumBlocks];
	size_t WritePosIdx = 2 * cChunkDef::NumBlocks;
	BLOCKTYPE * WritePosition = &TestBuffer[WritePosIdx];
	memset(TestBuffer, 0x03, sizeof(TestBuffer));
	size_t LastReportedStep = 1;
	for (size_t idx = 0; idx < 5000; idx += 7)
	{
		if (idx / 500 != LastReportedStep)
		{
			printf("Testing index %u...\n", (unsigned)idx);
			LastReportedStep = idx / 500;
		}

		for (size_t len = 3; len < 1000; len += 13)
		{
			Data.CopyBlockTypes(WritePosition, idx, len);

			// Verify the data copied:
			for (size_t i = 0; i < len; i++)
			{
				assert_test(WritePosition[i] == 0x01);
			}
			// Verify the space before the copied data hasn't been changed:
			for (size_t i = 0; i < WritePosIdx; i++)
			{
				assert_test(TestBuffer[i] == 0x03);
			}
			// Verify the space after the copied data hasn't been changed:
			for (size_t i = WritePosIdx + idx + len; i < ARRAYCOUNT(TestBuffer); i++)
			{
				assert_test(TestBuffer[i] == 0x03);
			}

			// Re-initialize the buffer for the next test:
			for (size_t i = 0; i < len; i++)
			{
				WritePosition[i] = 0x03;
			}
		}  // for len
	}  // for idx
	return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "SkHalf.h"
#include "SkRasterPipeline.h"

DEF_TEST(SkRasterPipeline, r) {
    // Build and run a simple pipeline to exercise SkRasterPipeline,
    // drawing 50% transparent blue over opaque red in half-floats.

    Sk4h red  = SkFloatToHalf_finite_ftz({ 1.0f, 0.0f, 0.0f, 1.0f }),
         blue = SkFloatToHalf_finite_ftz({ 0.0f, 0.0f, 0.5f, 0.5f }),
         result;

    SkRasterPipeline p;
    p.append(SkRasterPipeline::load_s_f16, &blue);
    p.append(SkRasterPipeline::load_d_f16, &red);
    p.append(SkRasterPipeline::srcover);
    p.append(SkRasterPipeline::store_f16, &result);
    p.run(1);

    Sk4f f = SkHalfToFloat_finite_ftz(result);

    // We should see half-intensity magenta.
#if !defined(SK_BUILD_FOR_MAC)
    REPORTER_ASSERT(r, f[0] == 0.5f);
    REPORTER_ASSERT(r, f[1] == 0.0f);
    REPORTER_ASSERT(r, f[2] == 0.5f);
    REPORTER_ASSERT(r, f[3] == 1.0f);
#else
    SkDebugf("SkRasterPipeline test: %g %g %g %g\n", f[0], f[1], f[2], f[3]);
#endif
}

DEF_TEST(SkRasterPipeline_empty, r) {
    // No asserts... just a test that this is safe to run.
    SkRasterPipeline p;
    p.run(20);
}

DEF_TEST(SkRasterPipeline_nonsense, r) {
    // No asserts... just a test that this is safe to run and terminates.
    // srcover() calls st->next(); this makes sure we've always got something there to call.
    SkRasterPipeline p;
    p.append(SkRasterPipeline::srcover);
    p.run(20);
}
<commit_msg>Revert "Debug Mac test failure."<commit_after>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Test.h"
#include "SkHalf.h"
#include "SkRasterPipeline.h"

DEF_TEST(SkRasterPipeline, r) {
    // Build and run a simple pipeline to exercise SkRasterPipeline,
    // drawing 50% transparent blue over opaque red in half-floats.

    Sk4h red  = SkFloatToHalf_finite_ftz({ 1.0f, 0.0f, 0.0f, 1.0f }),
         blue = SkFloatToHalf_finite_ftz({ 0.0f, 0.0f, 0.5f, 0.5f }),
         result;

    SkRasterPipeline p;
    p.append(SkRasterPipeline::load_s_f16, &blue);
    p.append(SkRasterPipeline::load_d_f16, &red);
    p.append(SkRasterPipeline::srcover);
    p.append(SkRasterPipeline::store_f16, &result);
    p.run(1);

    Sk4f f = SkHalfToFloat_finite_ftz(result);

    // We should see half-intensity magenta.
    REPORTER_ASSERT(r, f[0] == 0.5f);
    REPORTER_ASSERT(r, f[1] == 0.0f);
    REPORTER_ASSERT(r, f[2] == 0.5f);
    REPORTER_ASSERT(r, f[3] == 1.0f);
}

DEF_TEST(SkRasterPipeline_empty, r) {
    // No asserts... just a test that this is safe to run.
    SkRasterPipeline p;
    p.run(20);
}

DEF_TEST(SkRasterPipeline_nonsense, r) {
    // No asserts... just a test that this is safe to run and terminates.
    // srcover() calls st->next(); this makes sure we've always got something there to call.
    SkRasterPipeline p;
    p.append(SkRasterPipeline::srcover);
    p.run(20);
}
<|endoftext|>


<commit_before>/* network.cpp
 *
 * Kubo Ryosuke
 */

#include "network/CsaClient.h"
#include <fstream>

using namespace sunfish;

int network() {

	// logger settings
	std::ofstream fout("network.log", std::ios::out);
	if (fout) {
		Loggers::send.addStream(fout);
		Loggers::receive.addStream(fout);
	}
	Loggers::error.addStream(std::cerr, "\x1b[31m", "\x1b[39m");
	Loggers::warning.addStream(std::cerr, "\x1b[33m", "\x1b[39m");
	Loggers::message.addStream(std::cerr, "\x1b[32m", "\x1b[39m");
	Loggers::send.addStream(std::cerr, true, true, "\x1b[34m", "\x1b[39m");
	Loggers::receive.addStream(std::cerr, true, true, "\x1b[35m", "\x1b[39m");
#ifndef NDEBUG
	Loggers::debug.addStream(std::cerr, "\x1b[36m", "\x1b[39m");
	Loggers::develop.addStream(std::cerr, "\x1b[37m", "\x1b[39m");
#endif // NDEBUG

	CsaClient csaClient;

	csaClient.execute();

	return 0;

}
<commit_msg>Change message color<commit_after>/* network.cpp
 *
 * Kubo Ryosuke
 */

#include "network/CsaClient.h"
#include <fstream>

using namespace sunfish;

int network() {

	// logger settings
	std::ofstream fout("network.log", std::ios::out);
	if (fout) {
		Loggers::send.addStream(fout);
		Loggers::receive.addStream(fout);
	}
	Loggers::error.addStream(std::cerr, "\x1b[31m", "\x1b[39m");
	Loggers::warning.addStream(std::cerr, "\x1b[33m", "\x1b[39m");
	Loggers::message.addStream(std::cerr/*, "\x1b[32m", "\x1b[39m"*/);
	Loggers::send.addStream(std::cerr, true, true, "\x1b[34m", "\x1b[39m");
	Loggers::receive.addStream(std::cerr, true, true, "\x1b[35m", "\x1b[39m");
#ifndef NDEBUG
	Loggers::debug.addStream(std::cerr, "\x1b[36m", "\x1b[39m");
	Loggers::develop.addStream(std::cerr, "\x1b[37m", "\x1b[39m");
#endif // NDEBUG

	CsaClient csaClient;

	csaClient.execute();

	return 0;

}
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "dirtab.h"

#include <cerrno>
#include <cstdio>
#include <cstdlib>

#include "util.h"

namespace catalog {

Dirtab::Dirtab() : valid_(true) {}

bool Dirtab::Open(const std::string &dirtab_path) {
  if (!FileExists(dirtab_path)) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'",
             dirtab_path.c_str());
    valid_ = false;
    return valid_;
  }

  FILE *dirtab_file = fopen(dirtab_path.c_str(), "r");
  if (dirtab_file == NULL) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s' "
                                      "(errno: %d)",
             dirtab_path.c_str(), errno);
    valid_ = false;
    return valid_;
  }

  valid_ = Parse(dirtab_file);
  fclose(dirtab_file);
  return valid_;
}

bool Dirtab::Parse(const std::string &dirtab) {
  valid_ = true;
  off_t line_offset = 0;
  while (line_offset < static_cast<off_t>(dirtab.size())) {
    std::string line = GetLineMem(dirtab.c_str() + line_offset,
                                  dirtab.size() - line_offset);
    line_offset += line.size() + 1;  // +1 == skipped \n
    if (!ParseLine(line)) {
      valid_ = false;
    }
  }
  valid_ = valid_ && CheckRuleValidity();
  return valid_;
}

bool Dirtab::Parse(FILE *dirtab_file) {
  valid_ = true;
  std::string line;
  while (GetLineFile(dirtab_file, &line)) {
    if (!ParseLine(line)) {
      valid_ = false;
    }
  }
  valid_ = valid_ && CheckRuleValidity();
  return valid_;
}

bool Dirtab::ParseLine(const std::string &line) {
  // line parsing is done using std::string iterators. Each parsing method ex-
  // pects an iterator and the end iterator. While parsing itr is constantly
  // incremented to walk through the given .cvmfsdirtab line.
        std::string::const_iterator itr  = line.begin();
  const std::string::const_iterator iend = line.end();
  bool negation = false;

  // parse preamble
  SkipWhitespace(iend, &itr);
  if (*itr == Dirtab::kCommentMarker) {
    return true;
  } else if (*itr == Dirtab::kNegationMarker) {
    negation = true;
    ++itr;
    SkipWhitespace(iend, &itr);
  }

  // extract and parse pathspec
  std::string pathspec_str(itr, iend);
  return this->ParsePathspec(pathspec_str, negation);
}

bool Dirtab::ParsePathspec(const std::string &pathspec_str, bool negation) {
  if (pathspec_str.empty()) {
    return true;
  }
  Pathspec pathspec(pathspec_str);

  // all generated Pathspecs need to be valid and positive rules must be
  // absolute. Otherwise the .cvmfsdirtab is not valid.
  if ( !pathspec.IsValid() ||
      (!negation && !pathspec.IsAbsolute())) {
    return false;
  }

  // create a new dirtab rule
  const Rule rule(pathspec, negation);
  AddRule(rule);
  return true;
}

void Dirtab::AddRule(const Rule &rule) {
  if (rule.is_negation) {
    negative_rules_.push_back(rule);
  } else {
    positive_rules_.push_back(rule);
  }
}

bool Dirtab::CheckRuleValidity() const {
  // check if there are contradicting positive and negative rules
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert(!p->is_negation);
          Rules::const_iterator n    = negative_rules_.begin();
    const Rules::const_iterator nend = negative_rules_.end();
    for (; n != nend; ++n) {
      assert(n->is_negation);
      if (p->pathspec == n->pathspec) {
        return false;
      }
    }
  }

  return true;
}

bool Dirtab::IsMatching(const std::string &path) const {
  // check if path has a positive match
  bool has_positive_match = false;
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert(!p->is_negation);
    if (p->pathspec.IsMatching(path)) {
      has_positive_match = true;
      break;
    }
  }

  return has_positive_match && !IsOpposing(path);
}

bool Dirtab::IsOpposing(const std::string &path) const {
        Rules::const_iterator n    = negative_rules_.begin();
  const Rules::const_iterator nend = negative_rules_.end();
  for (; n != nend; ++n) {
    assert(n->is_negation);
    if (n->pathspec.IsMatchingRelaxed(path)) {
      return true;
    }
  }

  return false;
}

bool RelaxedPathFilter::ParsePathspec(const std::string &pathspec_str,
                                      bool negation) {
  if (negation) {
    return Dirtab::ParsePathspec(pathspec_str, true);
  }
  bool success = true;
  std::string current_pathspec_str = pathspec_str;
  while (current_pathspec_str.length() > 0) {
    if (!Dirtab::ParsePathspec(current_pathspec_str, false))
      success = false;
    int new_length = current_pathspec_str.find_last_of("/");
    current_pathspec_str = current_pathspec_str.substr(0, new_length);
  }

  return success;
}

}  // namespace catalog
<commit_msg>FIX: return type in dirt.cc<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "dirtab.h"

#include <cerrno>
#include <cstdio>
#include <cstdlib>

#include "util.h"

namespace catalog {

Dirtab::Dirtab() : valid_(true) {}

bool Dirtab::Open(const std::string &dirtab_path) {
  if (!FileExists(dirtab_path)) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'",
             dirtab_path.c_str());
    valid_ = false;
    return valid_;
  }

  FILE *dirtab_file = fopen(dirtab_path.c_str(), "r");
  if (dirtab_file == NULL) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s' "
                                      "(errno: %d)",
             dirtab_path.c_str(), errno);
    valid_ = false;
    return valid_;
  }

  valid_ = Parse(dirtab_file);
  fclose(dirtab_file);
  return valid_;
}

bool Dirtab::Parse(const std::string &dirtab) {
  valid_ = true;
  off_t line_offset = 0;
  while (line_offset < static_cast<off_t>(dirtab.size())) {
    std::string line = GetLineMem(dirtab.c_str() + line_offset,
                                  dirtab.size() - line_offset);
    line_offset += line.size() + 1;  // +1 == skipped \n
    if (!ParseLine(line)) {
      valid_ = false;
    }
  }
  valid_ = valid_ && CheckRuleValidity();
  return valid_;
}

bool Dirtab::Parse(FILE *dirtab_file) {
  valid_ = true;
  std::string line;
  while (GetLineFile(dirtab_file, &line)) {
    if (!ParseLine(line)) {
      valid_ = false;
    }
  }
  valid_ = valid_ && CheckRuleValidity();
  return valid_;
}

bool Dirtab::ParseLine(const std::string &line) {
  // line parsing is done using std::string iterators. Each parsing method ex-
  // pects an iterator and the end iterator. While parsing itr is constantly
  // incremented to walk through the given .cvmfsdirtab line.
        std::string::const_iterator itr  = line.begin();
  const std::string::const_iterator iend = line.end();
  bool negation = false;

  // parse preamble
  SkipWhitespace(iend, &itr);
  if (*itr == Dirtab::kCommentMarker) {
    return true;
  } else if (*itr == Dirtab::kNegationMarker) {
    negation = true;
    ++itr;
    SkipWhitespace(iend, &itr);
  }

  // extract and parse pathspec
  std::string pathspec_str(itr, iend);
  return this->ParsePathspec(pathspec_str, negation);
}

bool Dirtab::ParsePathspec(const std::string &pathspec_str, bool negation) {
  if (pathspec_str.empty()) {
    return true;
  }
  Pathspec pathspec(pathspec_str);

  // all generated Pathspecs need to be valid and positive rules must be
  // absolute. Otherwise the .cvmfsdirtab is not valid.
  if ( !pathspec.IsValid() ||
      (!negation && !pathspec.IsAbsolute())) {
    return false;
  }

  // create a new dirtab rule
  const Rule rule(pathspec, negation);
  AddRule(rule);
  return true;
}

void Dirtab::AddRule(const Rule &rule) {
  if (rule.is_negation) {
    negative_rules_.push_back(rule);
  } else {
    positive_rules_.push_back(rule);
  }
}

bool Dirtab::CheckRuleValidity() const {
  // check if there are contradicting positive and negative rules
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert(!p->is_negation);
          Rules::const_iterator n    = negative_rules_.begin();
    const Rules::const_iterator nend = negative_rules_.end();
    for (; n != nend; ++n) {
      assert(n->is_negation);
      if (p->pathspec == n->pathspec) {
        return false;
      }
    }
  }

  return true;
}

bool Dirtab::IsMatching(const std::string &path) const {
  // check if path has a positive match
  bool has_positive_match = false;
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert(!p->is_negation);
    if (p->pathspec.IsMatching(path)) {
      has_positive_match = true;
      break;
    }
  }

  return has_positive_match && !IsOpposing(path);
}

bool Dirtab::IsOpposing(const std::string &path) const {
        Rules::const_iterator n    = negative_rules_.begin();
  const Rules::const_iterator nend = negative_rules_.end();
  for (; n != nend; ++n) {
    assert(n->is_negation);
    if (n->pathspec.IsMatchingRelaxed(path)) {
      return true;
    }
  }

  return false;
}

bool RelaxedPathFilter::ParsePathspec(const std::string &pathspec_str,
                                      bool negation) {
  if (negation) {
    return Dirtab::ParsePathspec(pathspec_str, true);
  }
  bool success = true;
  std::string current_pathspec_str = pathspec_str;
  while (current_pathspec_str.length() > 0) {
    if (!Dirtab::ParsePathspec(current_pathspec_str, false))
      success = false;
    size_t new_length = current_pathspec_str.find_last_of("/");
    current_pathspec_str = current_pathspec_str.substr(0, new_length);
  }

  return success;
}

}  // namespace catalog
<|endoftext|>