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

/* Author: Ioan Sucan */

#include <moveit/robot_model/robot_model.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_trajectory/robot_trajectory.h>
#include <moveit/utils/robot_model_test_utils.h>
#include <gtest/gtest.h>

class RobotTrajectoryTestFixture : public testing::Test
{
protected:
  moveit::core::RobotModelConstPtr robot_model_;
  moveit::core::RobotStatePtr robot_state_;
  const std::string robot_model_name_ = "panda";
  const std::string arm_jmg_name_ = "panda_arm";

protected:
  void SetUp() override
  {
    robot_model_ = moveit::core::loadTestingRobotModel(robot_model_name_);
    robot_state_ = std::make_shared<moveit::core::RobotState>(robot_model_);
    robot_state_->setToDefaultValues();
    robot_state_->setVariableVelocity(/*index*/ 0, /*value*/ 1.0);
    robot_state_->setVariableAcceleration(/*index*/ 0, /*value*/ -0.1);
    robot_state_->update();
  }

  void TearDown() override
  {
  }

  void initTestTrajectory(robot_trajectory::RobotTrajectoryPtr& trajectory)
  {
    // Init a traj
    ASSERT_TRUE(robot_model_->hasJointModelGroup(arm_jmg_name_))
        << "Robot model does not have group: " << arm_jmg_name_;

    trajectory = std::make_shared<robot_trajectory::RobotTrajectory>(robot_model_, arm_jmg_name_);

    EXPECT_EQ(trajectory->getGroupName(), arm_jmg_name_) << "Generated trajectory group name does not match";
    EXPECT_TRUE(trajectory->empty()) << "Generated trajectory not empty";

    double duration_from_previous = 0.1;
    std::size_t waypoint_count = 5;
    for (std::size_t ix = 0; ix < waypoint_count; ++ix)
      trajectory->addSuffixWayPoint(*robot_state_, duration_from_previous);
    // Quick check that getDuration is working correctly
    EXPECT_EQ(trajectory->getDuration(), duration_from_previous * waypoint_count)
        << "Generated trajectory duration incorrect";
    EXPECT_EQ(waypoint_count, trajectory->getWayPointDurations().size())
        << "Generated trajectory has the wrong number of waypoints";
  }

  void copyTrajectory(const robot_trajectory::RobotTrajectoryPtr& trajectory,
                      robot_trajectory::RobotTrajectoryPtr& trajectory_copy, bool deepcopy)
  {
    // Copy the trajectory
    trajectory_copy = std::make_shared<robot_trajectory::RobotTrajectory>(*trajectory, deepcopy);
    // Quick check that the getDuration values match
    EXPECT_EQ(trajectory_copy->getDuration(), trajectory->getDuration());
    EXPECT_EQ(trajectory_copy->getWayPointDurations().size(), trajectory->getWayPointDurations().size());
  }

  void modifyFirstWaypointPtrAndCheckTrajectory(robot_trajectory::RobotTrajectoryPtr& trajectory)
  {
    ///////////////////////////
    // Get the first waypoint by POINTER, modify it, and check that the value WAS updated in trajectory
    ///////////////////////////
    // Get the first waypoint by shared pointer
    moveit::core::RobotStatePtr trajectory_first_waypoint = trajectory->getWayPointPtr(0);
    // Get the first waypoint joint values
    std::vector<double> trajectory_first_state;
    trajectory_first_waypoint->copyJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Modify the first waypoint joint values
    trajectory_first_state[0] += 0.01;
    trajectory_first_waypoint->setJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Check that the trajectory's first waypoint was updated
    moveit::core::RobotStatePtr trajectory_first_waypoint_after_update = trajectory->getWayPointPtr(0);
    std::vector<double> trajectory_first_state_after_update;
    trajectory_first_waypoint_after_update->copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);
    EXPECT_EQ(trajectory_first_state[0], trajectory_first_state_after_update[0]);
  }

  void modifyFirstWaypointAndCheckTrajectory(robot_trajectory::RobotTrajectoryPtr& trajectory)
  {
    ///////////////////////////
    // Get the first waypoint by VALUE, modify it, and check that the value WAS NOT updated in trajectory
    ///////////////////////////
    // Get the first waypoint by shared pointer
    moveit::core::RobotState trajectory_first_waypoint = trajectory->getWayPoint(0);
    // Get the first waypoint joint values
    std::vector<double> trajectory_first_state;
    trajectory_first_waypoint.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Modify the first waypoint joint values
    trajectory_first_state[0] += 0.01;
    trajectory_first_waypoint.setJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Check that the trajectory's first waypoint was updated
    moveit::core::RobotState trajectory_first_waypoint_after_update = trajectory->getWayPoint(0);
    std::vector<double> trajectory_first_state_after_update;
    trajectory_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);
    EXPECT_NE(trajectory_first_state[0], trajectory_first_state_after_update[0]);
  }
};

TEST_F(RobotTrajectoryTestFixture, ModifyFirstWaypointByPtr)
{
  robot_trajectory::RobotTrajectoryPtr trajectory;
  initTestTrajectory(trajectory);
  modifyFirstWaypointPtrAndCheckTrajectory(trajectory);
}

TEST_F(RobotTrajectoryTestFixture, ModifyFirstWaypointByValue)
{
  robot_trajectory::RobotTrajectoryPtr trajectory;
  initTestTrajectory(trajectory);
  modifyFirstWaypointAndCheckTrajectory(trajectory);
}

TEST_F(RobotTrajectoryTestFixture, DoubleReverse)
{
  robot_trajectory::RobotTrajectoryPtr trajectory;
  initTestTrajectory(trajectory);
  moveit_msgs::RobotTrajectory initial_trajectory_msg;
  trajectory->getRobotTrajectoryMsg(initial_trajectory_msg);

  trajectory->reverse().reverse();

  moveit_msgs::RobotTrajectory edited_trajectory_msg;
  trajectory->getRobotTrajectoryMsg(edited_trajectory_msg);

  EXPECT_EQ(initial_trajectory_msg, edited_trajectory_msg);
}

TEST_F(RobotTrajectoryTestFixture, ChainEdits)
{
  robot_trajectory::RobotTrajectoryPtr initial_trajectory;
  initTestTrajectory(initial_trajectory);
  moveit_msgs::RobotTrajectory initial_trajectory_msg;
  initial_trajectory->getRobotTrajectoryMsg(initial_trajectory_msg);

  robot_trajectory::RobotTrajectory trajectory(robot_model_);
  trajectory.setGroupName(arm_jmg_name_)
      .clear()
      .setRobotTrajectoryMsg(*robot_state_, initial_trajectory_msg)
      .reverse()
      .addSuffixWayPoint(*robot_state_, 0.1)
      .addPrefixWayPoint(*robot_state_, 0.1)
      .insertWayPoint(1, *robot_state_, 0.1)
      .append(*initial_trajectory, 0.1);

  EXPECT_EQ(trajectory.getGroupName(), arm_jmg_name_);
  EXPECT_EQ(trajectory.getWayPointCount(), initial_trajectory->getWayPointCount() * 2 + 3);
}

TEST_F(RobotTrajectoryTestFixture, RobotTrajectoryShallowCopy)
{
  bool deepcopy = false;

  robot_trajectory::RobotTrajectoryPtr trajectory;
  robot_trajectory::RobotTrajectoryPtr trajectory_copy;

  initTestTrajectory(trajectory);
  copyTrajectory(trajectory, trajectory_copy, deepcopy);
  modifyFirstWaypointPtrAndCheckTrajectory(trajectory);

  // Check that modifying the waypoint also modified the trajectory
  moveit::core::RobotState trajectory_first_waypoint_after_update = trajectory->getWayPoint(0);
  std::vector<double> trajectory_first_state_after_update;
  trajectory_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);

  // Get the first waypoint in the modified trajectory_copy
  moveit::core::RobotState trajectory_copy_first_waypoint_after_update = trajectory_copy->getWayPoint(0);
  std::vector<double> trajectory_copy_first_state_after_update;
  trajectory_copy_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_,
                                                                      trajectory_copy_first_state_after_update);

  // Check that we updated the value correctly in the trajectory
  EXPECT_EQ(trajectory_first_state_after_update[0], trajectory_copy_first_state_after_update[0]);
}

TEST_F(RobotTrajectoryTestFixture, RobotTrajectoryDeepCopy)
{
  bool deepcopy = true;

  robot_trajectory::RobotTrajectoryPtr trajectory;
  robot_trajectory::RobotTrajectoryPtr trajectory_copy;

  initTestTrajectory(trajectory);
  copyTrajectory(trajectory, trajectory_copy, deepcopy);
  modifyFirstWaypointPtrAndCheckTrajectory(trajectory);

  // Check that modifying the waypoint also modified the trajectory
  moveit::core::RobotState trajectory_first_waypoint_after_update = trajectory->getWayPoint(0);
  std::vector<double> trajectory_first_state_after_update;
  trajectory_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);

  // Get the first waypoint in the modified trajectory_copy
  moveit::core::RobotState trajectory_copy_first_waypoint_after_update = trajectory_copy->getWayPoint(0);
  std::vector<double> trajectory_copy_first_state_after_update;
  trajectory_copy_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_,
                                                                      trajectory_copy_first_state_after_update);

  // Check that we updated the value correctly in the trajectory
  EXPECT_NE(trajectory_first_state_after_update[0], trajectory_copy_first_state_after_update[0]);
}

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

/* Author: Ioan Sucan */

#include <moveit/robot_model/robot_model.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_trajectory/robot_trajectory.h>
#include <moveit/utils/robot_model_test_utils.h>
#include <gtest/gtest.h>

class RobotTrajectoryTestFixture : public testing::Test
{
protected:
  moveit::core::RobotModelConstPtr robot_model_;
  moveit::core::RobotStatePtr robot_state_;
  const std::string robot_model_name_ = "panda";
  const std::string arm_jmg_name_ = "panda_arm";

protected:
  void SetUp() override
  {
    robot_model_ = moveit::core::loadTestingRobotModel(robot_model_name_);
    robot_state_ = std::make_shared<moveit::core::RobotState>(robot_model_);
    robot_state_->setToDefaultValues();
    robot_state_->setVariableVelocity(/*index*/ 0, /*value*/ 1.0);
    robot_state_->setVariableAcceleration(/*index*/ 0, /*value*/ -0.1);
    robot_state_->update();
  }

  void TearDown() override
  {
  }

  void initTestTrajectory(robot_trajectory::RobotTrajectoryPtr& trajectory)
  {
    // Init a traj
    ASSERT_TRUE(robot_model_->hasJointModelGroup(arm_jmg_name_))
        << "Robot model does not have group: " << arm_jmg_name_;

    trajectory = std::make_shared<robot_trajectory::RobotTrajectory>(robot_model_, arm_jmg_name_);

    EXPECT_EQ(trajectory->getGroupName(), arm_jmg_name_) << "Generated trajectory group name does not match";
    EXPECT_TRUE(trajectory->empty()) << "Generated trajectory not empty";

    double duration_from_previous = 0.1;
    std::size_t waypoint_count = 5;
    for (std::size_t ix = 0; ix < waypoint_count; ++ix)
      trajectory->addSuffixWayPoint(*robot_state_, duration_from_previous);
    // Quick check that getDuration is working correctly
    EXPECT_EQ(trajectory->getDuration(), duration_from_previous * waypoint_count)
        << "Generated trajectory duration incorrect";
    EXPECT_EQ(waypoint_count, trajectory->getWayPointDurations().size())
        << "Generated trajectory has the wrong number of waypoints";
  }

