<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, 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 copyright holder(s) 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.
 *
 * $Id$
 *
 */
#ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_H_
#define PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_H_

#include <pcl/common/concatenate.h>
#include <pcl/registration/correspondence_estimation.h>
#include <pcl/common/io.h>

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::registration::CorrespondenceEstimationBase<PointSource, PointTarget>::setInputTarget (
    const PointCloudTargetConstPtr &cloud)
{
  if (cloud->points.empty ())
  {
    PCL_ERROR ("[pcl::%s::setInputTarget] Invalid or empty point cloud dataset given!\n", getClassName ().c_str ());
    return;
  }
  target_ = cloud;

  // Set the internal point representation of choice
  if (point_representation_)
    tree_->setPointRepresentation (point_representation_);
}

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> bool
pcl::registration::CorrespondenceEstimationBase<PointSource, PointTarget>::initCompute ()
{
  if (!target_)
  {
    PCL_WARN ("[pcl::%s::compute] No input target dataset was given!\n", getClassName ().c_str ());
    return (false);
  }

  // If the target indices have been given via setIndicesTarget
  if (target_indices_)
    tree_->setInputCloud (target_, target_indices_);
  else
    tree_->setInputCloud (target_);

  return (PCLBase<PointSource>::initCompute ());
}

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::registration::CorrespondenceEstimation<PointSource, PointTarget>::determineCorrespondences (
    pcl::Correspondences &correspondences, double max_distance)
{
  if (!initCompute ())
    return;

  double max_dist_sqr = max_distance * max_distance;

  typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
  correspondences.resize (indices_->size ());

  std::vector<int> index (1);
  std::vector<float> distance (1);
  pcl::Correspondence corr;
  unsigned int nr_valid_correspondences = 0;

  // Check if the template types are the same. If true, avoid a copy.
  // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro!
  if (isSamePointType<PointSource, PointTarget> ())
  {
    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      tree_->nearestKSearch (input_->points[*idx], 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  else
  {
    PointTarget pt;

    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      // Copy the source data to a target PointTarget format so we can search in the tree
      pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> (
            input_->points[*idx],
            pt));

      tree_->nearestKSearch (pt, 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  correspondences.resize (nr_valid_correspondences);
  deinitCompute ();
}

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::registration::CorrespondenceEstimation<PointSource, PointTarget>::determineReciprocalCorrespondences (
    pcl::Correspondences &correspondences, double max_distance)
{
  if (!initCompute ())
    return;

  typedef typename pcl::traits::fieldList<PointSource>::type FieldListSource;
  typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
  typedef typename pcl::intersect<FieldListSource, FieldListTarget>::type FieldList;

  // setup tree for reciprocal search
  pcl::KdTreeFLANN<PointSource> tree_reciprocal;
  // Set the internal point representation of choice
  if (point_representation_)
    tree_reciprocal.setPointRepresentation (point_representation_);

  tree_reciprocal.setInputCloud (input_, indices_);

  double max_dist_sqr = max_distance * max_distance;

  correspondences.resize (indices_->size());
  std::vector<int> index (1);
  std::vector<float> distance (1);
  std::vector<int> index_reciprocal (1);
  std::vector<float> distance_reciprocal (1);
  pcl::Correspondence corr;
  unsigned int nr_valid_correspondences = 0;
  int target_idx = 0;

  // Check if the template types are the same. If true, avoid a copy.
  // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro!
  if (isSamePointType<PointSource, PointTarget> ())
  {
    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      tree_->nearestKSearch (input_->points[*idx], 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      target_idx = index[0];

      tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal);
      if (distance_reciprocal[0] > max_dist_sqr || *idx != index_reciprocal[0])
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  else
  {
    PointTarget pt_src;
    PointSource pt_tgt;

    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      // Copy the source data to a target PointTarget format so we can search in the tree
      pcl::for_each_type <FieldList> (pcl::NdConcatenateFunctor <PointSource, PointTarget> (
            input_->points[*idx],
            pt_src));

      tree_->nearestKSearch (pt_src, 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      target_idx = index[0];

      // Copy the target data to a target PointSource format so we can search in the tree_reciprocal
      pcl::for_each_type<FieldList> (pcl::NdConcatenateFunctor <PointTarget, PointSource> (
            target_->points[target_idx],
            pt_tgt));

      tree_reciprocal.nearestKSearch (pt_tgt, 1, index_reciprocal, distance_reciprocal);
      if (distance_reciprocal[0] > max_dist_sqr || *idx != index_reciprocal[0])
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  correspondences.resize (nr_valid_correspondences);
  deinitCompute ();
}

//#define PCL_INSTANTIATE_CorrespondenceEstimation(T,U) template class PCL_EXPORTS pcl::registration::CorrespondenceEstimation<T,U>;

#endif /* PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_H_ */
<commit_msg>WARN->ERROR<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, 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 copyright holder(s) 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.
 *
 * $Id$
 *
 */
#ifndef PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_H_
#define PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_H_

#include <pcl/common/concatenate.h>
#include <pcl/registration/correspondence_estimation.h>
#include <pcl/common/io.h>

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::registration::CorrespondenceEstimationBase<PointSource, PointTarget>::setInputTarget (
    const PointCloudTargetConstPtr &cloud)
{
  if (cloud->points.empty ())
  {
    PCL_ERROR ("[pcl::%s::setInputTarget] Invalid or empty point cloud dataset given!\n", getClassName ().c_str ());
    return;
  }
  target_ = cloud;

  // Set the internal point representation of choice
  if (point_representation_)
    tree_->setPointRepresentation (point_representation_);
}

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> bool
pcl::registration::CorrespondenceEstimationBase<PointSource, PointTarget>::initCompute ()
{
  if (!target_)
  {
    PCL_ERROR ("[pcl::%s::compute] No input target dataset was given!\n", getClassName ().c_str ());
    return (false);
  }

  // If the target indices have been given via setIndicesTarget
  if (target_indices_)
    tree_->setInputCloud (target_, target_indices_);
  else
    tree_->setInputCloud (target_);

  return (PCLBase<PointSource>::initCompute ());
}

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::registration::CorrespondenceEstimation<PointSource, PointTarget>::determineCorrespondences (
    pcl::Correspondences &correspondences, double max_distance)
{
  if (!initCompute ())
    return;

  double max_dist_sqr = max_distance * max_distance;

  typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
  correspondences.resize (indices_->size ());

  std::vector<int> index (1);
  std::vector<float> distance (1);
  pcl::Correspondence corr;
  unsigned int nr_valid_correspondences = 0;

  // Check if the template types are the same. If true, avoid a copy.
  // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro!
  if (isSamePointType<PointSource, PointTarget> ())
  {
    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      tree_->nearestKSearch (input_->points[*idx], 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  else
  {
    PointTarget pt;

    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      // Copy the source data to a target PointTarget format so we can search in the tree
      pcl::for_each_type <FieldListTarget> (pcl::NdConcatenateFunctor <PointSource, PointTarget> (
            input_->points[*idx],
            pt));

      tree_->nearestKSearch (pt, 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  correspondences.resize (nr_valid_correspondences);
  deinitCompute ();
}

///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget> void
pcl::registration::CorrespondenceEstimation<PointSource, PointTarget>::determineReciprocalCorrespondences (
    pcl::Correspondences &correspondences, double max_distance)
{
  if (!initCompute ())
    return;

  typedef typename pcl::traits::fieldList<PointSource>::type FieldListSource;
  typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
  typedef typename pcl::intersect<FieldListSource, FieldListTarget>::type FieldList;

  // setup tree for reciprocal search
  pcl::KdTreeFLANN<PointSource> tree_reciprocal;
  // Set the internal point representation of choice
  if (point_representation_)
    tree_reciprocal.setPointRepresentation (point_representation_);

  tree_reciprocal.setInputCloud (input_, indices_);

  double max_dist_sqr = max_distance * max_distance;

  correspondences.resize (indices_->size());
  std::vector<int> index (1);
  std::vector<float> distance (1);
  std::vector<int> index_reciprocal (1);
  std::vector<float> distance_reciprocal (1);
  pcl::Correspondence corr;
  unsigned int nr_valid_correspondences = 0;
  int target_idx = 0;

  // Check if the template types are the same. If true, avoid a copy.
  // Both point types MUST be registered using the POINT_CLOUD_REGISTER_POINT_STRUCT macro!
  if (isSamePointType<PointSource, PointTarget> ())
  {
    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      tree_->nearestKSearch (input_->points[*idx], 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      target_idx = index[0];

      tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal);
      if (distance_reciprocal[0] > max_dist_sqr || *idx != index_reciprocal[0])
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  else
  {
    PointTarget pt_src;
    PointSource pt_tgt;

    // Iterate over the input set of source indices
    for (std::vector<int>::const_iterator idx = indices_->begin (); idx != indices_->end (); ++idx)
    {
      // Copy the source data to a target PointTarget format so we can search in the tree
      pcl::for_each_type <FieldList> (pcl::NdConcatenateFunctor <PointSource, PointTarget> (
            input_->points[*idx],
            pt_src));

      tree_->nearestKSearch (pt_src, 1, index, distance);
      if (distance[0] > max_dist_sqr)
        continue;

      target_idx = index[0];

      // Copy the target data to a target PointSource format so we can search in the tree_reciprocal
      pcl::for_each_type<FieldList> (pcl::NdConcatenateFunctor <PointTarget, PointSource> (
            target_->points[target_idx],
            pt_tgt));

      tree_reciprocal.nearestKSearch (pt_tgt, 1, index_reciprocal, distance_reciprocal);
      if (distance_reciprocal[0] > max_dist_sqr || *idx != index_reciprocal[0])
        continue;

      corr.index_query = *idx;
      corr.index_match = index[0];
      corr.distance = distance[0];
      correspondences[nr_valid_correspondences++] = corr;
    }
  }
  correspondences.resize (nr_valid_correspondences);
  deinitCompute ();
}

//#define PCL_INSTANTIATE_CorrespondenceEstimation(T,U) template class PCL_EXPORTS pcl::registration::CorrespondenceEstimation<T,U>;

#endif /* PCL_REGISTRATION_IMPL_CORRESPONDENCE_ESTIMATION_H_ */
<|endoftext|>


<commit_before>/**  Manages the event handling functions in the superloop
 *
 * StageManager.cpp
 * Created 1-28-18 By: Smitty
 *
 * A longer description.
 */

#include "StageManager.hpp"

/**
 * @brief  StageManager constructor
 */
StageManager::StageManager(void)
{
    timerList = new Timer[TIMER_NUM];
    timerList[0].limit = LED_1_POLL;
    timerList[1].limit = LED_2_POLL;
    // timerList[2].limit = LED_3_POLL;
    // timerList[3].limit = LED_4_POLL;

    //initializing the variables in the Timer array
    for(int i = 0; i < TIMER_NUM; i++)
    {
        //creating the individual mask for each timer
        timerList[i].TFmask = 1 << i;
        timerList[i].count = 0;
    }
}

/**
 * @brief  Handles the multiple timers running off of a single 1ms timer from main
 * @note   Might have to be fleshed out more
 * @retval uint32_t with each bit coresponding to which timers went off
 */
uint32_t StageManager::processTimers(Stage currentStage)
{
    //Goes through the array of timers to increment their count and store which ones popped
    for (int i = 0; i < TIMER_NUM; i++)
    {
        timerList[i].count++;
        if(timerList[i].count >= timerList[i].limit)
        {
            //store which timer popped
            timerTF |= timerList[i].TFmask;

            //resetting the count of the timer that just popped
            timerList[i].count = 0;
        }

    }

    return timerTF;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processCan(Stage currentStage)
{
    //do CAN stuff
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processCooling(Stage currentStage)
{
    //do Cooling stuff
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processDash(Stage currentStage)
{
    //do Dash processing

    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processGlcd(Stage currentStage)
{
    //glcd view display updating

    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processImd(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processOrion(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processPedal(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processSdCard(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processUnitek(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processBatlog(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processPrecharge(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processReadyToDrive(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processLaunch(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processShutdown(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note   Entry condition: EVOS finishes subsystem testing
 *         Exit condition:  Driver requests Precharging
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsStandby(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_STANDBY;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:

            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:

            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:

            if(localEventFlags && EF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_GLCD;
            }

            if(localEventFlags && EF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SDCARD;
            }

        break;

    } //End switch

    return currentStage;
}

/**
 * @brief
 * @note   Entry condition: Driver requests Precharging
 *         Exit condition:  Precharge done signal recieved from Unitek
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsPrecharge(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_PRECHARGE;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:
            //code here
            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:
            //code here
            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:
            //code here

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:
            //code here
            if(localEventFlags && EF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SDCARD;
            }

            if(localEventFlags && EF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_GLCD;
            }

        break;

    } //End switch

    return currentStage;
}

/**
 * @brief
 * @note   Entry condition: Precharge done signal recieved from Unitek
 *         Exit condition:  Driver requests ready to drive
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsEnergized(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_ENERGIZED;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:
            //code here
            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:
            //code here
            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:
            //code here

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:
            //code here
            if(localEventFlags && EF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_GLCD;
            }

            if(localEventFlags && EF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SDCARD;
            }

        break;

    } //End switch

    return currentStage;
}

/**
 * @brief
 * @note   Entry condition: Driver requests ready to drive
 *         Exit condition:  Driver requests standby
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsDriving(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_STANDBY;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:
            //code here
            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:
            //code here
            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:
            //code here

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:
            //code here
            if(localEventFlags && EF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_GLCD;
            }

            if(localEventFlags && EF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SDCARD;
            }

        break;

    } //End switch

    return currentStage;
}<commit_msg>#40 changing the variable names because I forgot to<commit_after>/**  Manages the event handling functions in the superloop
 *
 * StageManager.cpp
 * Created 1-28-18 By: Smitty
 *
 * A longer description.
 */

#include "StageManager.hpp"

/**
 * @brief  StageManager constructor
 */
StageManager::StageManager(void)
{
    timerList = new Timer[TIMER_NUM];
    timerList[0].limit = LED_1_POLL;
    timerList[1].limit = LED_2_POLL;
    // timerList[2].limit = LED_3_POLL;
    // timerList[3].limit = LED_4_POLL;

    //initializing the variables in the Timer array
    for(int i = 0; i < TIMER_NUM; i++)
    {
        //creating the individual mask for each timer
        timerList[i].TFmask = 1 << i;
        timerList[i].count = 0;
    }
}

/**
 * @brief  Handles the multiple timers running off of a single 1ms timer from main
 * @note   Might have to be fleshed out more
 * @retval uint32_t with each bit coresponding to which timers went off
 */
uint32_t StageManager::processTimers(Stage currentStage)
{
    //Goes through the array of timers to increment their count and store which ones popped
    for (int i = 0; i < TIMER_NUM; i++)
    {
        timerList[i].count++;
        if(timerList[i].count >= timerList[i].limit)
        {
            //store which timer popped
            timerTF |= timerList[i].TFmask;

            //resetting the count of the timer that just popped
            timerList[i].count = 0;
        }

    }

    return timerTF;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processCan(Stage currentStage)
{
    //do CAN stuff
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processCooling(Stage currentStage)
{
    //do Cooling stuff
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processDash(Stage currentStage)
{
    //do Dash processing

    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processGlcd(Stage currentStage)
{
    //glcd view display updating

    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processImd(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processOrion(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processPedal(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processSdCard(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processUnitek(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processBatlog(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processPrecharge(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processReadyToDrive(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processLaunch(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note
 * @retval
 */
uint32_t StageManager::processShutdown(Stage currentStage)
{
    return 0;
}

/**
 * @brief
 * @note   Entry condition: EVOS finishes subsystem testing
 *         Exit condition:  Driver requests Precharging
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsStandby(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_STANDBY;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:

            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:

            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:

            if(localEventFlags && TF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_GLCD;
            }

            if(localEventFlags && TF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_SDCARD;
            }

        break;

    } //End switch

    return currentStage;
}

/**
 * @brief
 * @note   Entry condition: Driver requests Precharging
 *         Exit condition:  Precharge done signal recieved from Unitek
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsPrecharge(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_PRECHARGE;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:
            //code here
            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:
            //code here
            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:
            //code here

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:
            //code here
            if(localEventFlags && TF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_SDCARD;
            }

            if(localEventFlags && TF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_GLCD;
            }

        break;

    } //End switch

    return currentStage;
}

/**
 * @brief
 * @note   Entry condition: Precharge done signal recieved from Unitek
 *         Exit condition:  Driver requests ready to drive
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsEnergized(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_ENERGIZED;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:
            //code here
            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:
            //code here
            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:
            //code here

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:
            //code here
            if(localEventFlags && TF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_GLCD;
            }

            if(localEventFlags && TF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_SDCARD;
            }

        break;

    } //End switch

    return currentStage;
}

/**
 * @brief
 * @note   Entry condition: Driver requests ready to drive
 *         Exit condition:  Driver requests standby
 * @param  &localEventFlags:
 * @param  urgencyLevel:
 * @retval
 */
StageManager::Stage StageManager::processEventsDriving(uint32_t &localEventFlags, Priority urgencyLevel)
{
    Stage currentStage = Stage::STAGE_STANDBY;

    switch(urgencyLevel)
    {
        case PRIORITY_CRITICAL:
            //code here
            if(localEventFlags && EF_SHUTDOWN)
            {
                processShutdown(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_SHUTDOWN;
            }

            if(localEventFlags && EF_IMD)
            {
                processImd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_IMD;
            }

        break;

        case PRIORITY_HIGH:
            //code here
            if(localEventFlags && EF_CAN)
            {
                processCan(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_CAN;
            }

            if(localEventFlags && EF_UNITEK)
            {
                processUnitek(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_UNITEK;
            }

            if(localEventFlags && EF_ORION)
            {
                processOrion(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_ORION;
            }

        break;

        case PRIORITY_MEDIUM:
            //code here

             if(localEventFlags && EF_COOLING)
            {
                processCooling(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_COOLING;
            }

            if(localEventFlags && EF_BATLOG)
            {
                processBatlog(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_BATLOG;
            }

            if(localEventFlags && EF_DASH)
            {
                processDash(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~EF_DASH;
            }

        break;

        case PRIORITY_LOW:
            //code here
            if(localEventFlags && TF_GLCD)
            {
                processGlcd(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_GLCD;
            }

            if(localEventFlags && TF_SDCARD)
            {
                processSdCard(currentStage);

                //clearing the EF so we don't trigger this again
                localEventFlags &= ~TF_SDCARD;
            }

        break;

    } //End switch

    return currentStage;
}<|endoftext|>


<commit_before>
#pragma once

#include <QString>

#include <reflectionzeug/property/Property.h>

namespace reflectionzeug
{

/**
*  @brief
*    Property implementation for QString
*/
class PropertyQString : public reflectionzeug::AbstractValueProperty<QString>, public AbstractStringInterface
{
public:
    /**
    *  @brief
    *    Constructor
    */
    template <typename... Arguments>
    PropertyQString(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<QString>(std::forward<Arguments>(args)...)
    {
    }

    // Virtual AbstractProperty interface
    virtual std::string toString() const override
    {
        return this->value().toStdString();
    }

    virtual bool fromString(const std::string & string) override
    {
        this->setValue(QString::fromStdString(string));
        return true;
    }

    virtual Variant toVariant() const override
    {
        // Return string
        return Variant(this->value().toStdString());
    }

    virtual bool fromVariant(const Variant & value) override
    {
        // Read from string
        if (value.hasType<std::string>() || value.canConvert<std::string>()) {
            this->setValue(QString::fromStdString(value.value<std::string>()));
            return true;
        }

        // Invalid value
        return false;
    }

    virtual void accept(AbstractVisitor * visitor) override
    {
        visitor->callVisitor<PropertyQString>(this);
        visitor->callVisitor<AbstractStringInterface>(this);
    }
};

/**
*  @brief
*    Property selector for properties of type QString
*/
template <>
struct PropertyTypeSelector<QString>
{
    using Type = PropertyQString;
};

} // namespace reflectionzeug
<commit_msg>Implement property class for QColor<commit_after>
#pragma once

#include <QString>
#include <QColor>

#include <reflectionzeug/property/Property.h>

namespace reflectionzeug
{

/**
*  @brief
*    Property implementation for QString
*/
class PropertyQString : public reflectionzeug::AbstractValueProperty<QString>, public AbstractStringInterface
{
public:
    /**
    *  @brief
    *    Constructor
    */
    template <typename... Arguments>
    PropertyQString(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<QString>(std::forward<Arguments>(args)...)
    {
    }

    // Virtual AbstractProperty interface
    virtual std::string toString() const override
    {
        return this->value().toStdString();
    }

    virtual bool fromString(const std::string & string) override
    {
        this->setValue(QString::fromStdString(string));
        return true;
    }

    virtual Variant toVariant() const override
    {
        // Return string
        return Variant(this->value().toStdString());
    }

    virtual bool fromVariant(const Variant & value) override
    {
        // Read from string
        if (value.hasType<std::string>() || value.canConvert<std::string>()) {
            this->setValue(QString::fromStdString(value.value<std::string>()));
            return true;
        }

        // Invalid value
        return false;
    }

    virtual void accept(AbstractVisitor * visitor) override
    {
        visitor->callVisitor<PropertyQString>(this);
        visitor->callVisitor<AbstractStringInterface>(this);
    }
};

/**
*  @brief
*    Property implementation for QColor
*/
class PropertyQColor : public reflectionzeug::AbstractValueProperty<QColor>, public AbstractColorInterface
{
public:
    /**
    *  @brief
    *    Constructor
    */
    template <typename... Arguments>
    PropertyQColor(Arguments&&... args)
    : reflectionzeug::AbstractValueProperty<QColor>(std::forward<Arguments>(args)...)
    {
    }

    // Virtual AbstractColorInterface interface
    virtual void getRGBA(int & r, int & g, int & b, int & a) const override
    {
        QColor color = this->value();
        r = color.red();
        g = color.green();
        b = color.blue();
        a = color.alpha();
    }

    virtual void setRGBA(int r, int g, int b, int a) override
    {
        this->setValue(QColor(r, g, b, a));
    }

    virtual int red() const override
    {
        return this->value().red();
    }

    virtual void setRed(int red) override
    {
        QColor color = this->value();
        color.setRed(red);
        this->setValue(color);
    }

    virtual int green() const override
    {
        return this->value().green();
    }

    virtual void setGreen(int green) override
    {
        QColor color = this->value();
        color.setGreen(green);
        this->setValue(color);
    }

    virtual int blue() const override
    {
        return this->value().blue();
    }

    virtual void setBlue(int blue) override
    {
        QColor color = this->value();
        color.setBlue(blue);
        this->setValue(color);
    }

    virtual int alpha() const override
    {
        return this->value().alpha();
    }

    virtual void setAlpha(int alpha) override
    {
        QColor color = this->value();
        color.setAlpha(alpha);
        this->setValue(color);
    }

    // Virtual AbstractProperty interface
    virtual std::string toString() const override
    {
        // Return hex representation
        return toHexString();
    }

    virtual bool fromString(const std::string & string) override
    {
        // Read from hex representation
        return fromHexString(string);
    }

    virtual Variant toVariant() const override
    {
        // Return color as variant object
        return toColorVariant();
    }

    virtual bool fromVariant(const Variant & value) override
    {
        // Read from variant of the exact type
        if (value.hasType<QColor>() || value.canConvert<QColor>()) {
            setValue( value.value<QColor>() );
            return true;
        }

        // Read from string or object representation
        else {
            return fromColorVariant(value);
        }
    }

    virtual void accept(AbstractVisitor * visitor) override
    {
        visitor->callVisitor<PropertyQColor>(this);
        visitor->callVisitor<AbstractColorInterface>(this);
    }
};

/**
*  @brief
*    Property selector for properties of type QString
*/
template <>
struct PropertyTypeSelector<QString>
{
    using Type = PropertyQString;
};

/**
*  @brief
*    Property selector for properties of type QColor
*/
template <>
struct PropertyTypeSelector<QColor>
{
    using Type = PropertyQColor;
};

} // namespace reflectionzeug
<|endoftext|>


<commit_before>/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
  Part of the Wiring project - http://wiring.org.co
  Copyright (c) 2004-06 Hernando Barragan
  Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/

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

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

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA

  $Id$
*/

extern "C" {
  #include "stdlib.h"
}

void randomSeed(unsigned int seed)
{
  if(seed != 0){
    srand(seed);
  }
}

long random(long howbig)
{
  long value;
  if (howbig == 0){
    return 0;
  }
  return rand() % howbig;
}

long random(long howsmall, long howbig)
{
  if(howsmall >= howbig){
    return howsmall;
  }
  long diff = howbig - howsmall;
  return random(diff) + howsmall;
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}<commit_msg>added newline at the end of file to get rid of compiler and SVN warnings<commit_after>/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
  Part of the Wiring project - http://wiring.org.co
  Copyright (c) 2004-06 Hernando Barragan
  Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/

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

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

  You should have received a copy of the GNU Lesser General
  Public License along with this library; if not, write to the
  Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  Boston, MA  02111-1307  USA

  $Id$
*/

extern "C" {
  #include "stdlib.h"
}

void randomSeed(unsigned int seed)
{
  if(seed != 0){
    srand(seed);
  }
}

long random(long howbig)
{
  long value;
  if (howbig == 0){
    return 0;
  }
  return rand() % howbig;
}

long random(long howsmall, long howbig)
{
  if(howsmall >= howbig){
    return howsmall;
  }
  long diff = howbig - howsmall;
  return random(diff) + howsmall;
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
<|endoftext|>


<commit_before>#include <utility>
#include "api/halley_api.h"
#include <halley/plugin/plugin.h>
#include "halley/audio/audio_facade.h"
#include "halley/support/logger.h"
#include "entry/entry_point.h"

using namespace Halley;

void HalleyAPI::assign()
{
	Expects(coreInternal != nullptr);
	Expects(systemInternal != nullptr);

	core = coreInternal;
	system = systemInternal.get();

	if (videoInternal) {
		video = videoInternal.get();
	}
	if (inputInternal) {
		input = inputInternal.get();
	}
	if (audioInternal) {
		audio = audioInternal.get();
	}
	if (platformInternal) {
		platform = platformInternal.get();
	}
	if (networkInternal) {
		network = networkInternal.get();
	}
	if (movieInternal) {
		movie = movieInternal.get();
	}
}

void HalleyAPI::init()
{
	if (systemInternal) {
		systemInternal->init();
	}
	if (videoInternal) {
		videoInternal->init();
	}
	if (inputInternal) {
		inputInternal->init();
	}
	if (audioOutputInternal) {
		audioOutputInternal->init();
	}
	if (audioInternal) {
		audioInternal->init();
	}
	if (platformInternal) {
		platformInternal->init();
	}
	if (networkInternal) {
		networkInternal->init();
	}
	if (movieInternal) {
		movieInternal->init();
	}
}

void HalleyAPI::deInit()
{
	if (movieInternal) {
		movieInternal->deInit();
	}
	if (networkInternal) {
		networkInternal->deInit();
	}
	if (platformInternal) {
		platformInternal->deInit();
	}
	if (audioInternal) {
		audioInternal->deInit();
	}
	if (audioOutputInternal) {
		audioOutputInternal->deInit();
	}
	if (inputInternal) {
		inputInternal->deInit();
	}
	if (videoInternal) {
		videoInternal->deInit();
	}
	if (systemInternal) {
		systemInternal->deInit();
	}
}

std::unique_ptr<HalleyAPI> HalleyAPI::create(CoreAPIInternal* core, int flags)
{
	auto api = std::make_unique<HalleyAPI>();
	api->coreInternal = core;

	HalleyAPIFlags::Flags flagList[] = { HalleyAPIFlags::System, HalleyAPIFlags::Video, HalleyAPIFlags::Input, HalleyAPIFlags::Audio, HalleyAPIFlags::Network, HalleyAPIFlags::Platform, HalleyAPIFlags::Movie };
	PluginType pluginTypes[] = { PluginType::SystemAPI, PluginType::GraphicsAPI, PluginType::InputAPI, PluginType::AudioOutputAPI, PluginType::NetworkAPI, PluginType::PlatformAPI, PluginType::MovieAPI };
	String names[] = { "System", "Graphics", "Input", "AudioOutput", "Network", "Platform", "Movie" };

	constexpr size_t n = std::end(flagList) - std::begin(flagList);
	for (size_t i = 0; i < n; ++i) {
		if (flags & flagList[i] || flagList[i] == HalleyAPIFlags::System) {
			auto plugins = core->getPlugins(pluginTypes[i]);
			if (!plugins.empty()) {
				Logger::logInfo(names[i] + " plugin: " + plugins[0]->getName());
				api->setAPI(pluginTypes[i], plugins[0]->createAPI(api->systemInternal.get()));
			} else {
				throw Exception("No suitable " + names[i] + " plugins found.", HalleyExceptions::Core);
			}
		}
	}

	api->assign();
	return api;
}

void HalleyAPI::setAPI(PluginType pluginType, HalleyAPIInternal* api)
{
	switch (pluginType) {
	case PluginType::SystemAPI:
		systemInternal.reset(dynamic_cast<SystemAPIInternal*>(api));
		return;
	case PluginType::InputAPI:
		inputInternal.reset(dynamic_cast<InputAPIInternal*>(api));
		return;
	case PluginType::GraphicsAPI:
		videoInternal.reset(dynamic_cast<VideoAPIInternal*>(api));
		return;
	case PluginType::AudioOutputAPI:
		audioOutputInternal.reset(dynamic_cast<AudioOutputAPIInternal*>(api));
		audioInternal = std::make_unique<AudioFacade>(*audioOutputInternal, *systemInternal);
		return;
	case PluginType::PlatformAPI:
		platformInternal.reset(dynamic_cast<PlatformAPIInternal*>(api));
		return;
	case PluginType::NetworkAPI:
		networkInternal.reset(dynamic_cast<NetworkAPIInternal*>(api));
		return;
	case PluginType::MovieAPI:
		movieInternal.reset(dynamic_cast<MovieAPIInternal*>(api));
		return;
	}
}

HalleyAPI& HalleyAPI::operator=(const HalleyAPI& other) = default;

std::unique_ptr<HalleyAPI> HalleyAPI::clone() const
{
	auto api = std::make_unique<HalleyAPI>();
	*api = *this;
	return api;
}

void HalleyAPI::replaceCoreAPI(CoreAPIInternal* coreAPI)
{
	coreInternal = coreAPI;
	core = coreAPI;
}

uint32_t Halley::getHalleyDLLAPIVersion()
{
	return 177;
}
<commit_msg>Bump version<commit_after>#include <utility>
#include "api/halley_api.h"
#include <halley/plugin/plugin.h>
#include "halley/audio/audio_facade.h"
#include "halley/support/logger.h"
#include "entry/entry_point.h"

using namespace Halley;

void HalleyAPI::assign()
{
	Expects(coreInternal != nullptr);
	Expects(systemInternal != nullptr);

	core = coreInternal;
	system = systemInternal.get();

	if (videoInternal) {
		video = videoInternal.get();
	}
	if (inputInternal) {
		input = inputInternal.get();
	}
	if (audioInternal) {
		audio = audioInternal.get();
	}
	if (platformInternal) {
		platform = platformInternal.get();
	}
	if (networkInternal) {
		network = networkInternal.get();
	}
	if (movieInternal) {
		movie = movieInternal.get();
	}
}

void HalleyAPI::init()
{
	if (systemInternal) {
		systemInternal->init();
	}
	if (videoInternal) {
		videoInternal->init();
	}
	if (inputInternal) {
		inputInternal->init();
	}
	if (audioOutputInternal) {
		audioOutputInternal->init();
	}
	if (audioInternal) {
		audioInternal->init();
	}
	if (platformInternal) {
		platformInternal->init();
	}
	if (networkInternal) {
		networkInternal->init();
	}
	if (movieInternal) {
		movieInternal->init();
	}
}

void HalleyAPI::deInit()
{
	if (movieInternal) {
		movieInternal->deInit();
	}
	if (networkInternal) {
		networkInternal->deInit();
	}
	if (platformInternal) {
		platformInternal->deInit();
	}
	if (audioInternal) {
		audioInternal->deInit();
	}
	if (audioOutputInternal) {
		audioOutputInternal->deInit();
	}
	if (inputInternal) {
		inputInternal->deInit();
	}
	if (videoInternal) {
		videoInternal->deInit();
	}
	if (systemInternal) {
		systemInternal->deInit();
	}
}

std::unique_ptr<HalleyAPI> HalleyAPI::create(CoreAPIInternal* core, int flags)
{
	auto api = std::make_unique<HalleyAPI>();
	api->coreInternal = core;

	HalleyAPIFlags::Flags flagList[] = { HalleyAPIFlags::System, HalleyAPIFlags::Video, HalleyAPIFlags::Input, HalleyAPIFlags::Audio, HalleyAPIFlags::Network, HalleyAPIFlags::Platform, HalleyAPIFlags::Movie };
	PluginType pluginTypes[] = { PluginType::SystemAPI, PluginType::GraphicsAPI, PluginType::InputAPI, PluginType::AudioOutputAPI, PluginType::NetworkAPI, PluginType::PlatformAPI, PluginType::MovieAPI };
	String names[] = { "System", "Graphics", "Input", "AudioOutput", "Network", "Platform", "Movie" };

	constexpr size_t n = std::end(flagList) - std::begin(flagList);
	for (size_t i = 0; i < n; ++i) {
		if (flags & flagList[i] || flagList[i] == HalleyAPIFlags::System) {
			auto plugins = core->getPlugins(pluginTypes[i]);
			if (!plugins.empty()) {
				Logger::logInfo(names[i] + " plugin: " + plugins[0]->getName());
				api->setAPI(pluginTypes[i], plugins[0]->createAPI(api->systemInternal.get()));
			} else {
				throw Exception("No suitable " + names[i] + " plugins found.", HalleyExceptions::Core);
			}
		}
	}

	api->assign();
	return api;
}

void HalleyAPI::setAPI(PluginType pluginType, HalleyAPIInternal* api)
{
	switch (pluginType) {
	case PluginType::SystemAPI:
		systemInternal.reset(dynamic_cast<SystemAPIInternal*>(api));
		return;
	case PluginType::InputAPI:
		inputInternal.reset(dynamic_cast<InputAPIInternal*>(api));
		return;
	case PluginType::GraphicsAPI:
		videoInternal.reset(dynamic_cast<VideoAPIInternal*>(api));
		return;
	case PluginType::AudioOutputAPI:
		audioOutputInternal.reset(dynamic_cast<AudioOutputAPIInternal*>(api));
		audioInternal = std::make_unique<AudioFacade>(*audioOutputInternal, *systemInternal);
		return;
	case PluginType::PlatformAPI:
		platformInternal.reset(dynamic_cast<PlatformAPIInternal*>(api));
		return;
	case PluginType::NetworkAPI:
		networkInternal.reset(dynamic_cast<NetworkAPIInternal*>(api));
		return;
	case PluginType::MovieAPI:
		movieInternal.reset(dynamic_cast<MovieAPIInternal*>(api));
		return;
	}
}

HalleyAPI& HalleyAPI::operator=(const HalleyAPI& other) = default;

std::unique_ptr<HalleyAPI> HalleyAPI::clone() const
{
	auto api = std::make_unique<HalleyAPI>();
	*api = *this;
	return api;
}

void HalleyAPI::replaceCoreAPI(CoreAPIInternal* coreAPI)
{
	coreInternal = coreAPI;
	core = coreAPI;
}

uint32_t Halley::getHalleyDLLAPIVersion()
{
	return 178;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// --- ROOT system ---
#include <TObjString.h>
#include <TH2F.h>
#include <TClonesArray.h>

//---- AliRoot system ----
#include "AliAnaRandomTrigger.h"
#include "AliCaloTrackParticleCorrelation.h"
#include "AliEMCALGeometry.h"

/// \cond CLASSIMP
ClassImp(AliAnaRandomTrigger) ;
/// \endcond

//__________________________________________
/// Default Constructor. Initialize parameters.
//__________________________________________
AliAnaRandomTrigger::AliAnaRandomTrigger() :
    AliAnaCaloTrackCorrBaseClass(),
    fTriggerDetector(kEMCAL),
    fTriggerDetectorString("EMCAL"),
    fRandom(0),         fNRandom(0),
    fMomentum(),
    fhE(0),             fhPt(0),
    fhPhi(0),           fhEta(0),
    fhEtaPhi(0)
{
  InitParameters();
}

//_________________________________________________________________________
/// Check if there is a dead or bad region in a detector.
/// Only EMCAL for now.
//_________________________________________________________________________
Bool_t AliAnaRandomTrigger::ExcludeDeadBadRegions(Float_t eta, Float_t phi)
{
  if ( fTriggerDetector!=kEMCAL || fTriggerDetector!=kDCAL ) return kFALSE;

  //-------------------------------------
  // Get the corresponding cell in EMCAL, check if it exists in acceptance (phi gaps, borders)
  //-------------------------------------

  Int_t absId = -1;
  if(!GetEMCALGeometry()->GetAbsCellIdFromEtaPhi(eta,phi, absId)) return kTRUE; // remove if out of EMCAL acceptance, phi gaps

  Int_t icol = -1, irow = -1, iRCU = -1;
  Int_t sm = GetCaloUtils()->GetModuleNumberCellIndexes(absId,kEMCAL, icol, irow, iRCU);

  //printf("eta %f, phi %f, ieta %d, iphi %d, sm %d\n",eta,phi,icol,irow,sm);

  //-------------------------------------
  // Remove in case of close to border, by default always 1 but check what was set in reco utils
  //-------------------------------------

  Bool_t okrow = kFALSE;
	Bool_t okcol = kFALSE;
  Int_t nborder = GetCaloUtils()->GetEMCALRecoUtils()->GetNumberOfCellsFromEMCALBorder();
  if ( nborder < 1 ) nborder = 1;

  // Rows
  if ( sm < 10 )
  {
    if(irow >= nborder && irow < 24-nborder) okrow =kTRUE;
  }
  else
  {
    if((GetCaloUtils()->EMCALGeometryName()).Contains("12SM")) // 1/3 SM
    {
      if(irow >= nborder && irow < 8-nborder) okrow =kTRUE;
    }
    else // 1/2 SM
    {
      if(irow >= nborder && irow <12-nborder) okrow =kTRUE;
    }
  }

  // Columns
  if ( sm%2==0 )
  {
    if ( icol >= nborder )     okcol = kTRUE;
  }
  else
  {
    if ( icol <  48-nborder )  okcol = kTRUE;
  }

  //printf("okcol %d, okrow %d\n",okcol,okrow);
  if (!okcol || !okrow) return kTRUE;

  //-------------------------------------
  // Check if the cell or those around are bad
  //-------------------------------------

  Int_t status = 0;
  if ( GetCaloUtils()->GetEMCALChannelStatus(sm,icol, irow,status) )
    return kTRUE ; // trigger falls into a bad channel

  // Check if close there was a bad channel
//  for(Int_t i = -1; i <= 1; i++)
//  {
//    for(Int_t j = -1; j <= 1; j++)
//    {
//      //printf("\t check icol %d, irow %d \n",icol+i, irow+j);
//      if(GetCaloUtils()->GetEMCALChannelStatus(sm,icol+i, irow+j) > 0) return kTRUE ; // trigger falls into a bad channel
//      //printf("\t ok\n");
//    }
//  }

   //printf("\t OK\n");

  return kFALSE;
}

//__________________________________________________
/// Save parameters used for analysis.
//__________________________________________________
TObjString *  AliAnaRandomTrigger::GetAnalysisCuts()
{
  TString parList ; //this will be list of parameters used for this analysis.
  const Int_t buffersize = 255;
  char onePar[buffersize] ;

  snprintf(onePar,buffersize,"--- AliAnaRandomTrigger ---:") ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Detector: %s;"    , fTriggerDetectorString.Data()) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"N per event = %d;", fNRandom       ) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Min E   = %3.2f - Max E   = %3.2f;", GetMinPt(), GetMaxPt()) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Min Eta = %3.2f - Max Eta = %3.2f;", fEtaCut[0], fEtaCut[1]) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Min Phi = %3.2f - Max Phi = %3.2f;", fPhiCut[0], fPhiCut[1]) ;
  parList+=onePar ;

  return new TObjString(parList) ;
}

//____________________________________________________
/// Create histograms to be saved in output file and
/// store them in fOutputContainer
//____________________________________________________
TList *  AliAnaRandomTrigger::GetCreateOutputObjects()
{
  TList * outputContainer = new TList() ;
  outputContainer->SetName("RandomTrigger") ;

  Int_t nptbins  = GetHistogramRanges()->GetHistoPtBins(); Int_t nphibins = GetHistogramRanges()->GetHistoPhiBins(); Int_t netabins = GetHistogramRanges()->GetHistoEtaBins();
  Float_t ptmax  = GetHistogramRanges()->GetHistoPtMax();  Float_t phimax = GetHistogramRanges()->GetHistoPhiMax();  Float_t etamax = GetHistogramRanges()->GetHistoEtaMax();
  Float_t ptmin  = GetHistogramRanges()->GetHistoPtMin();  Float_t phimin = GetHistogramRanges()->GetHistoPhiMin();  Float_t etamin = GetHistogramRanges()->GetHistoEtaMin();

  fhE  = new TH1F ("hE","Random E distribution", nptbins,ptmin,ptmax);
  fhE->SetXTitle("E (GeV)");
  outputContainer->Add(fhE);

  fhPt  = new TH1F ("hPt","Random p_{T} distribution", nptbins,ptmin,ptmax);
  fhPt->SetXTitle("p_{T} (GeV/c)");
  outputContainer->Add(fhPt);

  fhPhi  = new TH2F ("hPhi","Random #phi distribution",
                        nptbins,ptmin,ptmax, nphibins,phimin,phimax);
  fhPhi->SetYTitle("#phi (rad)");
  fhPhi->SetXTitle("p_{T} (GeV/c)");
  outputContainer->Add(fhPhi);

  fhEta  = new TH2F ("hEta","Random #eta distribution",
                        nptbins,ptmin,ptmax, netabins,etamin,etamax);
  fhEta->SetYTitle("#eta ");
  fhEta->SetXTitle("p_{T} (GeV/c)");
  outputContainer->Add(fhEta);

  fhEtaPhi  = new TH2F ("hEtaPhi","Random #eta vs #phi ",netabins,etamin,etamax, nphibins,phimin,phimax);
  fhEtaPhi->SetXTitle("#eta ");
  fhEtaPhi->SetYTitle("#phi (rad)");
  outputContainer->Add(fhEtaPhi);

  return outputContainer;
}

//________________________________________
/// Initialize the parameters of the analysis.
//________________________________________
void AliAnaRandomTrigger::InitParameters()
{
  SetOutputAODClassName("AliCaloTrackParticleCorrelation");
  SetOutputAODName("RandomTrigger");

  AddToHistogramsName("AnaRandomTrigger_");

  fNRandom   = 1    ;
  fPhiCut[0] = 0.   ;
  fPhiCut[1] = TMath::TwoPi() ;
  fEtaCut[0] =-1.   ;
  fEtaCut[1] = 1.   ;
}

//_________________________________________________________
/// Print some relevant parameters set for the analysis.
//_________________________________________________________
void AliAnaRandomTrigger::Print(const Option_t * opt) const
{
  if(! opt)
    return;

  printf("**** Print %s %s ****\n", GetName(), GetTitle() ) ;
  AliAnaCaloTrackCorrBaseClass::Print(" ");

  printf("Detector = %s\n",  fTriggerDetectorString.Data());
  printf("Min E   = %3.2f - Max E   = %3.2f\n", GetMinPt(), GetMaxPt());
  printf("Min Eta = %3.2f - Max Eta = %3.2f\n", fEtaCut[0], fEtaCut[1]);
  printf("Min Phi = %3.2f - Max Phi = %3.2f\n", fPhiCut[0], fPhiCut[1]);
}

//______________________________________________
/// Do analysis and fill aods.
/// Generate particle randomly.
/// fNRandom particles per event.
//______________________________________________
void  AliAnaRandomTrigger::MakeAnalysisFillAOD()
{
  for(Int_t irandom = 0; irandom < fNRandom; irandom++)
  {
    // Get the random variables of the trigger
    Float_t pt  = fRandom.Uniform(GetMinPt(), GetMaxPt());
    Float_t eta = fRandom.Uniform(fEtaCut[0], fEtaCut[1]);
    Float_t phi = fRandom.Uniform(fPhiCut[0], fPhiCut[1]);

    // Check if particle falls into a dead region, if inside, get new
    Bool_t excluded =  ExcludeDeadBadRegions(eta,phi);

    // If excluded, generate a new trigger until accepted
    while (excluded)
    {
      pt  = fRandom.Uniform(GetMinPt(), GetMaxPt());
      eta = fRandom.Uniform(fEtaCut[0], fEtaCut[1]);
      phi = fRandom.Uniform(fPhiCut[0], fPhiCut[1]);

      excluded = ExcludeDeadBadRegions(eta,phi);
    }

    // Create the AOD trigger object
    fMomentum.SetPtEtaPhiM(pt,eta,phi,0);

    AliCaloTrackParticle trigger = AliCaloTrackParticle(fMomentum);
    trigger.SetDetectorTag(fTriggerDetector);
    trigger.SetSModNumber(GetModuleNumber(&trigger));

    AliDebug(1,Form("iRandom %d, Trigger e %2.2f pt %2.2f, phi %2.2f, eta %2.2f, SM %d",
                    irandom, trigger.E(), trigger.Pt(), trigger.Phi(), trigger.Eta(), trigger.GetSModNumber()));

    AddAODParticle(trigger);
  }

  AliDebug(1,Form("Final aod branch entries %d", GetOutputAODBranch()->GetEntriesFast()));
}

//_____________________________________________________
// Fill control histograms with generated trigger kinematics.
//_____________________________________________________
void  AliAnaRandomTrigger::MakeAnalysisFillHistograms()
{
  // Loop on stored AODParticles
  Int_t naod = GetOutputAODBranch()->GetEntriesFast();

  AliDebug(1,Form("AOD branch entries %d, fNRandom %d", naod, fNRandom));

  for(Int_t iaod = 0; iaod < naod ; iaod++)
  {
    AliCaloTrackParticle* trigger =  (AliCaloTrackParticle*) (GetOutputAODBranch()->At(iaod));

    fhPt    ->Fill(trigger->Pt (),                 GetEventWeight());
    fhE     ->Fill(trigger->E  (),                 GetEventWeight());
    fhPhi   ->Fill(trigger->Pt (), trigger->Phi(), GetEventWeight());
    fhEta   ->Fill(trigger->Pt (), trigger->Eta(), GetEventWeight());
    fhEtaPhi->Fill(trigger->Eta(), trigger->Phi(), GetEventWeight());
  }// aod branch loop
}

//_________________________________________________________
/// Set the detrimeter for the analysis.
//_________________________________________________________
void AliAnaRandomTrigger::SetTriggerDetector(TString det)
{
  fTriggerDetectorString = det;

  if     (det=="EMCAL") fTriggerDetector = kEMCAL;
  else if(det=="PHOS" ) fTriggerDetector = kPHOS;
  else if(det=="CTS")   fTriggerDetector = kCTS;
  else if(det=="DCAL")  fTriggerDetector = kDCAL;
  else if(det.Contains("DCAL") && det.Contains("PHOS")) fTriggerDetector = kDCALPHOS;
  else AliFatal(Form("Detector < %s > not known!", det.Data()));
}

//______________________________________________________
// Set the calorimeter for the analysis.
//______________________________________________________
void AliAnaRandomTrigger::SetTriggerDetector(Int_t det)
{
  fTriggerDetector = det;

  if     ( det == kEMCAL   ) fTriggerDetectorString = "EMCAL";
  else if( det == kPHOS    ) fTriggerDetectorString = "PHOS";
  else if( det == kCTS     ) fTriggerDetectorString = "CTS";
  else if( det == kDCAL    ) fTriggerDetectorString = "DCAL";
  else if( det == kDCALPHOS) fTriggerDetectorString = "DCAL_PHOS";
  else AliFatal(Form("Detector < %d > not known!", det));
}

<commit_msg>fix warning<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// --- ROOT system ---
#include <TObjString.h>
#include <TH2F.h>
#include <TClonesArray.h>

//---- AliRoot system ----
#include "AliAnaRandomTrigger.h"
#include "AliCaloTrackParticleCorrelation.h"
#include "AliEMCALGeometry.h"

/// \cond CLASSIMP
ClassImp(AliAnaRandomTrigger) ;
/// \endcond

//__________________________________________
/// Default Constructor. Initialize parameters.
//__________________________________________
AliAnaRandomTrigger::AliAnaRandomTrigger() :
    AliAnaCaloTrackCorrBaseClass(),
    fTriggerDetector(kEMCAL),
    fTriggerDetectorString("EMCAL"),
    fRandom(0),         fNRandom(0),
    fMomentum(),
    fhE(0),             fhPt(0),
    fhPhi(0),           fhEta(0),
    fhEtaPhi(0)
{
  InitParameters();
}

//_________________________________________________________________________
/// Check if there is a dead or bad region in a detector.
/// Only EMCAL for now.
//_________________________________________________________________________
Bool_t AliAnaRandomTrigger::ExcludeDeadBadRegions(Float_t eta, Float_t phi)
{
  if ( fTriggerDetector != kEMCAL && fTriggerDetector != kDCAL ) return kFALSE;

  //-------------------------------------
  // Get the corresponding cell in EMCAL, check if it exists in acceptance (phi gaps, borders)
  //-------------------------------------

  Int_t absId = -1;
  if(!GetEMCALGeometry()->GetAbsCellIdFromEtaPhi(eta,phi, absId)) return kTRUE; // remove if out of EMCAL acceptance, phi gaps

  Int_t icol = -1, irow = -1, iRCU = -1;
  Int_t sm = GetCaloUtils()->GetModuleNumberCellIndexes(absId,kEMCAL, icol, irow, iRCU);

  //printf("eta %f, phi %f, ieta %d, iphi %d, sm %d\n",eta,phi,icol,irow,sm);

  //-------------------------------------
  // Remove in case of close to border, by default always 1 but check what was set in reco utils
  //-------------------------------------

  Bool_t okrow = kFALSE;
	Bool_t okcol = kFALSE;
  Int_t nborder = GetCaloUtils()->GetEMCALRecoUtils()->GetNumberOfCellsFromEMCALBorder();
  if ( nborder < 1 ) nborder = 1;

  // Rows
  if ( sm < 10 )
  {
    if(irow >= nborder && irow < 24-nborder) okrow =kTRUE;
  }
  else
  {
    if((GetCaloUtils()->EMCALGeometryName()).Contains("12SM")) // 1/3 SM
    {
      if(irow >= nborder && irow < 8-nborder) okrow =kTRUE;
    }
    else // 1/2 SM
    {
      if(irow >= nborder && irow <12-nborder) okrow =kTRUE;
    }
  }

  // Columns
  if ( sm%2==0 )
  {
    if ( icol >= nborder )     okcol = kTRUE;
  }
  else
  {
    if ( icol <  48-nborder )  okcol = kTRUE;
  }

  //printf("okcol %d, okrow %d\n",okcol,okrow);
  if (!okcol || !okrow) return kTRUE;

  //-------------------------------------
  // Check if the cell or those around are bad
  //-------------------------------------

  Int_t status = 0;
  if ( GetCaloUtils()->GetEMCALChannelStatus(sm,icol, irow,status) )
    return kTRUE ; // trigger falls into a bad channel

  // Check if close there was a bad channel
//  for(Int_t i = -1; i <= 1; i++)
//  {
//    for(Int_t j = -1; j <= 1; j++)
//    {
//      //printf("\t check icol %d, irow %d \n",icol+i, irow+j);
//      if(GetCaloUtils()->GetEMCALChannelStatus(sm,icol+i, irow+j) > 0) return kTRUE ; // trigger falls into a bad channel
//      //printf("\t ok\n");
//    }
//  }

   //printf("\t OK\n");

  return kFALSE;
}

//__________________________________________________
/// Save parameters used for analysis.
//__________________________________________________
TObjString *  AliAnaRandomTrigger::GetAnalysisCuts()
{
  TString parList ; //this will be list of parameters used for this analysis.
  const Int_t buffersize = 255;
  char onePar[buffersize] ;

  snprintf(onePar,buffersize,"--- AliAnaRandomTrigger ---:") ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Detector: %s;"    , fTriggerDetectorString.Data()) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"N per event = %d;", fNRandom       ) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Min E   = %3.2f - Max E   = %3.2f;", GetMinPt(), GetMaxPt()) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Min Eta = %3.2f - Max Eta = %3.2f;", fEtaCut[0], fEtaCut[1]) ;
  parList+=onePar ;
  snprintf(onePar,buffersize,"Min Phi = %3.2f - Max Phi = %3.2f;", fPhiCut[0], fPhiCut[1]) ;
  parList+=onePar ;

  return new TObjString(parList) ;
}

//____________________________________________________
/// Create histograms to be saved in output file and
/// store them in fOutputContainer
//____________________________________________________
TList *  AliAnaRandomTrigger::GetCreateOutputObjects()
{
  TList * outputContainer = new TList() ;
  outputContainer->SetName("RandomTrigger") ;

  Int_t nptbins  = GetHistogramRanges()->GetHistoPtBins(); Int_t nphibins = GetHistogramRanges()->GetHistoPhiBins(); Int_t netabins = GetHistogramRanges()->GetHistoEtaBins();
  Float_t ptmax  = GetHistogramRanges()->GetHistoPtMax();  Float_t phimax = GetHistogramRanges()->GetHistoPhiMax();  Float_t etamax = GetHistogramRanges()->GetHistoEtaMax();
  Float_t ptmin  = GetHistogramRanges()->GetHistoPtMin();  Float_t phimin = GetHistogramRanges()->GetHistoPhiMin();  Float_t etamin = GetHistogramRanges()->GetHistoEtaMin();

  fhE  = new TH1F ("hE","Random E distribution", nptbins,ptmin,ptmax);
  fhE->SetXTitle("E (GeV)");
  outputContainer->Add(fhE);

  fhPt  = new TH1F ("hPt","Random p_{T} distribution", nptbins,ptmin,ptmax);
  fhPt->SetXTitle("p_{T} (GeV/c)");
  outputContainer->Add(fhPt);

  fhPhi  = new TH2F ("hPhi","Random #phi distribution",
                        nptbins,ptmin,ptmax, nphibins,phimin,phimax);
  fhPhi->SetYTitle("#phi (rad)");
  fhPhi->SetXTitle("p_{T} (GeV/c)");
  outputContainer->Add(fhPhi);

  fhEta  = new TH2F ("hEta","Random #eta distribution",
                        nptbins,ptmin,ptmax, netabins,etamin,etamax);
  fhEta->SetYTitle("#eta ");
  fhEta->SetXTitle("p_{T} (GeV/c)");
  outputContainer->Add(fhEta);

  fhEtaPhi  = new TH2F ("hEtaPhi","Random #eta vs #phi ",netabins,etamin,etamax, nphibins,phimin,phimax);
  fhEtaPhi->SetXTitle("#eta ");
  fhEtaPhi->SetYTitle("#phi (rad)");
  outputContainer->Add(fhEtaPhi);

  return outputContainer;
}

//________________________________________
/// Initialize the parameters of the analysis.
//________________________________________
void AliAnaRandomTrigger::InitParameters()
{
  SetOutputAODClassName("AliCaloTrackParticleCorrelation");
  SetOutputAODName("RandomTrigger");

  AddToHistogramsName("AnaRandomTrigger_");

  fNRandom   = 1    ;
  fPhiCut[0] = 0.   ;
  fPhiCut[1] = TMath::TwoPi() ;
  fEtaCut[0] =-1.   ;
  fEtaCut[1] = 1.   ;
}

//_________________________________________________________
/// Print some relevant parameters set for the analysis.
//_________________________________________________________
void AliAnaRandomTrigger::Print(const Option_t * opt) const
{
  if(! opt)
    return;

  printf("**** Print %s %s ****\n", GetName(), GetTitle() ) ;
  AliAnaCaloTrackCorrBaseClass::Print(" ");

  printf("Detector = %s\n",  fTriggerDetectorString.Data());
  printf("Min E   = %3.2f - Max E   = %3.2f\n", GetMinPt(), GetMaxPt());
  printf("Min Eta = %3.2f - Max Eta = %3.2f\n", fEtaCut[0], fEtaCut[1]);
  printf("Min Phi = %3.2f - Max Phi = %3.2f\n", fPhiCut[0], fPhiCut[1]);
}

//______________________________________________
/// Do analysis and fill aods.
/// Generate particle randomly.
/// fNRandom particles per event.
//______________________________________________
void  AliAnaRandomTrigger::MakeAnalysisFillAOD()
{
  for(Int_t irandom = 0; irandom < fNRandom; irandom++)
  {
    // Get the random variables of the trigger
    Float_t pt  = fRandom.Uniform(GetMinPt(), GetMaxPt());
    Float_t eta = fRandom.Uniform(fEtaCut[0], fEtaCut[1]);
    Float_t phi = fRandom.Uniform(fPhiCut[0], fPhiCut[1]);

    // Check if particle falls into a dead region, if inside, get new
    Bool_t excluded =  ExcludeDeadBadRegions(eta,phi);

    // If excluded, generate a new trigger until accepted
    while (excluded)
    {
      pt  = fRandom.Uniform(GetMinPt(), GetMaxPt());
      eta = fRandom.Uniform(fEtaCut[0], fEtaCut[1]);
      phi = fRandom.Uniform(fPhiCut[0], fPhiCut[1]);

      excluded = ExcludeDeadBadRegions(eta,phi);
    }

    // Create the AOD trigger object
    fMomentum.SetPtEtaPhiM(pt,eta,phi,0);

    AliCaloTrackParticle trigger = AliCaloTrackParticle(fMomentum);
    trigger.SetDetectorTag(fTriggerDetector);
    trigger.SetSModNumber(GetModuleNumber(&trigger));

    AliDebug(1,Form("iRandom %d, Trigger e %2.2f pt %2.2f, phi %2.2f, eta %2.2f, SM %d",
                    irandom, trigger.E(), trigger.Pt(), trigger.Phi(), trigger.Eta(), trigger.GetSModNumber()));

    AddAODParticle(trigger);
  }

  AliDebug(1,Form("Final aod branch entries %d", GetOutputAODBranch()->GetEntriesFast()));
}

//_____________________________________________________
// Fill control histograms with generated trigger kinematics.
//_____________________________________________________
void  AliAnaRandomTrigger::MakeAnalysisFillHistograms()
{
  // Loop on stored AODParticles
  Int_t naod = GetOutputAODBranch()->GetEntriesFast();

  AliDebug(1,Form("AOD branch entries %d, fNRandom %d", naod, fNRandom));

  for(Int_t iaod = 0; iaod < naod ; iaod++)
  {
    AliCaloTrackParticle* trigger =  (AliCaloTrackParticle*) (GetOutputAODBranch()->At(iaod));

    fhPt    ->Fill(trigger->Pt (),                 GetEventWeight());
    fhE     ->Fill(trigger->E  (),                 GetEventWeight());
    fhPhi   ->Fill(trigger->Pt (), trigger->Phi(), GetEventWeight());
    fhEta   ->Fill(trigger->Pt (), trigger->Eta(), GetEventWeight());
    fhEtaPhi->Fill(trigger->Eta(), trigger->Phi(), GetEventWeight());
  }// aod branch loop
}

//_________________________________________________________
/// Set the detrimeter for the analysis.
//_________________________________________________________
void AliAnaRandomTrigger::SetTriggerDetector(TString det)
{
  fTriggerDetectorString = det;

  if     (det=="EMCAL") fTriggerDetector = kEMCAL;
  else if(det=="PHOS" ) fTriggerDetector = kPHOS;
  else if(det=="CTS")   fTriggerDetector = kCTS;
  else if(det=="DCAL")  fTriggerDetector = kDCAL;
  else if(det.Contains("DCAL") && det.Contains("PHOS")) fTriggerDetector = kDCALPHOS;
  else AliFatal(Form("Detector < %s > not known!", det.Data()));
}

//______________________________________________________
// Set the calorimeter for the analysis.
//______________________________________________________
void AliAnaRandomTrigger::SetTriggerDetector(Int_t det)
{
  fTriggerDetector = det;

  if     ( det == kEMCAL   ) fTriggerDetectorString = "EMCAL";
  else if( det == kPHOS    ) fTriggerDetectorString = "PHOS";
  else if( det == kCTS     ) fTriggerDetectorString = "CTS";
  else if( det == kDCAL    ) fTriggerDetectorString = "DCAL";
  else if( det == kDCALPHOS) fTriggerDetectorString = "DCAL_PHOS";
  else AliFatal(Form("Detector < %d > not known!", det));
}

<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "sprint.hh"

TEST(_fmt, int) {
	int a = 2;
	ASSERT_STREQ("%d", _fmt(a));
}

TEST(_fmt, uint64_t) {
	uint64_t a = 4294967295;
	ASSERT_STREQ("%lu", _fmt(a));
}

TEST(_fmt, int64_t) {
	int64_t a = 4294967295;
	ASSERT_STREQ("%ld", _fmt(a));
}

TEST(_fmt, double) {
	double a = 3.14159;
	ASSERT_STREQ("%lf", _fmt(a));
}

TEST(_sfmt, 3ints) {
	char buffer[100];
	memset(buffer, 0, 100);
	int t = _sfmt(buffer, 0, false, 2, 2.1, 'a');
	ASSERT_STREQ("%d %lf %c", buffer);
	ASSERT_EQ(9, t);
}

TEST(_sfmt, newline) {
	char buffer[100];
	memset(buffer, 0, 100);
	int t = _sfmt(buffer, 0, true, 2, 2.1, 'a');
	ASSERT_STREQ("%d %lf %c\n", buffer);
	ASSERT_EQ(10, t);
}
<commit_msg>sprint_test: fix tests for macOS and more tests<commit_after>#include <gtest/gtest.h>

#include "sprint.hh"

TEST(_fmt, int) {
	int a = 2;
	ASSERT_STREQ("%d", _fmt(a));
}

TEST(_fmt, uint64_t) {
	uint64_t a = 4294967295;
	if (typeid(a) == typeid(unsigned long long int)) {
		ASSERT_STREQ("%llu", _fmt(a));
	} else {
		ASSERT_STREQ("%lu", _fmt(a));
	}
}

TEST(_fmt, int64_t) {
	int64_t a = 4294967295;
	if (typeid(a) == typeid(long long int)) {
		ASSERT_STREQ("%lld", _fmt(a));
	} else {
		ASSERT_STREQ("%ld", _fmt(a));
	}
}

TEST(_fmt, uint32_t) {
	uint32_t a = 4294967295;
	if (typeid(a) == typeid(unsigned long int)) {
		ASSERT_STREQ("%lu", _fmt(a));
	} else {
		ASSERT_STREQ("%u", _fmt(a));
	}
}

TEST(_fmt, int32_t) {
	int32_t a = 4294967295;
	if (typeid(a) == typeid(long int)) {
		ASSERT_STREQ("%ld", _fmt(a));
	} else {
		ASSERT_STREQ("%d", _fmt(a));
	}
}

TEST(_fmt, double) {
	double a = 3.14159;
	ASSERT_STREQ("%lf", _fmt(a));
}

TEST(_fmt, float) {
	float a = 3.14159;
	ASSERT_STREQ("%f", _fmt(a));
}

TEST(_fmt, char) {
	char a = '1';
	ASSERT_STREQ("%c", _fmt(a));
}

TEST(_sfmt, single_arg) {
	char buffer[100];
	memset(buffer, 0, 100);
	int t = _sfmt(buffer, 0, false, 2);
	ASSERT_STREQ("%d", buffer);
	ASSERT_EQ(2, t);
}

TEST(_sfmt, three_args) {
	char buffer[100];
	memset(buffer, 0, 100);
	int t = _sfmt(buffer, 0, false, 2, 2.1, 'a');
	ASSERT_STREQ("%d %lf %c", buffer);
	ASSERT_EQ(9, t);
}

TEST(_sfmt, newline) {
	char buffer[100];
	memset(buffer, 0, 100);
	int t = _sfmt(buffer, 0, true, 2, 2.1, 'a');
	ASSERT_STREQ("%d %lf %c\n", buffer);
	ASSERT_EQ(10, t);
}
<|endoftext|>