  void copyTrajectory(const robot_trajectory::RobotTrajectoryPtr& trajectory,
                      robot_trajectory::RobotTrajectoryPtr& trajectory_copy, bool deepcopy)
  {
    // Copy the trajectory
    trajectory_copy = std::make_shared<robot_trajectory::RobotTrajectory>(*trajectory, deepcopy);
    // Quick check that the getDuration values match
    EXPECT_EQ(trajectory_copy->getDuration(), trajectory->getDuration());
    EXPECT_EQ(trajectory_copy->getWayPointDurations().size(), trajectory->getWayPointDurations().size());
  }

  void modifyFirstWaypointPtrAndCheckTrajectory(robot_trajectory::RobotTrajectoryPtr& trajectory)
  {
    ///////////////////////////
    // Get the first waypoint by POINTER, modify it, and check that the value WAS updated in trajectory
    ///////////////////////////
    // Get the first waypoint by shared pointer
    moveit::core::RobotStatePtr trajectory_first_waypoint = trajectory->getWayPointPtr(0);
    // Get the first waypoint joint values
    std::vector<double> trajectory_first_state;
    trajectory_first_waypoint->copyJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Modify the first waypoint joint values
    trajectory_first_state[0] += 0.01;
    trajectory_first_waypoint->setJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Check that the trajectory's first waypoint was updated
    moveit::core::RobotStatePtr trajectory_first_waypoint_after_update = trajectory->getWayPointPtr(0);
    std::vector<double> trajectory_first_state_after_update;
    trajectory_first_waypoint_after_update->copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);
    EXPECT_EQ(trajectory_first_state[0], trajectory_first_state_after_update[0]);

    // Modify the first waypoint duration
    double trajectory_first_duration_before_update = trajectory->getWayPointDurationFromPrevious(0);
    double new_duration = trajectory_first_duration_before_update + 0.1;
    trajectory->setWayPointDurationFromPrevious(0, new_duration);

    // Check that the trajectory's first duration was updated
    EXPECT_EQ(trajectory->getWayPointDurationFromPrevious(0), new_duration);
  }

  void modifyFirstWaypointAndCheckTrajectory(robot_trajectory::RobotTrajectoryPtr& trajectory)
  {
    ///////////////////////////
    // Get the first waypoint by VALUE, modify it, and check that the value WAS NOT updated in trajectory
    ///////////////////////////
    // Get the first waypoint by shared pointer
    moveit::core::RobotState trajectory_first_waypoint = trajectory->getWayPoint(0);
    // Get the first waypoint joint values
    std::vector<double> trajectory_first_state;
    trajectory_first_waypoint.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Modify the first waypoint joint values
    trajectory_first_state[0] += 0.01;
    trajectory_first_waypoint.setJointGroupPositions(arm_jmg_name_, trajectory_first_state);

    // Check that the trajectory's first waypoint was updated
    moveit::core::RobotState trajectory_first_waypoint_after_update = trajectory->getWayPoint(0);
    std::vector<double> trajectory_first_state_after_update;
    trajectory_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);
    EXPECT_NE(trajectory_first_state[0], trajectory_first_state_after_update[0]);
  }
};

TEST_F(RobotTrajectoryTestFixture, ModifyFirstWaypointByPtr)
{
  robot_trajectory::RobotTrajectoryPtr trajectory;
  initTestTrajectory(trajectory);
  modifyFirstWaypointPtrAndCheckTrajectory(trajectory);
}

TEST_F(RobotTrajectoryTestFixture, ModifyFirstWaypointByValue)
{
  robot_trajectory::RobotTrajectoryPtr trajectory;
  initTestTrajectory(trajectory);
  modifyFirstWaypointAndCheckTrajectory(trajectory);
}

TEST_F(RobotTrajectoryTestFixture, DoubleReverse)
{
  robot_trajectory::RobotTrajectoryPtr trajectory;
  initTestTrajectory(trajectory);
  moveit_msgs::RobotTrajectory initial_trajectory_msg;
  trajectory->getRobotTrajectoryMsg(initial_trajectory_msg);

  trajectory->reverse().reverse();

  moveit_msgs::RobotTrajectory edited_trajectory_msg;
  trajectory->getRobotTrajectoryMsg(edited_trajectory_msg);

  EXPECT_EQ(initial_trajectory_msg, edited_trajectory_msg);
}

TEST_F(RobotTrajectoryTestFixture, ChainEdits)
{
  robot_trajectory::RobotTrajectoryPtr initial_trajectory;
  initTestTrajectory(initial_trajectory);
  moveit_msgs::RobotTrajectory initial_trajectory_msg;
  initial_trajectory->getRobotTrajectoryMsg(initial_trajectory_msg);

  robot_trajectory::RobotTrajectory trajectory(robot_model_);
  trajectory.setGroupName(arm_jmg_name_)
      .clear()
      .setRobotTrajectoryMsg(*robot_state_, initial_trajectory_msg)
      .reverse()
      .addSuffixWayPoint(*robot_state_, 0.1)
      .addPrefixWayPoint(*robot_state_, 0.1)
      .insertWayPoint(1, *robot_state_, 0.1)
      .append(*initial_trajectory, 0.1);

  EXPECT_EQ(trajectory.getGroupName(), arm_jmg_name_);
  EXPECT_EQ(trajectory.getWayPointCount(), initial_trajectory->getWayPointCount() * 2 + 3);
}

TEST_F(RobotTrajectoryTestFixture, RobotTrajectoryShallowCopy)
{
  bool deepcopy = false;

  robot_trajectory::RobotTrajectoryPtr trajectory;
  robot_trajectory::RobotTrajectoryPtr trajectory_copy;

  initTestTrajectory(trajectory);
  copyTrajectory(trajectory, trajectory_copy, deepcopy);
  modifyFirstWaypointPtrAndCheckTrajectory(trajectory);

  // Check that modifying the waypoint also modified the trajectory
  moveit::core::RobotState trajectory_first_waypoint_after_update = trajectory->getWayPoint(0);
  std::vector<double> trajectory_first_state_after_update;
  trajectory_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);

  // Get the first waypoint in the modified trajectory_copy
  moveit::core::RobotState trajectory_copy_first_waypoint_after_update = trajectory_copy->getWayPoint(0);
  std::vector<double> trajectory_copy_first_state_after_update;
  trajectory_copy_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_,
                                                                      trajectory_copy_first_state_after_update);

  // Check that we updated the joint position correctly in the trajectory
  EXPECT_EQ(trajectory_first_state_after_update[0], trajectory_copy_first_state_after_update[0]);
}

TEST_F(RobotTrajectoryTestFixture, RobotTrajectoryDeepCopy)
{
  bool deepcopy = true;

  robot_trajectory::RobotTrajectoryPtr trajectory;
  robot_trajectory::RobotTrajectoryPtr trajectory_copy;

  initTestTrajectory(trajectory);
  copyTrajectory(trajectory, trajectory_copy, deepcopy);
  modifyFirstWaypointPtrAndCheckTrajectory(trajectory);

  // Check that modifying the waypoint also modified the trajectory
  moveit::core::RobotState trajectory_first_waypoint_after_update = trajectory->getWayPoint(0);
  std::vector<double> trajectory_first_state_after_update;
  trajectory_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_, trajectory_first_state_after_update);

  // Get the first waypoint in the modified trajectory_copy
  moveit::core::RobotState trajectory_copy_first_waypoint_after_update = trajectory_copy->getWayPoint(0);
  std::vector<double> trajectory_copy_first_state_after_update;
  trajectory_copy_first_waypoint_after_update.copyJointGroupPositions(arm_jmg_name_,
                                                                      trajectory_copy_first_state_after_update);

  // Check that joint positions changed in the original trajectory but not the deep copy
  EXPECT_NE(trajectory_first_state_after_update[0], trajectory_copy_first_state_after_update[0]);
  // Check that the first waypoint duration changed in the original trajectory but not the deep copy
  EXPECT_NE(trajectory->getWayPointDurationFromPrevious(0), trajectory_copy->getWayPointDurationFromPrevious(0));
}

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>
#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "interval.h"
#include "itemrange.h"
#include "intervalrange.h"
#include "identifierrange.h"
#include "datadefinition.h"
#include "indexdefinition.h"

using namespace Ilwis;

size_t hash(const Ilwis::IndexDefinition::TrackIndex& val){
    std::hash<double> h1;
    std::hash<quint64> h2;

    size_t v = h1(val._trackValue)/2 + h2(val._featureid)/2;

    return v;
}

bool operator==(const Ilwis::IndexDefinition::TrackIndex& val1, const Ilwis::IndexDefinition::TrackIndex& val2 ){
    return val1._featureid == val2._featureid && val1._trackValue == val2._trackValue;
}

inline bool operator<(const Ilwis::IndexDefinition::TrackIndex& val1, const Ilwis::IndexDefinition::TrackIndex& val2 ){
    if ( val1._featureid < val2._featureid)
        return true;

    return val1._trackValue < val2._trackValue;
}

bool IndexDefinition::LessTrack::operator()(const IndexDefinition::TrackIndex &val1, const IndexDefinition::TrackIndex &val2) const
{
    if ( val1._featureid < val2._featureid)
        return true;

    return val1._trackValue < val2._trackValue;
}

//--------------------------------------------------------
IndexDefinition::IndexDefinition() : DataDefinition()
{

}

IndexDefinition::IndexDefinition(const IDomain& dm, Ilwis::Range *rng) : DataDefinition(dm, rng) {
}

quint32 IndexDefinition::indexSize() const
{
    return _index.size();
}

void IndexDefinition::addIndex(quint64 fid, const QVariant& tvalue, quint32 rec)
{
    double value = key(tvalue);
    if ( value != rUNDEF){
        TrackIndex trackIndex(value, fid);
        _index[trackIndex] = rec;
        _range->add(tvalue);;
    }
}

QVariant IndexDefinition::byOrder(quint32 record)
{
    QVariant indexValue;
    if ( record < _index.size()){
        if ( hasType(domain()->valueType(), itNUMBER )) {
            RangeIterator<double, NumericRange> iter(_range.data());
            indexValue = iter[record];
        } else if (hasType(domain()->valueType(), itNAMEDITEM)){
            RangeIterator<SPDomainItem, NamedIdentifierRange> iter(_range.data());
            indexValue = iter[record]->name();
        }else if (hasType(domain()->valueType(), itINDEXEDITEM)){
            RangeIterator<SPDomainItem, IndexedIdentifierRange> iter(_range.data());
            indexValue = iter[record]->name();
        }else if (hasType(domain()->valueType(), itDATETIME)){
            RangeIterator<double, TimeInterval> iter(_range.data());
            indexValue = iter[record];
        }
    }
    return indexValue;
}

void IndexDefinition::removeIndex(quint64 fid, const QVariant& tvalue)
{
    double value = key(tvalue);
    if ( value != rUNDEF){
        auto iter = _index.find(TrackIndex(value, fid));
        if(iter != _index.end())
            _index.erase(iter);
    }
}
quint32 IndexDefinition::indexRecord(quint64 fid, const QVariant &tvalue) const
{
    double value = key(tvalue);
    if ( value != rUNDEF){
        auto iter = _index.find(TrackIndex(value, fid));
        if ( iter != _index.end())
            return (*iter).second;
    }
    return iUNDEF;
}

double IndexDefinition::key(const QVariant &value) const
{
    double keyvalue = rUNDEF;
    if ( hasType(domain()->valueType(), itNUMBER )) {
        QVariant var = domain()->impliedValue(value);
        keyvalue = hasType(domain()->valueType(), itDATETIME) ? (double)var.value<Ilwis::Time>() : var.toDouble();
    }
    if ( hasType(domain()->ilwisType(), itITEMDOMAIN)) {
        SPItemRange rng = domain()->range<ItemRange>();
        if ( !rng->isValid())
            return rUNDEF;
        IlwisTypes valueType = domain()->valueType();
        if ( hasType(valueType, itNUMERICITEM )) {
            SPIntervalRange rng = domain()->range<IntervalRange>();
            keyvalue = rng->index(value.toDouble());
        }

        SPDomainItem domItem = rng->item(value.toString());
        if ( !domItem.isNull())
            keyvalue = domItem->raw();
    }

    return keyvalue;
}

<commit_msg>no real changes<commit_after>
#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "interval.h"
#include "itemrange.h"
#include "intervalrange.h"
#include "identifierrange.h"
#include "datadefinition.h"
#include "indexdefinition.h"

using namespace Ilwis;

size_t hash(const Ilwis::IndexDefinition::TrackIndex& val){
    std::hash<double> h1;
    std::hash<quint64> h2;

    size_t v = h1(val._trackValue)/2 + h2(val._featureid)/2;

    return v;
}

bool operator==(const Ilwis::IndexDefinition::TrackIndex& val1, const Ilwis::IndexDefinition::TrackIndex& val2 ){
    return val1._featureid == val2._featureid && val1._trackValue == val2._trackValue;
}

inline bool operator<(const Ilwis::IndexDefinition::TrackIndex& val1, const Ilwis::IndexDefinition::TrackIndex& val2 ){
    if ( val1._featureid < val2._featureid)
        return true;

    return val1._trackValue < val2._trackValue;
}

bool IndexDefinition::LessTrack::operator()(const IndexDefinition::TrackIndex &val1, const IndexDefinition::TrackIndex &val2) const
{
    if ( val1._featureid < val2._featureid)
        return true;

    return val1._trackValue < val2._trackValue;
}

//--------------------------------------------------------
IndexDefinition::IndexDefinition() : DataDefinition()
{

}

IndexDefinition::IndexDefinition(const IDomain& dm, Ilwis::Range *rng) : DataDefinition(dm, rng) {
}

quint32 IndexDefinition::indexSize() const
{
    return _index.size();
}

void IndexDefinition::addIndex(quint64 fid, const QVariant& tvalue, quint32 rec)
{
    double value = key(tvalue);
    if ( value != rUNDEF){
        TrackIndex trackIndex(value, fid);
        _index[trackIndex] = rec;
        _range->add(tvalue);
    }
}

QVariant IndexDefinition::byOrder(quint32 record)
{
    QVariant indexValue;
    if ( record < _index.size()){
        if ( hasType(domain()->valueType(), itNUMBER )) {
            RangeIterator<double, NumericRange> iter(_range.data());
            indexValue = iter[record];
        } else if (hasType(domain()->valueType(), itNAMEDITEM)){
            RangeIterator<SPDomainItem, NamedIdentifierRange> iter(_range.data());
            indexValue = iter[record]->name();
        }else if (hasType(domain()->valueType(), itINDEXEDITEM)){
            RangeIterator<SPDomainItem, IndexedIdentifierRange> iter(_range.data());
            indexValue = iter[record]->name();
        }else if (hasType(domain()->valueType(), itDATETIME)){
            RangeIterator<double, TimeInterval> iter(_range.data());
            indexValue = iter[record];
        }
    }
    return indexValue;
}

void IndexDefinition::removeIndex(quint64 fid, const QVariant& tvalue)
{
    double value = key(tvalue);
    if ( value != rUNDEF){
        auto iter = _index.find(TrackIndex(value, fid));
        if(iter != _index.end())
            _index.erase(iter);
    }
}
quint32 IndexDefinition::indexRecord(quint64 fid, const QVariant &tvalue) const
{
    double value = key(tvalue);
    if ( value != rUNDEF){
        auto iter = _index.find(TrackIndex(value, fid));
        if ( iter != _index.end())
            return (*iter).second;
    }
    return iUNDEF;
}

double IndexDefinition::key(const QVariant &value) const
{
    double keyvalue = rUNDEF;
    if ( hasType(domain()->valueType(), itNUMBER )) {
        QVariant var = domain()->impliedValue(value);
        keyvalue = hasType(domain()->valueType(), itDATETIME) ? (double)var.value<Ilwis::Time>() : var.toDouble();
    }
    if ( hasType(domain()->ilwisType(), itITEMDOMAIN)) {
        SPItemRange rng = domain()->range<ItemRange>();
        if ( !rng->isValid())
            return rUNDEF;
        IlwisTypes valueType = domain()->valueType();
        if ( hasType(valueType, itNUMERICITEM )) {
            SPIntervalRange rng = domain()->range<IntervalRange>();
            keyvalue = rng->index(value.toDouble());
        }

        SPDomainItem domItem = rng->item(value.toString());
        if ( !domItem.isNull())
            keyvalue = domItem->raw();
    }

    return keyvalue;
}

<|endoftext|>


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

#include "ros/service_client_link.h"
#include "ros/service_publication.h"
#include "ros/header.h"
#include "ros/connection.h"
#include "ros/service_manager.h"
#include "ros/transport/transport.h"
#include "ros/this_node.h"
#include "ros/file_log.h"

#include <boost/bind.hpp>

namespace ros
{

ServiceClientLink::ServiceClientLink()
{
}

ServiceClientLink::~ServiceClientLink()
{
}

bool ServiceClientLink::initialize(const ConnectionPtr& connection)
{
  connection_ = connection;
  connection_->addDropListener(boost::bind(&ServiceClientLink::onConnectionDropped, this, _1));

  return true;
}

bool ServiceClientLink::handleHeader(const Header& header)
{
  std::string md5sum, service, client_callerid;
  if (!header.getValue("md5sum", md5sum)
   || !header.getValue("service", service)
   || !header.getValue("callerid", client_callerid))
  {
    std::string msg("bogus tcpros header. did not have the "
                          "required elements: md5sum, service, callerid");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }

  ROSCPP_LOG_DEBUG("Service client [%s] wants service [%s] with md5sum [%s]", client_callerid.c_str(), service.c_str(), md5sum.c_str());
  ServicePublicationPtr ss = ServiceManager::instance()->lookupServicePublication(service);
  if (!ss)
  {
    std::string msg = std::string("received a tcpros connection for a "
                             "nonexistent service [") +
            service + std::string("].");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }
  if (ss->getMD5Sum() != md5sum &&
      (md5sum != std::string("*") && ss->getMD5Sum() != std::string("*")))
  {
    std::string msg = std::string("client wants service ") + service +
            std::string(" to have md5sum ") + md5sum +
            std::string(", but it has ") + ss->getMD5Sum() +
            std::string(". Dropping connection.");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }

  // Check whether the service (ss here) has been deleted from
  // advertised_topics through a call to unadvertise(), which could
  // have happened while we were waiting for the subscriber to
  // provide the md5sum.
  if(ss->isDropped())
  {
    std::string msg = std::string("received a tcpros connection for a "
                             "nonexistent service [") +
            service + std::string("].");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }
  else
  {
    parent_ = ServicePublicationWPtr(ss);

    // Send back a success, with info
    M_string m;
    m["request_type"] = ss->getRequestDataType();
    m["response_type"] = ss->getResponseDataType();
    m["type"] = ss->getDataType();
    m["md5sum"] = ss->getMD5Sum();
    m["callerid"] = this_node::getName();
    connection_->writeHeader(m, boost::bind(&ServiceClientLink::onHeaderWritten, this, _1));

    ss->addServiceClientLink(shared_from_this());
  }

  return true;
}

void ServiceClientLink::onConnectionDropped(const ConnectionPtr& conn)
{
  ROS_ASSERT(conn == connection_);

  if (ServicePublicationPtr parent = parent_.lock())
  {
    parent->removeServiceClientLink(shared_from_this());
  }
}

void ServiceClientLink::onHeaderWritten(const ConnectionPtr& conn)
{
  connection_->read(4, boost::bind(&ServiceClientLink::onRequestLength, this, _1, _2, _3, _4));
}

void ServiceClientLink::onRequestLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  if (!success)
    return;

  ROS_ASSERT(conn == connection_);
  ROS_ASSERT(size == 4);

  uint32_t len = *((uint32_t*)buffer.get());

  if (len > 1000000000)
  {
    ROS_ERROR("woah! a message of over a gigabyte was " \
                "predicted in tcpros. that seems highly " \
                "unlikely, so I'll assume protocol " \
                "synchronization is lost... it's over.");
    conn->drop();
  }

  connection_->read(len, boost::bind(&ServiceClientLink::onRequest, this, _1, _2, _3, _4));
}

void ServiceClientLink::onRequest(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  if (!success)
    return;

  ROS_ASSERT(conn == connection_);

  if (ServicePublicationPtr parent = parent_.lock())
  {
    parent->processRequest(buffer, size, shared_from_this());
  }
  else
  {
    ROS_BREAK();
  }
}

void ServiceClientLink::onResponseWritten(const ConnectionPtr& conn)
{
  ROS_ASSERT(conn == connection_);

  connection_->read(4, boost::bind(&ServiceClientLink::onRequestLength, this, _1, _2, _3, _4));
}

void ServiceClientLink::processResponse(bool ok, const SerializedMessage& res)
{
  connection_->write(res.buf, res.num_bytes, boost::bind(&ServiceClientLink::onResponseWritten, this, _1));
}

} // namespace ros

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

#include "ros/service_client_link.h"
#include "ros/service_publication.h"
#include "ros/header.h"
#include "ros/connection.h"
#include "ros/service_manager.h"
#include "ros/transport/transport.h"
#include "ros/this_node.h"
#include "ros/file_log.h"

#include <boost/bind.hpp>

namespace ros
{

ServiceClientLink::ServiceClientLink()
{
}

ServiceClientLink::~ServiceClientLink()
{
  if (connection_)
  {
    connection_->drop();
  }
}

bool ServiceClientLink::initialize(const ConnectionPtr& connection)
{
  connection_ = connection;
  connection_->addDropListener(boost::bind(&ServiceClientLink::onConnectionDropped, this, _1));

  return true;
}

bool ServiceClientLink::handleHeader(const Header& header)
{
  std::string md5sum, service, client_callerid;
  if (!header.getValue("md5sum", md5sum)
   || !header.getValue("service", service)
   || !header.getValue("callerid", client_callerid))
  {
    std::string msg("bogus tcpros header. did not have the "
                          "required elements: md5sum, service, callerid");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }

  ROSCPP_LOG_DEBUG("Service client [%s] wants service [%s] with md5sum [%s]", client_callerid.c_str(), service.c_str(), md5sum.c_str());
  ServicePublicationPtr ss = ServiceManager::instance()->lookupServicePublication(service);
  if (!ss)
  {
    std::string msg = std::string("received a tcpros connection for a "
                             "nonexistent service [") +
            service + std::string("].");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }
  if (ss->getMD5Sum() != md5sum &&
      (md5sum != std::string("*") && ss->getMD5Sum() != std::string("*")))
  {
    std::string msg = std::string("client wants service ") + service +
            std::string(" to have md5sum ") + md5sum +
            std::string(", but it has ") + ss->getMD5Sum() +
            std::string(". Dropping connection.");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }

  // Check whether the service (ss here) has been deleted from
  // advertised_topics through a call to unadvertise(), which could
  // have happened while we were waiting for the subscriber to
  // provide the md5sum.
  if(ss->isDropped())
  {
    std::string msg = std::string("received a tcpros connection for a "
                             "nonexistent service [") +
            service + std::string("].");

    ROS_ERROR("%s", msg.c_str());
    connection_->sendHeaderError(msg);

    return false;
  }
  else
  {
    parent_ = ServicePublicationWPtr(ss);

    // Send back a success, with info
    M_string m;
    m["request_type"] = ss->getRequestDataType();
    m["response_type"] = ss->getResponseDataType();
    m["type"] = ss->getDataType();
    m["md5sum"] = ss->getMD5Sum();
    m["callerid"] = this_node::getName();
    connection_->writeHeader(m, boost::bind(&ServiceClientLink::onHeaderWritten, this, _1));

    ss->addServiceClientLink(shared_from_this());
  }

  return true;
}

void ServiceClientLink::onConnectionDropped(const ConnectionPtr& conn)
{
  ROS_ASSERT(conn == connection_);

  if (ServicePublicationPtr parent = parent_.lock())
  {
    parent->removeServiceClientLink(shared_from_this());
  }
}

void ServiceClientLink::onHeaderWritten(const ConnectionPtr& conn)
{
  connection_->read(4, boost::bind(&ServiceClientLink::onRequestLength, this, _1, _2, _3, _4));
}

void ServiceClientLink::onRequestLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  if (!success)
    return;

  ROS_ASSERT(conn == connection_);
  ROS_ASSERT(size == 4);

  uint32_t len = *((uint32_t*)buffer.get());

  if (len > 1000000000)
  {
    ROS_ERROR("woah! a message of over a gigabyte was " \
                "predicted in tcpros. that seems highly " \
                "unlikely, so I'll assume protocol " \
                "synchronization is lost... it's over.");
    conn->drop();
  }

  connection_->read(len, boost::bind(&ServiceClientLink::onRequest, this, _1, _2, _3, _4));
}

void ServiceClientLink::onRequest(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  if (!success)
    return;

  ROS_ASSERT(conn == connection_);

  if (ServicePublicationPtr parent = parent_.lock())
  {
    parent->processRequest(buffer, size, shared_from_this());
  }
  else
  {
    ROS_BREAK();
  }
}

void ServiceClientLink::onResponseWritten(const ConnectionPtr& conn)
{
  ROS_ASSERT(conn == connection_);

  connection_->read(4, boost::bind(&ServiceClientLink::onRequestLength, this, _1, _2, _3, _4));
}

void ServiceClientLink::processResponse(bool ok, const SerializedMessage& res)
{
  connection_->write(res.buf, res.num_bytes, boost::bind(&ServiceClientLink::onResponseWritten, this, _1));
}

} // namespace ros

<|endoftext|>


<commit_before>#include "cinder/app/AppNative.h"
#include "cinder/app/RendererGl.h"
#include "cinder/Clipboard.h"
#include "cinder/Utilities.h"

#include "Resources.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ClipboardBasicApp : public AppNative {
  public:
	void keyDown( KeyEvent event );
	void draw();
};

void ClipboardBasicApp::keyDown( KeyEvent event )
{
#if ! defined( CINDER_COCOA_TOUCH )
	if( event.getChar() == 'c' && event.isAccelDown() ) {
		Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
		// to copy the contents of the window, you might do something like
		// Clipboard::setImage( copyWindowSurface() );
	}
#endif
}

void ClipboardBasicApp::draw()
{
	gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
	gl::setMatricesWindow( getWindowSize() );
	gl::enableAlphaBlending();

	if( Clipboard::hasImage() )
		gl::draw( gl::Texture::create( Clipboard::getImage() ) );
	else if( Clipboard::hasString() )
		gl::drawString( Clipboard::getString(), vec2( 0, getWindowCenter().y ) );
	else
		gl::drawString( "Clipboard contents unknown", vec2( 0, getWindowCenter().y ) );
}

CINDER_APP_NATIVE( ClipboardBasicApp, RendererGl )
<commit_msg>ClipboardBasic build fix<commit_after>#include "cinder/app/AppNative.h"
#include "cinder/app/RendererGl.h"
#include "cinder/Clipboard.h"
#include "cinder/Utilities.h"
#include "cinder/gl/Texture.h"

#include "Resources.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class ClipboardBasicApp : public AppNative {
  public:
	void keyDown( KeyEvent event );
	void draw();
};

void ClipboardBasicApp::keyDown( KeyEvent event )
{
#if ! defined( CINDER_COCOA_TOUCH )
	if( event.getChar() == 'c' && event.isAccelDown() ) {
		Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
		// to copy the contents of the window, you might do something like
		// Clipboard::setImage( copyWindowSurface() );
	}
#endif
}

void ClipboardBasicApp::draw()
{
	gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
	gl::setMatricesWindow( getWindowSize() );
	gl::enableAlphaBlending();

	if( Clipboard::hasImage() )
		gl::draw( gl::Texture::create( Clipboard::getImage() ) );
	else if( Clipboard::hasString() )
		gl::drawString( Clipboard::getString(), vec2( 0, getWindowCenter().y ) );
	else
		gl::drawString( "Clipboard contents unknown", vec2( 0, getWindowCenter().y ) );
}

CINDER_APP_NATIVE( ClipboardBasicApp, RendererGl )
<|endoftext|>


<commit_before>#ifndef ENSEMBLE_SAMPLER_HPP
#define ENSEMBLE_SAMPLER_HPP
#include <cassert>
#include <cmath>
#include <functional>
#include <type_traits>
#include <thread>
#include <mutex>
#include <atomic>
#include <sstream>
#include "mcmc_traits.hpp"
#include "base_urand.hpp"
#include "distribution.hpp"
#include "error_handler.hpp"

/*
  implemeted the emcee algorithm according to
  http://adsabs.harvard.edu/abs/2013PASP..125..306F
  https://arxiv.org/abs/1202.3665
*/

namespace mcmc_utilities
{
  template <typename T>
  T draw_z(base_urand<T>& rnd,T a)
  {
    const T sqrt_a=std::sqrt(a);
    T p=rnd()*2*(sqrt_a-1/sqrt_a);
    return std::pow(static_cast<T>(1/sqrt_a+p/2),static_cast<T>(2));
  }

  template <typename T_logprob,typename T_ensemble>
  const T_ensemble ensemble_sample(const T_logprob& logprob,
	  const T_ensemble& ensemble,
	  base_urand<typename std::result_of<T_logprob(typename T_ensemble::value_type)>::type>& rnd,
	  typename std::result_of<T_logprob(typename T_ensemble::value_type)>::type a=2)
  {
    using T=typename std::result_of<T_logprob(typename T_ensemble::value_type)>::type;
    using T_var=typename T_ensemble::value_type;

    const size_t K=get_size(ensemble);
    if(K==0)
      {
	throw mcmc_exception("number of walkers must not be zero");
      }
    if(K%2!=0)
      {
	throw mcmc_exception("number of walkers must be even");
      }
    const size_t n=get_size(get_element(ensemble,0));
    const size_t half_K=K/2;
    //T_ensemble ensemble_half(ensemble);
    auto ensemble_half(clone<T_ensemble>(ensemble));

    auto task=[&](size_t k)
      {
	const size_t i=k<half_K?0:1;
	const size_t ni=1-i;
	size_t j=0;
	do
	  {
	    j=rnd()*(half_K);
	  }
	while(j==half_K);
	T z=draw_z(rnd,a);
	//T_var Y(get_element(ensemble,k));
	T_var Y(clone<T_var>(get_element(ensemble,k)));
	for(int l=0;l<get_size(Y);++l)
	  {
	    T y=get_element(get_element(ensemble,j+half_K*ni),l)+z*(get_element(get_element(ensemble,k),l)-get_element(get_element(ensemble,j+half_K*ni),l));
	    set_element(Y,l,y);
	    if(std::isnan(y)||std::isinf(y))
	      {
		nan_or_inf e;
		e.attach_message("inf or nan for y\n");
		std::ostringstream oss;
		oss<<"y="<<y<<std::endl;
		e.attach_message(oss.str());
	      }
	  }
	T q=std::exp((n-1)*std::log(z)+(logprob(Y)-logprob(get_element(ensemble,k))));
	if(std::isnan(q)||std::isinf(q))
	  {
	    nan_or_inf e;
	    e.attach_message("inf or nan\n");

	    std::ostringstream oss;
	    oss<<"q="<<q<<std::endl;
	    oss<<"Y=";
	    for(int l=0;l<n;++l)
	      {
		oss<<get_element(Y,l)<<" ";
	      }
	    oss<<"\nlogprob(Y)="<<logprob(Y)<<"\n";

	    oss<<"X=";
	    for(int l=0;l<n;++l)
	      {
		oss<<get_element(get_element(ensemble,k),l)<<" ";
	      }
	    oss<<"\nlogprob(X)="<<logprob(get_element(ensemble,k))<<"\n";
	    e.attach_message(oss.str());
	    throw e;
	  }

	T r=rnd();
	if(r<=q)
	  {
	    set_element(ensemble_half,k,Y);
	  }
      };

    if(!rnd.is_parallel())
      {
	for(size_t k=0;k<K;++k)
	  {
	    task(k);
	  }
      }
    else
      {
	std::vector<std::thread> pool;
	pool.reserve(K);
	size_t nthread_allowed=std::thread::hardware_concurrency();
	size_t nrunning_thread(0);
	size_t k(0);
	std::mutex mx;
	std::function<void()> chain_task([&nrunning_thread,&k,&task,nthread_allowed,&pool,&chain_task,K,&mx](){
	    mx.lock();
	    int k1=k;
	    //std::cerr<<"k="<<k<<std::endl;
	    nrunning_thread++;
	    k++;
	    mx.unlock();
	    task(k1);
	    mx.lock();
	    if(nrunning_thread<nthread_allowed&&pool.size()<K)
	      {
		pool.push_back(std::thread(chain_task));
		//assert(pool.size()<=K);
	      }
	    nrunning_thread--;
	    mx.unlock();
	  });
	mx.lock();
	for(int i=0;i<nthread_allowed;++i)
	  {
	    pool.push_back(std::thread(chain_task));
	  }
	mx.unlock();
	//std::cerr<<pool.size()<<std::endl;
	bool any_running=false;
	do
	  {
	    any_running=false;
	    for(auto& t:pool)
	      {
		if(t.joinable())
		  {
		    any_running=true;
		    t.join();
		  }
	      }
	  }
	while(any_running||pool.size()<K);
      }

    return (ensemble_half);
  }
}

#endif
<commit_msg>	修改：     core/ensemble_sample.hpp<commit_after>#ifndef ENSEMBLE_SAMPLER_HPP
#define ENSEMBLE_SAMPLER_HPP
#include <cassert>
#include <cmath>
#include <functional>
#include <type_traits>
#include <thread>
#include <mutex>
#include <atomic>
#include <sstream>
#include "mcmc_traits.hpp"
#include "base_urand.hpp"
#include "distribution.hpp"
#include "error_handler.hpp"

/*
  implemeted the emcee algorithm according to
  http://adsabs.harvard.edu/abs/2013PASP..125..306F
  https://arxiv.org/abs/1202.3665
*/

namespace mcmc_utilities
{
  template <typename T>
  T draw_z(base_urand<T>& rnd,T a)
  {
    const T sqrt_a=std::sqrt(a);
    T p=rnd()*2*(sqrt_a-1/sqrt_a);
    return std::pow(static_cast<T>(1/sqrt_a+p/2),static_cast<T>(2));
  }

  template <typename T_logprob,typename T_ensemble>
  const T_ensemble ensemble_sample(const T_logprob& logprob,
	  const T_ensemble& ensemble,
	  base_urand<typename std::result_of<T_logprob(typename T_ensemble::value_type)>::type>& rnd,
	  typename std::result_of<T_logprob(typename T_ensemble::value_type)>::type a=2)
  {
    using T=typename std::result_of<T_logprob(typename T_ensemble::value_type)>::type;
    using T_var=typename T_ensemble::value_type;

    const size_t K=get_size(ensemble);
    if(K==0)
      {
	throw mcmc_exception("number of walkers must not be zero");
      }
    if(K%2!=0)
      {
	throw mcmc_exception("number of walkers must be even");
      }
    const size_t n=get_size(get_element(ensemble,0));
    const size_t half_K=K/2;
    //T_ensemble ensemble_half(ensemble);
    auto ensemble_half(clone<T_ensemble>(ensemble));

    auto task=[&](size_t k)
      {
	const size_t i=k<half_K?0:1;
	const size_t ni=1-i;
	size_t j=0;
	do
	  {
	    j=rnd()*(half_K);
	  }
	while(j==half_K);
	T z=draw_z(rnd,a);
	//T_var Y(get_element(ensemble,k));
	T_var Y(clone<T_var>(get_element(ensemble,k)));
	for(int l=0;l<get_size(Y);++l)
	  {
	    T y=get_element(get_element(ensemble,j+half_K*ni),l)+z*(get_element(get_element(ensemble,k),l)-get_element(get_element(ensemble,j+half_K*ni),l));
	    set_element(Y,l,y);
	    if(std::isnan(y)||std::isinf(y))
	      {
		nan_or_inf e;
		e.attach_message("inf or nan for y\n");
		std::ostringstream oss;
		oss<<"y="<<y<<std::endl;
		e.attach_message(oss.str());
	      }
	  }
	T q=std::exp((n-1)*std::log(z)+logprob(Y)-logprob(get_element(ensemble,k)));
	if(std::isnan(q))
	  {
	    nan_or_inf e;
	    e.attach_message("inf or nan\n");

	    std::ostringstream oss;
	    oss<<"q="<<q<<std::endl;
	    oss<<"Y=";
	    for(int l=0;l<n;++l)
	      {
		oss<<get_element(Y,l)<<" ";
	      }
	    oss<<"\nlogprob(Y)="<<logprob(Y)<<"\n";

	    oss<<"X=";
	    for(int l=0;l<n;++l)
	      {
		oss<<get_element(get_element(ensemble,k),l)<<" ";
	      }
	    oss<<"\nlogprob(X)="<<logprob(get_element(ensemble,k))<<"\n";
	    oss<<"z="<<z<<std::endl;
	    e.attach_message(oss.str());
	    throw e;
	  }

	T r=rnd();
	if(r<=q)
	  {
	    set_element(ensemble_half,k,Y);
	  }
      };

    if(!rnd.is_parallel())
      {
	for(size_t k=0;k<K;++k)
	  {
	    task(k);
	  }
      }
    else
      {
	std::vector<std::thread> pool;
	pool.reserve(K);
	size_t nthread_allowed=std::thread::hardware_concurrency();
	size_t nrunning_thread(0);
	size_t k(0);
	std::mutex mx;
	std::function<void()> chain_task([&nrunning_thread,&k,&task,nthread_allowed,&pool,&chain_task,K,&mx](){
	    mx.lock();
	    int k1=k;
	    //std::cerr<<"k="<<k<<std::endl;
	    nrunning_thread++;
	    k++;
	    mx.unlock();
	    task(k1);
	    mx.lock();
	    if(nrunning_thread<nthread_allowed&&pool.size()<K)
	      {
		pool.push_back(std::thread(chain_task));
		//assert(pool.size()<=K);
	      }
	    nrunning_thread--;
	    mx.unlock();
	  });
	mx.lock();
	for(int i=0;i<nthread_allowed;++i)
	  {
	    pool.push_back(std::thread(chain_task));
	  }
	mx.unlock();
	//std::cerr<<pool.size()<<std::endl;
	bool any_running=false;
	do
	  {
	    any_running=false;
	    for(auto& t:pool)
	      {
		if(t.joinable())
		  {
		    any_running=true;
		    t.join();
		  }
	      }
	  }
	while(any_running||pool.size()<K);
      }

    return (ensemble_half);
  }
}

#endif
<|endoftext|>


<commit_before>#include "Sound.h"
#ifdef WIN32
#include <SDL/SDL_mixer.h>
#else
#include <SDL_mixer/SDL_mixer.h>
#endif
#include <SDL/SDL.h>
#include <queue>

#include <map>
#include <math.h>
#include "Utilities/ResourceManager.h"
#include "Logging.h"

namespace Sound
{

namespace Internal
{

typedef std::map<std::string, Mix_Chunk*> EffectsMap;
typedef std::map<std::string, Mix_Music*> MusicMap;
std::queue<std::string> preloadQueue;
EffectsMap effects;
MusicMap musics;

SDL_mutex* effectMapLock = NULL;
SDL_mutex* preloadQueueLock = NULL;
SDL_cond* preloadQueueCondition = NULL;

Mix_Chunk* SoundNamed ( const std::string& name )
{
	SDL_LockMutex(effectMapLock);
	EffectsMap::iterator iter = effects.find(name);
	if (iter == effects.end())
	{
		// load the sound
		std::string path = "Sounds/" + name + ".aiff";
		SDL_RWops* ops = ResourceManager::OpenFile(path);
		Mix_Chunk* newChunk = Mix_LoadWAV_RW(ops, 1);
		if (!newChunk)
		{
            LOG("Sound", LOG_WARNING, "Decoding sound '%s' failed! Error: %s", name.c_str(), Mix_GetError());
			effects[name] = NULL;
			SDL_UnlockMutex(effectMapLock);
			return NULL;
		}
		effects[name] = newChunk;
		SDL_UnlockMutex(effectMapLock);
		return newChunk;
	}
	else
	{
		SDL_UnlockMutex(effectMapLock);
		return iter->second;
	}
}

void PreloadingThread ()
{
	SDL_LockMutex(preloadQueueLock);
	while (SDL_CondWait(preloadQueueCondition, preloadQueueLock))
	{
		while (!preloadQueue.empty())
		{
			std::string nextSound = preloadQueue.front();
			preloadQueue.pop();
			SoundNamed(nextSound);
		}
	}
}

const char* extensions[] =
{
	".s3m",
	".ogg",
	".xm",
	".mod",
	".aiff",
	NULL
};

Mix_Music* MusicNamed ( const std::string& name )
{
	MusicMap::iterator iter = musics.find(name);
	if (iter == musics.end())
	{
		// load the sound
		Mix_Music* newMusic = NULL;
		for (unsigned i = 0; extensions[i] != NULL; i++)
		{
			std::string path = "Music/" + name + extensions[i];
			SDL_RWops* ops = ResourceManager::OpenFile(path);
			if (!ops)
				continue;
			newMusic = Mix_LoadMUS_RW(ops);
			if (newMusic)
				break;
		}
		musics[name] = newMusic;
		return newMusic;
	}
	else
	{
		return iter->second;
	}
}

std::string songName;

}

using namespace Internal;

static bool disable_music = false;

void Init ( int frequency, int resolution, int sources )
{
	int volume_sound = MIX_MAX_VOLUME, volume_music = MIX_MAX_VOLUME;
	Uint16 format;
	switch (resolution)
	{
		case 8:
			format = AUDIO_S8;
			break;
		case 16:
			format = AUDIO_S16SYS;
			break;
/*		case 24:
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
			format = 0x8018;
#else
			format = 0x9018;
#endif
			break;*/
		default:
            LOG("Sound", LOG_NOTICE, "Unsupported audio format, defaulting to 16-bit");
			format = AUDIO_S16SYS;
			break;
	}
	Mix_OpenAudio(frequency, format, 2, 4096);
	Mix_AllocateChannels(sources);
	Mix_VolumeMusic(volume_music);
	Mix_Volume(-1, volume_sound);
	if (getenv("APOLLO_MUSIC_DISABLE"))
		disable_music = true;
	effectMapLock = SDL_CreateMutex();
	preloadQueueLock = SDL_CreateMutex();
	preloadQueueCondition = SDL_CreateCond();
}

void Preload ( const std::string& name )
{
	SDL_LockMutex(preloadQueueLock);
	preloadQueue.push(name);
	SDL_UnlockMutex(preloadQueueLock);
	SDL_CondSignal(preloadQueueCondition);
}

void PlaySoundSDL ( const std::string& name, float gain, float pan )
{
	Mix_Chunk* chunk = SoundNamed(name);
	if (!chunk)
		return;
	Uint8 ipan = pan * 127;
	int ivolume = gain * (MIX_MAX_VOLUME / 2);
	int channel = Mix_GroupAvailable(-1);
	Mix_UnregisterAllEffects(channel);
	if (ipan != 127)
		Mix_SetPanning(channel, 0xFF - ipan, ipan);
	if (fabs(gain - 1.0f) > 0.0003f)
		Mix_SetDistance(channel, 1 / gain);
	Mix_PlayChannel(channel, chunk, 0);
}

void PlayMusic ( const std::string& music )
{
	if (disable_music)
		return;
	Mix_Music* mus = MusicNamed(music);
	if (mus)
	{
		Mix_PlayMusic(mus, -1);
		songName = music;
	}
}

void StopMusic ()
{
	songName = "(no song)";
	Mix_HaltMusic();
}

std::string MusicName ()
{
	return songName;
}

float MusicVolume ()
{
	return Mix_VolumeMusic(-1) / (float)MIX_MAX_VOLUME;
}

void SetMusicVolume ( float _mvol )
{
	Mix_VolumeMusic(_mvol * MIX_MAX_VOLUME);
}

float SoundVolume ()
{
	return Mix_Volume(-1, -1) / (float)MIX_MAX_VOLUME;
}

void SetSoundVolume ( float _mvol )
{
	Mix_Volume(-1, MIX_MAX_VOLUME * _mvol);
}

}
<commit_msg>Sound update: use Mix_Init.<commit_after>#include "Sound.h"
#ifdef WIN32
#include <SDL/SDL_mixer.h>
#else
#include <SDL_mixer/SDL_mixer.h>
#endif
#include <SDL/SDL.h>
#include <queue>

#include <map>
#include <math.h>
#include "Utilities/ResourceManager.h"
#include "Logging.h"

namespace Sound
{

namespace Internal
{

typedef std::map<std::string, Mix_Chunk*> EffectsMap;
typedef std::map<std::string, Mix_Music*> MusicMap;
std::queue<std::string> preloadQueue;
EffectsMap effects;
MusicMap musics;

SDL_mutex* effectMapLock = NULL;
SDL_mutex* preloadQueueLock = NULL;
SDL_cond* preloadQueueCondition = NULL;

Mix_Chunk* SoundNamed ( const std::string& name )
{
	SDL_LockMutex(effectMapLock);
	EffectsMap::iterator iter = effects.find(name);
	if (iter == effects.end())
	{
		// load the sound
		std::string path = "Sounds/" + name + ".aiff";
		SDL_RWops* ops = ResourceManager::OpenFile(path);
		Mix_Chunk* newChunk = Mix_LoadWAV_RW(ops, 1);
		if (!newChunk)
		{
            LOG("Sound", LOG_WARNING, "Decoding sound '%s' failed! Error: %s", name.c_str(), Mix_GetError());
			effects[name] = NULL;
			SDL_UnlockMutex(effectMapLock);
			return NULL;
		}
		effects[name] = newChunk;
		SDL_UnlockMutex(effectMapLock);
		return newChunk;
	}
	else
	{
		SDL_UnlockMutex(effectMapLock);
		return iter->second;
	}
}

void PreloadingThread ()
{
	SDL_LockMutex(preloadQueueLock);
	while (SDL_CondWait(preloadQueueCondition, preloadQueueLock))
	{
		while (!preloadQueue.empty())
		{
			std::string nextSound = preloadQueue.front();
			preloadQueue.pop();
			SoundNamed(nextSound);
		}
	}
}

const char* extensions[] =
{
	".s3m",
	".ogg",
	".xm",
	".mod",
	".aiff",
	NULL
};

Mix_Music* MusicNamed ( const std::string& name )
{
	MusicMap::iterator iter = musics.find(name);
	if (iter == musics.end())
	{
		// load the sound
		Mix_Music* newMusic = NULL;
		for (unsigned i = 0; extensions[i] != NULL; i++)
		{
			std::string path = "Music/" + name + extensions[i];
			SDL_RWops* ops = ResourceManager::OpenFile(path);
			if (!ops)
				continue;
			newMusic = Mix_LoadMUS_RW(ops);
			if (newMusic)
				break;
		}
		musics[name] = newMusic;
		return newMusic;
	}
	else
	{
		return iter->second;
	}
}

std::string songName;

}

using namespace Internal;

static bool disable_music = false;

void Init ( int frequency, int resolution, int sources )
{
	Mix_Init(MIX_INIT_MOD|MIX_INIT_OGG);
	int volume_sound = MIX_MAX_VOLUME, volume_music = MIX_MAX_VOLUME;
	Uint16 format;
	switch (resolution)
	{
		case 8:
			format = AUDIO_S8;
			break;
		case 16:
			format = AUDIO_S16SYS;
			break;
/*		case 24:
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
			format = 0x8018;
#else
			format = 0x9018;
#endif
			break;*/
		default:
            LOG("Sound", LOG_NOTICE, "Unsupported audio format, defaulting to 16-bit");
			format = AUDIO_S16SYS;
			break;
	}
	Mix_OpenAudio(frequency, format, 2, 4096);
	Mix_AllocateChannels(sources);
	Mix_VolumeMusic(volume_music);
	Mix_Volume(-1, volume_sound);
	if (getenv("APOLLO_MUSIC_DISABLE"))
		disable_music = true;
	effectMapLock = SDL_CreateMutex();
	preloadQueueLock = SDL_CreateMutex();
	preloadQueueCondition = SDL_CreateCond();
}

void Preload ( const std::string& name )
{
	SDL_LockMutex(preloadQueueLock);
	preloadQueue.push(name);
	SDL_UnlockMutex(preloadQueueLock);
	SDL_CondSignal(preloadQueueCondition);
}

void PlaySoundSDL ( const std::string& name, float gain, float pan )
{
	Mix_Chunk* chunk = SoundNamed(name);
	if (!chunk)
		return;
	Uint8 ipan = pan * 127;
	int ivolume = gain * (MIX_MAX_VOLUME / 2);
	int channel = Mix_GroupAvailable(-1);
	Mix_UnregisterAllEffects(channel);
	if (ipan != 127)
		Mix_SetPanning(channel, 0xFF - ipan, ipan);
	if (fabs(gain - 1.0f) > 0.0003f)
		Mix_SetDistance(channel, 1 / gain);
	Mix_PlayChannel(channel, chunk, 0);
}

void PlayMusic ( const std::string& music )
{
	if (disable_music)
		return;
	Mix_Music* mus = MusicNamed(music);
	if (mus)
	{
		Mix_PlayMusic(mus, -1);
		songName = music;
	}
}

void StopMusic ()
{
	songName = "(no song)";
	Mix_HaltMusic();
}

std::string MusicName ()
{
	return songName;
}

float MusicVolume ()
{
	return Mix_VolumeMusic(-1) / (float)MIX_MAX_VOLUME;
}

void SetMusicVolume ( float _mvol )
{
	Mix_VolumeMusic(_mvol * MIX_MAX_VOLUME);
}

float SoundVolume ()
{
	return Mix_Volume(-1, -1) / (float)MIX_MAX_VOLUME;
}

void SetSoundVolume ( float _mvol )
{
	Mix_Volume(-1, MIX_MAX_VOLUME * _mvol);
}

}
<|endoftext|>


<commit_before>/*
 *   CrissCross
 *   A multi-purpose cross-platform library.
 *
 *   A product of IO.IN Research.
 *
 *   (c) 2006-2008 Steven Noonan.
 *   Licensed under the New BSD License.
 *
 */

#include "header.h"

using namespace CrissCross::Data;
using namespace CrissCross::IO;
using namespace CrissCross::System;
using namespace std;

Console *console = NULL;

void BenchmarkDArray(Sorter<char *> &sorter)
{
	DArray<char *> data, rdata;
	Stopwatch sw;
	char buffer[512], format[64];
	sprintf(format, "%s", "%4.3lfs");

	FileReader file;

	file.SetLineEndings(CC_LN_LF);
	file.Open("dataset");

	if (file.IsOpen()) {
		data.setStepDouble();
		rdata.setStepDouble();

		console->Write("Loading... ");

		sw.Start();

		/* Load the file into the data DArray */
		while (file.ReadLine(buffer, sizeof(buffer)) >= 0)
			data.insert(cc_strdup(buffer));

		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		file.Close();

		console->WriteLine("Loaded %d items.", data.used());

		console->Write("Random: ");
		sw.Start();
		data.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		/* Create a reverse-sorted DArray */
		for (long i = (long)data.size(); i >= 0; i--) {
			if (data.valid(i)) {
				rdata.insert(data.get(i));
			}
		}

		console->Write("Pre-sorted: ");
		sw.Start();
		data.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		console->Write("Reverse-sorted: ");
		sw.Start();
		rdata.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		for (size_t i = 0; i < data.size(); i++) {
			if (data.valid(i)) {
				free(data.get(i));
				data.remove(i);
			}
		}

		data.empty();
		rdata.empty();
	} else {
		console->WriteLine("Dataset not found.");
	}
}

int RunApplication(int argc, char * *argv)
{
	console = new Console();

#if !defined (DISABLE_DEPRECATED_CODE)
	BubbleSort<char *>    bs;
	QuickSort<char *>     qs;
	InsertionSort<char *> is;
#endif
	HeapSort<char *>      hs;
	CombSort<char *>      cs;
	ShellSort<char *>     ss;

#ifdef TARGET_OS_NDSFIRMWARE
	chdir("/data/SortBenchmark/");
#endif
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("HeapSort...");
	console->SetColour();
	BenchmarkDArray(hs);
	console->WriteLine();
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("CombSort...");
	console->SetColour();
	BenchmarkDArray(cs);
	console->WriteLine();
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("ShellSort...");
	console->SetColour();
	BenchmarkDArray(ss);
	console->WriteLine();
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("QuickSort...");
	console->SetColour();
	BenchmarkDArray(qs);
	console->WriteLine();
#if !defined (DISABLE_DEPRECATED_CODE)
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("BubbleSort...");
	console->SetColour();
	BenchmarkDArray(bs);
	console->WriteLine();
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("InsertionSort...");
	console->SetColour();
	BenchmarkDArray(is);
	console->WriteLine();
#endif

#ifdef TARGET_OS_WINDOWS
	system("pause");
#endif

	delete console;
	return 0;
}
<commit_msg>SortBenchmark: remove obsolete bubblesort tests<commit_after>/*
 *   CrissCross
 *   A multi-purpose cross-platform library.
 *
 *   A product of IO.IN Research.
 *
 *   (c) 2006-2008 Steven Noonan.
 *   Licensed under the New BSD License.
 *
 */

#include "header.h"

using namespace CrissCross::Data;
using namespace CrissCross::IO;
using namespace CrissCross::System;
using namespace std;

Console *console = NULL;

void BenchmarkDArray(Sorter<char *> &sorter)
{
	DArray<char *> data, rdata;
	Stopwatch sw;
	char buffer[512], format[64];
	sprintf(format, "%s", "%4.3lfs");

	FileReader file;

	file.SetLineEndings(CC_LN_LF);
	file.Open("dataset");

	if (file.IsOpen()) {
		data.setStepDouble();
		rdata.setStepDouble();

		console->Write("Loading... ");

		sw.Start();

		/* Load the file into the data DArray */
		while (file.ReadLine(buffer, sizeof(buffer)) >= 0)
			data.insert(cc_strdup(buffer));

		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		file.Close();

		console->WriteLine("Loaded %d items.", data.used());

		console->Write("Random: ");
		sw.Start();
		data.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		/* Create a reverse-sorted DArray */
		for (long i = (long)data.size(); i >= 0; i--) {
			if (data.valid(i)) {
				rdata.insert(data.get(i));
			}
		}

		console->Write("Pre-sorted: ");
		sw.Start();
		data.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		console->Write("Reverse-sorted: ");
		sw.Start();
		rdata.sort(sorter);
		sw.Stop();
		console->WriteLine(format, sw.Elapsed());

		for (size_t i = 0; i < data.size(); i++) {
			if (data.valid(i)) {
				free(data.get(i));
				data.remove(i);
			}
		}

		data.empty();
		rdata.empty();
	} else {
		console->WriteLine("Dataset not found.");
	}
}

int RunApplication(int argc, char * *argv)
{
	console = new Console();

#if !defined (DISABLE_DEPRECATED_CODE)
	QuickSort<char *>     qs;
	InsertionSort<char *> is;
#endif
	HeapSort<char *>      hs;
	CombSort<char *>      cs;
	ShellSort<char *>     ss;

#ifdef TARGET_OS_NDSFIRMWARE
	chdir("/data/SortBenchmark/");
#endif
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("HeapSort...");
	console->SetColour();
	BenchmarkDArray(hs);
	console->WriteLine();
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("CombSort...");
	console->SetColour();
	BenchmarkDArray(cs);
	console->WriteLine();
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("ShellSort...");
	console->SetColour();
	BenchmarkDArray(ss);
	console->WriteLine();
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("QuickSort...");
	console->SetColour();
	BenchmarkDArray(qs);
	console->WriteLine();
#if !defined (DISABLE_DEPRECATED_CODE)
	console->SetColour(console->FG_BLUE | console->FG_INTENSITY);
	console->WriteLine("InsertionSort...");
	console->SetColour();
	BenchmarkDArray(is);
	console->WriteLine();
#endif

#ifdef TARGET_OS_WINDOWS
	system("pause");
#endif

	delete console;
	return 0;
}
<|endoftext|>


<commit_before>#include <string>
#include <time.h>
#include <iostream>
#include <math.h>
#include <map>
#include <vector>

using namespace std;

#ifndef __GNUG__
	#include "stFDR.h"
#endif //__GNUG__

#ifdef __GNUG__
	#include "stFDR.cpp"
#endif //__GNUG__

// default values
#define NORMALIZE_FACTOR 0 // Independent

// global variables
clock_t startTime;

/**
 * Initiates the measurement of run time.
 */
void initClock() {
	startTime=clock();
}//end initClock

/**
 * Prints the elapsed time.
 */
void printElapsed() {
	printf("Elapsed time: %0.3lf sec.\n", (double) (clock() - startTime) / CLOCKS_PER_SEC);
}//end printElapsed

/**
 * Initiates the clustering process.
 *
 * @param argc Number of arguments received.
 * @param argv Array with the arguments received.
 * @return success (0), error (1).
 */
int main(int argc, char **argv) {
	int H = 0;
	int numberOfDimensions = 0;
	double alpha = 0;
	int aux;

	string cellId;
	string tmpCellId;
	int sum;
	int len;
	double level;

	map<string, int> m;
	map<string, int> m2;
	map<string, int>::iterator it;

	// reads the input parameters
	FILE *parameters;
	parameters=fopen("parameters", "r");
	fscanf(parameters,"%lf",&alpha);
	fscanf(parameters,"%d",&H);
	fclose(parameters);

	// reads the data dimensionality
	FILE *dimensionality;
	dimensionality=fopen("dimensionality", "r");
	fscanf(dimensionality,"%d",&numberOfDimensions);
	fclose(dimensionality);

	if(H < 2) { // first validations
		cout << "Error: MrCC needs at least two resolution levels (H >= 2) to perform the clustering process.";
	} // end if

	while(cin) {
		cin >> cellId;
		cin >> sum;

		if(m.find(cellId) == m.end()) {
			m[cellId] = sum;
		} else {
			m[cellId] = m[cellId] + sum;
		}

		for(int i = 0; i < numberOfDimensions; i++) {
			tmpCellId = cellId;
			for(int j = 0; j < cellId.length(); j++) {
				if(j % numberOfDimensions == i) {
					tmpCellId[j] = 'x';
				}
			}

			if(m2.find(tmpCellId) == m2.end()) {
				m2[tmpCellId] = sum;
			} else {
				m2[tmpCellId] = m2[tmpCellId] + sum;
			}
		}

	} // end while

	for(it = m.begin(); it != m.end(); it++) {
		cout << it->first << " " << it->second << "\n";
	}

	cout << "\nCounting removing one variable at a time...\n\n";
	for(it = m2.begin(); it != m2.end(); it++) {
		cout << it->first << " " << it->second << "\n";
	}

	return 0; // success
}<commit_msg>Calculating the log for both sides.<commit_after>#include <stdio.h>
#include <string.h>
#include <string>
#include <cstdlib>
#include <time.h>
#include <iostream>
#include <math.h>
#include <map>
#include <vector>

using namespace std;

#ifndef __GNUG__
	#include "stFDR.h"
#endif //__GNUG__

#ifdef __GNUG__
	#include "stFDR.cpp"
#endif //__GNUG__

// default values
#define NORMALIZE_FACTOR 0 // Independent

// global variables
clock_t startTime;

/**
 * Initiates the measurement of run time.
 */
void initClock() {
	startTime=clock();
}//end initClock

/**
 * Prints the elapsed time.
 */
void printElapsed() {
	printf("Elapsed time: %0.3lf sec.\n", (double) (clock() - startTime) / CLOCKS_PER_SEC);
}//end printElapsed

/**
 * Initiates the clustering process.
 *
 * @param argc Number of arguments received.
 * @param argv Array with the arguments received.
 * @return success (0), error (1).
 */
int main(int argc, char **argv) {
	int H = 0;
	int numberOfDimensions = 0;
	double alpha = 0;
	int aux;

	string cellId;
	string tmpCellId;
	string key;
	int sum;
	int len;
	double level;

	int x;

	map<string, int> m;
	map<string, int> m2;
	map<string, int> calcLog2;
	map<string, int>::iterator it;

	map<int, int> calcLog;
	map<int, int>::iterator it2;

	// reads the input parameters
	FILE *parameters;
	parameters=fopen("parameters", "r");
	fscanf(parameters,"%lf",&alpha);
	fscanf(parameters,"%d",&H);
	fclose(parameters);

	// reads the data dimensionality
	FILE *dimensionality;
	dimensionality=fopen("dimensionality", "r");
	fscanf(dimensionality,"%d",&numberOfDimensions);
	fclose(dimensionality);

	if(H < 2) { // first validations
		cout << "Error: MrCC needs at least two resolution levels (H >= 2) to perform the clustering process.";
	} // end if

	while(cin) {
		cin >> cellId;
		cin >> sum;

		if(m.find(cellId) == m.end()) {
			m[cellId] = sum;
		} else {
			m[cellId] = m[cellId] + sum;
		}

		for(int i = 0; i < numberOfDimensions; i++) {
			tmpCellId = cellId;
			for(int j = 0; j < cellId.length(); j++) {
				if(j % numberOfDimensions == i) {
					tmpCellId[j] = 'x';
				}
			}

			if(m2.find(tmpCellId) == m2.end()) {
				m2[tmpCellId] = sum;
			} else {
				m2[tmpCellId] = m2[tmpCellId] + sum;
			}
		}

	} // end while

	for(it = m.begin(); it != m.end(); it++) {
		cout << it->first << " " << pow(it->second, 2) << "\n";

		len = (it->first).length();
		if(calcLog.find(len) == calcLog.end()) {
			calcLog[len] = pow(it->second, 2);
		} else {
			calcLog[len] = calcLog[len] + pow(it->second, 2);
		}
	}

	cout << "\n";

	for(it2 = calcLog.begin(); it2 != calcLog.end(); it2++) {
		cout << 1.0 / it2->first << " " << log(1.0 / it2->first);
		cout << " " << log(it2->second) << "\n";
	}

	cout << "\nCounting removing one variable at a time...\n\n";

	int i;
	for(it = m2.begin(); it != m2.end(); it++) {
		cout << it->first << " " << pow(it->second, 2) << "\n";

		for(i = 0; i < numberOfDimensions; i++) {
			if((it->first)[i] == 'x') {
				break;
			}
		}

		len = (it->first).length();
		key = to_string(len) + "_" + to_string(i);
		if(calcLog2.find(key) == calcLog2.end()) {
			calcLog2[key] = pow(it->second, 2);
		} else {
			calcLog2[key] = calcLog2[key] + pow(it->second, 2);
		}
	}

	cout << "\n";

	for(it = calcLog2.begin(); it != calcLog2.end(); it++) {
		i = 0;
		x = 0;
		while((it->first)[i] != '_') {
			x = (10 * x) + ((it->first)[i] - 48);
			i++;
		}

		cout << 1.0 / x << " " << log(1.0 / x);
		cout << " " << log(it->second) << "\n";
	}

	return 0; // success
}<|endoftext|>


<commit_before>/*
 *  PathResolver.cpp
 *  openc2e
 *
 *  Created by Bryan Donlan
 *  Copyright (c) 2005 Bryan Donlan. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "PathResolver.h"

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <set>
#include <map>
#include <cctype>
#include <string>
#include <algorithm>
#include <iostream>

using std::map;
using std::set;
using std::string;
using namespace boost::filesystem;

static set<string> dircache;
static map<string, string> cache;

static bool checkDirCache(path &dir);
static bool doCacheDir(path &dir);

/* C++ is far too verbose for its own good */
static string toLowerCase(string in) {
	transform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower);
	return in;
}

static path lcpath(path &orig) {
	return path(toLowerCase(orig.string()), native);
}

static path lcleaf(path &orig) {
	path br, leaf;
	br = orig.branch_path();
	leaf = path(toLowerCase(orig.leaf()), native);
	return br / leaf;
}

bool resolveFile(path &p) {
	string s = p.string();
	if (!resolveFile(s)) {
		// Maybe something changed underneath us; reset the cache and try again
		cache.clear();
		dircache.clear();
		if (!resolveFile(s))
			return false;
	}
	p = path(s, native);
	return true;
}

bool resolveFile_(string &srcPath) {
	path orig(srcPath, native);
	if (exists(orig))
		return true;

	orig.normalize();
	path dir = orig.branch_path();
	path leaf = path(orig.leaf(), native);

	if (!checkDirCache(dir))
		return false;

	orig = dir / lcpath(leaf);
	string fn = orig.string();

	if (exists(orig)) {
		srcPath = fn;
		return true;
	}

	map<string, string>::iterator i = cache.find(fn);
	if (i == cache.end()) {
		assert(!exists(orig));
		return false;
	}
	srcPath = cache[fn];
	return true;
}

bool resolveFile(std::string &path) {
	std::string orig = path;
	bool res = resolveFile_(path);
#if 0
	std::cerr << orig << " -> ";
	if (!res)
		std::cerr << "(nil)";
	else
		std::cerr << path;
	std::cerr << std::endl;
#endif
	return res;
}

/* If dir is cached, do nothing.
 * If dir exists, cache it.
 * If dir does not exist, see if there's one with different capitalization.
 *
 * If we find a dir, return true. Else, false.
 */
bool checkDirCache(path &dir) {
	if (dir == path())
		dir = path(".");
//	std::cerr << "checkDirCache: " << dir.string() << std::endl;
	if (dircache.end() != dircache.find(dir.string())) {
		return true;
	}
	if (exists(dir))
		return doCacheDir(dir);
	if (dir.empty())
		return false;
	bool res = resolveFile(dir);
	if (!res)
		return false;
	return checkDirCache(dir);
}

/* Cache a dir. Return true for success.
 */
bool doCacheDir(path &dir) {
//	std::cerr << "cacheing: " << dir.string() << std::endl;
	directory_iterator it(dir);
	directory_iterator fsend;
	while (it != fsend) {
		path cur = *it++;
		string key, val;
		key = cur.string();
		val = lcleaf(cur).string();
//		std::cerr << "Cache put: " << val << " -> " << key << std::endl;
		cache[val] = key;
	}
	dircache.insert(dir.string());
	return true;
}

static void constructSearchPattern(const std::string &wild, std::vector<std::string> &l) {
	std::string::const_iterator i = wild.begin();
	l.push_back(std::string());
	while (i != wild.end()) {
		if (*i != '*')
			l.back().push_back(*i);
		else
			l.push_back(std::string());
		i++;
	}
}

static bool checkSearchPattern(const std::string &match, const std::vector<std::string> &l) {
	size_t p = 0;
	std::vector<std::string>::const_iterator it = l.begin();
	while (it != l.end()) {
		p = match.find(*it, p);
		if (p == std::string::npos)
			return false;
		it++;
	}
	if (match.substr(match.length() - l.back().length()) != l.back())
		return false;
	return true;
}

std::vector<std::string> findByWildcard(std::string dir, std::string wild) {
	cache.clear();
	dircache.clear();

	wild = toLowerCase(wild);

	path dirp(dir, native);
	dirp.normalize();
	if (!resolveFile(dirp))
		return std::vector<std::string>();
	dir = dirp.string();

	if (!doCacheDir(dirp))
		return std::vector<std::string>();
	std::vector<std::string> l, results;
	constructSearchPattern(wild, l);

	std::string lcdir = toLowerCase(dir);
	std::map<string, string>::iterator skey = cache.lower_bound(dir);
	for (; skey != cache.end(); skey++) {
		if (skey->first.length() < lcdir.length())
			break;
		std::string dirpart, filepart; // XXX: we should use boost fops, maybe
		dirpart = skey->first.substr(0, lcdir.length());
		if (dirpart != dir)
			break;
		if (skey->first.length() < lcdir.length() + 2)
			continue;
		filepart = toLowerCase(skey->first.substr(lcdir.length() + 1));
		if (!checkSearchPattern(filepart, l))
			continue;
		results.push_back(skey->second);
	}
	return results;
}

/* vim: set noet: */
<commit_msg>Fix globbing<commit_after>/*
 *  PathResolver.cpp
 *  openc2e
 *
 *  Created by Bryan Donlan
 *  Copyright (c) 2005 Bryan Donlan. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "PathResolver.h"

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/xpressive/xpressive.hpp>
#include <set>
#include <map>
#include <cctype>
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>

using std::map;
using std::set;
using std::string;
using namespace boost::filesystem;
namespace x = boost::xpressive;

static set<string> dircache;
static map<string, string> cache;

static bool checkDirCache(path &dir);
static bool doCacheDir(path &dir);

/* C++ is far too verbose for its own good */
static string toLowerCase(string in) {
	transform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower);
	return in;
}

static path lcpath(path &orig) {
	return path(toLowerCase(orig.string()), native);
}

static path lcleaf(path &orig) {
	path br, leaf;
	br = orig.branch_path();
	leaf = path(toLowerCase(orig.leaf()), native);
	return br / leaf;
}

bool resolveFile(path &p) {
	string s = p.string();
	if (!resolveFile(s)) {
		// Maybe something changed underneath us; reset the cache and try again
		cache.clear();
		dircache.clear();
		if (!resolveFile(s))
			return false;
	}
	p = path(s, native);
	return true;
}

bool resolveFile_(string &srcPath) {
	path orig(srcPath, native);
	if (exists(orig))
		return true;

	orig.normalize();
	path dir = orig.branch_path();
	path leaf = path(orig.leaf(), native);

	if (!checkDirCache(dir))
		return false;

	orig = dir / lcpath(leaf);
	string fn = orig.string();

	if (exists(orig)) {
		srcPath = fn;
		return true;
	}

	map<string, string>::iterator i = cache.find(fn);
	if (i == cache.end()) {
		assert(!exists(orig));
		return false;
	}
	srcPath = cache[fn];
	return true;
}

bool resolveFile(std::string &path) {
	std::string orig = path;
	bool res = resolveFile_(path);
#if 0
	std::cerr << orig << " -> ";
	if (!res)
		std::cerr << "(nil)";
	else
		std::cerr << path;
	std::cerr << std::endl;
#endif
	return res;
}

/* If dir is cached, do nothing.
 * If dir exists, cache it.
 * If dir does not exist, see if there's one with different capitalization.
 *
 * If we find a dir, return true. Else, false.
 */
bool checkDirCache(path &dir) {
	if (dir == path())
		dir = path(".");
//	std::cerr << "checkDirCache: " << dir.string() << std::endl;
	if (dircache.end() != dircache.find(dir.string())) {
		return true;
	}
	if (exists(dir))
		return doCacheDir(dir);
	if (dir.empty())
		return false;
	bool res = resolveFile(dir);
	if (!res)
		return false;
	return checkDirCache(dir);
}

/* Cache a dir. Return true for success.
 */
bool doCacheDir(path &dir) {
//	std::cerr << "cacheing: " << dir.string() << std::endl;
	directory_iterator it(dir);
	directory_iterator fsend;
	while (it != fsend) {
		path cur = *it++;
		string key, val;
		key = cur.string();
		val = lcleaf(cur).string();
//		std::cerr << "Cache put: " << val << " -> " << key << std::endl;
		cache[val] = key;
	}
	dircache.insert(dir.string());
	return true;
}

static x::sregex constructSearchPattern(const std::string &wild) {
	x::sregex scanner;
	scanner = *(x::alnum | x::blank) | (x::s1= x::_);
	std::ostringstream matchstr;
	x::sregex_iterator cur(wild.begin(), wild.end(), scanner);
	x::sregex_iterator end;
	matchstr << "^";
	for (; cur != end; cur++) {
		x::smatch const &what_m = *cur;
		const std::string what = what_m[0];
		if (what == "*")
			matchstr << ".*";
		else if (what == "?")
			matchstr << ".";
		else if (what_m[1] != "")
			matchstr << "[" << what_m[1] << "]";
		else
			matchstr << what_m[0];
	}
	matchstr << "$";
	std::cout << "matchstr " << matchstr.str() << std::endl;
	return x::sregex::compile(matchstr.str());
}

static bool checkSearchPattern(const std::string &match, const x::sregex &l) {
	return x::regex_match(match, l);
}

std::vector<std::string> findByWildcard(std::string dir, std::string wild) {
	cache.clear();
	dircache.clear();

	wild = toLowerCase(wild);

	path dirp(dir, native);
	dirp.normalize();
	if (!resolveFile(dirp))
		return std::vector<std::string>();
	dir = dirp.string();

	if (!doCacheDir(dirp))
		return std::vector<std::string>();
	std::vector<std::string> results;
	x::sregex l = constructSearchPattern(wild);

	std::string lcdir = toLowerCase(dir);
	std::map<string, string>::iterator skey = cache.lower_bound(dir);
	for (; skey != cache.end(); skey++) {
		if (skey->first.length() < lcdir.length())
			break;
		std::string dirpart, filepart; // XXX: we should use boost fops, maybe
		dirpart = skey->first.substr(0, lcdir.length());
		if (dirpart != dir)
			break;
		if (skey->first.length() < lcdir.length() + 2)
			continue;
		filepart = toLowerCase(skey->first.substr(lcdir.length() + 1));
		if (!x::regex_match(filepart, l))
			continue;
		results.push_back(skey->second);
	}
	return results;
}

/* vim: set noet: */
<|endoftext|>


<commit_before>#include "Student.h"
#include <iostream>
#include <iomanip> //For std::setw()

std::string Student::getNumber(void) {
	return this->_number;
}

void Student::setNumber(const std::string& number) {
	this->_number = number;
}

std::string Student::getName(void) {
	return this->_name;
}

void Student::setName(const std::string& name) {
	this->_name = name;
}

std::string Student::getAge(void) {
	return this->_age;
}

void Student::setAge(const std::string& age) {
	this->_age = age;
}

std::string Student::getGender(void) {
	return this->_gender;
}

void Student::setGender(const std::string& gender) {
	this->_gender = gender;
}

std::string Student::getType(void) {
	return this->_type;
}

void Student::setType(const std::string& type) {
	this->_type = type;
}

Student* Student::getNext(void) {
	return this->_next;
}

void Student::setNext(Student* next) {
	this->_next = next;
}

//Copy a student from another student
void Student::copyStudent(Student* destination, Student* source) {
	destination->setNumber(source->getNumber());
	destination->setName(source->getName());
	destination->setGender(source->getGender());
	destination->setAge(source->getAge());
	destination->setType(source->getType());

	return;
}

//Input a Student from a std::istream
void Student::input(std::istream& in) {
	//Read in the information
	in >> this->_number >> this->_name >> this->_gender >> this->_age >> this->_type;

	return;
}

//Output a Student to a std::ostream
void Student::output(std::ostream& out) {
	out << std::setw(10) << this->getNumber() << std::setw(10) << this->getName() << std::setw(6) << this->getGender() << std::setw(6) << this->getAge() << std::setw(20) << this->getType() << std::endl;

	return;
}
<commit_msg>Update Student.cpp<commit_after>#include "Student.h"
#include <iostream>
#include <iomanip> // For std::setw()

std::string Student::getNumber(void) {
	return this->_number;
}

void Student::setNumber(const std::string& number) {
	this->_number = number;
}

std::string Student::getName(void) {
	return this->_name;
}

void Student::setName(const std::string& name) {
	this->_name = name;
}

std::string Student::getAge(void) {
	return this->_age;
}

void Student::setAge(const std::string& age) {
	this->_age = age;
}

std::string Student::getGender(void) {
	return this->_gender;
}

void Student::setGender(const std::string& gender) {
	this->_gender = gender;
}

std::string Student::getType(void) {
	return this->_type;
}

void Student::setType(const std::string& type) {
	this->_type = type;
}

Student* Student::getNext(void) {
	return this->_next;
}

void Student::setNext(Student* next) {
	this->_next = next;
}

// Copies a student from another student
void Student::copyStudent(Student* destination, Student* source) {
	destination->setNumber(source->getNumber());
	destination->setName(source->getName());
	destination->setGender(source->getGender());
	destination->setAge(source->getAge());
	destination->setType(source->getType());

	return;
}

// Inputs a Student from a std::istream
void Student::input(std::istream& in) {
	// Read in the information
	in >> this->_number >> this->_name >> this->_gender >> this->_age >> this->_type;

	return;
}

// Outputs a Student to a std::ostream
void Student::output(std::ostream& out) {
	out << std::setw(10) << this->getNumber() << std::setw(11) << this->getName() << std::setw(7) << this->getGender() << std::setw(7) << this->getAge() << std::setw(21) << this->getType() << std::endl;

	return;
}
<|endoftext|>