<commit_before>/**
 *  Capture.cpp
 */

#include <iomanip>

#include <bites.hpp>

#include "Capture.hpp"

namespace wabbit {

Capture::Capture( bites::Config& config,
                  const int& duration,
                  std::ostream* output_stream )
    : m_config( config ),
      m_duration( duration ),
      m_output_stream( output_stream ),
      m_video_capture( stod( m_config["device"] )),
      m_rate_ticker({1, 5, 10})
{
    m_video_capture.set( 3, stod( m_config["width"] ));
    m_video_capture.set( 4, stod( m_config["height"] ));

    // Compute interval needed to observe maximum FPS limit.
    float max_fps = stof( m_config["max_fps"] );
    max_fps = max_fps >= 0 ? max_fps : std::numeric_limits<float>::max();
    float interval_seconds = 1 / max_fps;
    int interval_ms = interval_seconds * 1000000;
    m_min_interval = std::chrono::microseconds( interval_ms );

    // Set the minimum read time for detecting camera disconnect.
    m_min_read = stof( m_config["min_read"] );

    m_prev_time = std::chrono::system_clock::now();
    m_end_time = m_prev_time + std::chrono::seconds( m_duration );
}

Capture::Capture( const Capture& capture )
    : m_config( capture.m_config ),
      m_duration( capture.m_duration ),
      m_output_stream( capture.m_output_stream ),
      m_video_capture( capture.m_video_capture ),
      m_rate_ticker( capture.m_rate_ticker ),
      m_prev_time( capture.m_prev_time ),
      m_end_time( capture.m_end_time ),
      m_min_interval( capture.m_min_interval ),
      m_min_read( capture.m_min_read )
{}

std::vector <float> Capture::getFramerate ()
{
    return m_framerate.get();
}

bool Capture::operator()( wabbit::ImageAndTime& image_and_time )
{
    if( !m_video_capture.isOpened() ){
        return false;
    }
    if( m_end_time <= std::chrono::system_clock::now() and m_duration >= 0 ){
        return false;
    }

    // Insert delay to observe maximum framerate limit.
    auto elapsed = std::chrono::system_clock::now() - m_prev_time;
    auto elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed );
    auto sleep_ms = m_min_interval - elapsed_ms;
    sleep_ms = sleep_ms.count() < 0 ? std::chrono::microseconds(0) : sleep_ms;
    usleep( sleep_ms.count());

    // Take a snapshot.
    // The only way I could detect camera disconnect was by
    // thresholding the length of time to call read() method.
    // For some reason return value of read() is always True,
    // even after disconnecting the camera.
    m_prev_time = std::chrono::system_clock::now();
    m_video_capture >> image_and_time.image;  // Read the image.
    elapsed = std::chrono::system_clock::now() - m_prev_time;
    image_and_time.time = m_prev_time;
    elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed );
    if( elapsed_ms.count()/1000000. < m_min_read )
    {
        // TODO: Write error to log instead of stdout.
        std::cout << "Error: Read time failed to meet threshold: " << std::endl;
        std::cout << std::fixed << std::setw( 10 ) << std::setprecision( 6 )
                  << elapsed_ms.count() / 1000000. << " (readtime) < "
                  << m_min_read << " (threshold)" << std::endl;
        std::cout << "Probably disconnected camera." << std::endl;
        return false;
    }

    // Set the framerate.
    auto fps = m_rate_ticker.tick();
    m_framerate.set( fps );

    // Optionally print the current framerate.
    if( m_output_stream ){
        *m_output_stream << std::fixed << std::setw( 10 ) << std::setprecision( 6 )
                         << elapsed_ms.count()/1000000.;
        for(auto ii=begin( fps ); ii!=end( fps ); ++ii){
            *m_output_stream << std::fixed << std::setw( 7 ) << std::setprecision( 2 )
                             << *ii;
        }
        *m_output_stream << std::endl;
    }

    return true;
}

}  // namespace wabbit.
<commit_msg>Enable use of /dev/v4l path as video device.<commit_after>/**
 *  Capture.cpp
 */

#include <iomanip>
#include <regex>
#include <stdexcept>  // std::invalid_argument

#include <bites.hpp>
#include <boost/filesystem.hpp>

#include "Capture.hpp"

namespace wabbit {

Capture::Capture( bites::Config& config,
                  const int& duration,
                  std::ostream* output_stream )
    : m_config( config ),
      m_duration( duration ),
      m_output_stream( output_stream ),
      m_video_capture(),
      m_rate_ticker({1, 5, 10})
{
    // Attempt to open device given as integer.
    // If that fails, attempt to resolve the device as a path.
    int device = -1;
    try{
        device = stod( m_config["device"] );
    }
    catch( std::invalid_argument){
        boost::filesystem::path path( m_config["device"] );
        auto target = boost::filesystem::canonical(path).string();
        std::regex exp( ".*video(\\d+)" );
        std::smatch match;
        std::regex_search( target, match, exp );
        device = stod( match[1] );
    }
    if( m_output_stream ){
        *m_output_stream << "device: " << device << std::endl;
    }

    // Setup the OpenCV VideoCapture object.
    m_video_capture.open( device );
    m_video_capture.set( 3, stod( m_config["width"] ));
    m_video_capture.set( 4, stod( m_config["height"] ));

    // Compute interval needed to observe maximum FPS limit.
    float max_fps = stof( m_config["max_fps"] );
    max_fps = max_fps >= 0 ? max_fps : std::numeric_limits<float>::max();
    float interval_seconds = 1 / max_fps;
    int interval_ms = interval_seconds * 1000000;
    m_min_interval = std::chrono::microseconds( interval_ms );

    // Set the minimum read time for detecting camera disconnect.
    m_min_read = stof( m_config["min_read"] );

    m_prev_time = std::chrono::system_clock::now();
    m_end_time = m_prev_time + std::chrono::seconds( m_duration );
}

Capture::Capture( const Capture& capture )
    : m_config( capture.m_config ),
      m_duration( capture.m_duration ),
      m_output_stream( capture.m_output_stream ),
      m_video_capture( capture.m_video_capture ),
      m_rate_ticker( capture.m_rate_ticker ),
      m_prev_time( capture.m_prev_time ),
      m_end_time( capture.m_end_time ),
      m_min_interval( capture.m_min_interval ),
      m_min_read( capture.m_min_read )
{}

std::vector <float> Capture::getFramerate ()
{
    return m_framerate.get();
}

bool Capture::operator()( wabbit::ImageAndTime& image_and_time )
{
    if( !m_video_capture.isOpened() ){
        return false;
    }
    if( m_end_time <= std::chrono::system_clock::now() and m_duration >= 0 ){
        return false;
    }

    // Insert delay to observe maximum framerate limit.
    auto elapsed = std::chrono::system_clock::now() - m_prev_time;
    auto elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed );
    auto sleep_ms = m_min_interval - elapsed_ms;
    sleep_ms = sleep_ms.count() < 0 ? std::chrono::microseconds(0) : sleep_ms;
    usleep( sleep_ms.count());

    // Take a snapshot.
    // The only way I could detect camera disconnect was by
    // thresholding the length of time to call read() method.
    // For some reason return value of read() is always True,
    // even after disconnecting the camera.
    m_prev_time = std::chrono::system_clock::now();
    m_video_capture >> image_and_time.image;  // Read the image.
    elapsed = std::chrono::system_clock::now() - m_prev_time;
    image_and_time.time = m_prev_time;
    elapsed_ms = std::chrono::duration_cast<std::chrono::microseconds>( elapsed );
    if( elapsed_ms.count()/1000000. < m_min_read )
    {
        // TODO: Write error to log instead of stdout.
        std::cout << "Error: Read time failed to meet threshold: " << std::endl;
        std::cout << std::fixed << std::setw( 10 ) << std::setprecision( 6 )
                  << elapsed_ms.count() / 1000000. << " (readtime) < "
                  << m_min_read << " (threshold)" << std::endl;
        std::cout << "Probably disconnected camera." << std::endl;
        return false;
    }

    // Set the framerate.
    auto fps = m_rate_ticker.tick();
    m_framerate.set( fps );

    // Optionally print the current framerate.
    if( m_output_stream ){
        *m_output_stream << std::fixed << std::setw( 10 ) << std::setprecision( 6 )
                         << elapsed_ms.count()/1000000.;
        for(auto ii=begin( fps ); ii!=end( fps ); ++ii){
            *m_output_stream << std::fixed << std::setw( 7 ) << std::setprecision( 2 )
                             << *ii;
        }
        *m_output_stream << std::endl;
    }

    return true;
}

}  // namespace wabbit.
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
//1 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#define OS_TERMINATE_ON_CONTRACT_VIOLATION
#include <os>

#include <fs/disk.hpp>
std::shared_ptr<fs::Disk> disk;

void list_partitions(decltype(disk));

#define MYINFO(X,...) INFO("VirtioBlk",X,##__VA_ARGS__)

void Service::start()
{
  // instantiate memdisk with FAT filesystem
  auto& device = hw::Dev::disk<1, VirtioBlk>();
  disk = std::make_shared<fs::Disk> (device);
  // assert that we have a disk
  CHECKSERT(disk, "Disk created");
  // if the disk is empty, we can't mount a filesystem
  CHECKSERT(not disk->empty(), "Disk is not empty");

  // list extended partitions
  list_partitions(disk);

  // mount first valid partition (auto-detect and mount)
  disk->mount(
  [] (fs::error_t err) {
    if (err) {
      printf("Could not mount filesystem\n");
      panic("mount() failed");
    }

    // async ls
    disk->fs().ls("/",
    [] (fs::error_t err, auto ents) {
      if (err) {
        printf("Could not list '/' directory\n");
        panic("ls() failed");
      }

      // go through directory entries
      for (auto& e : *ents) {
        printf("%s: %s\t of size %llu bytes (CL: %llu)\n",
               e.type_string().c_str(), e.name().c_str(), e.size, e.block);

        if (e.is_file()) {
          printf("*** Read %s\n", e.name().c_str());
          disk->fs().read(e, 0, e.size,
          [e] (fs::error_t err, fs::buffer_t buffer, size_t len) {
            if (err) {
              printf("Failed to read %s!\n", e.name().c_str());
              panic("read() failed");
            }

            std::string contents((const char*) buffer.get(), len);
            printf("[%s contents]:\n%s\nEOF\n\n",
                   e.name().c_str(), contents.c_str());
            // ---
            INFO("Virtioblk Test", "SUCCESS");
          });

        } // is_file

      } // ents

    }); // ls

  }); // disk->auto_detect()

  printf("*** TEST SERVICE STARTED *** \n");

}

void list_partitions(decltype(disk) disk)
{
  disk->partitions([] (fs::error_t err, auto& parts) {

      CHECKSERT (not err, "Was able to fetch partition table");

      for (auto& part : parts)
        printf("[Partition]  '%s' at LBA %u\n",
               part.name().c_str(), part.lba());

    });
}
<commit_msg>Fixed virtio_block test<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
//1 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#define OS_TERMINATE_ON_CONTRACT_VIOLATION
#include <os>

#include <fs/disk.hpp>
std::shared_ptr<fs::Disk> disk;

void list_partitions(decltype(disk));

#define MYINFO(X,...) INFO("VirtioBlk",X,##__VA_ARGS__)

void Service::start()
{
  // instantiate memdisk with FAT filesystem
  auto& device = hw::Dev::disk<1, VirtioBlk>();
  disk = std::make_shared<fs::Disk> (device);
  // assert that we have a disk
  CHECKSERT(disk, "Disk created");
  // if the disk is empty, we can't mount a filesystem
  CHECKSERT(not disk->empty(), "Disk is not empty");

  // list extended partitions
  list_partitions(disk);

  // mount first valid partition (auto-detect and mount)
  disk->mount(
  [] (fs::error_t err) {
    if (err) {
      printf("Could not mount filesystem\n");
      panic("mount() failed");
    }

    // async ls
    disk->fs().ls("/",
    [] (fs::error_t err, auto ents) {
      if (err) {
        printf("Could not list '/' directory\n");
        panic("ls() failed");
      }

      // go through directory entries
      for (auto& e : *ents) {
        printf("%s: %s\t of size %llu bytes (CL: %llu)\n",
               e.type_string().c_str(), e.name().c_str(), e.size(), e.block);

        if (e.is_file()) {
          printf("*** Read %s\n", e.name().c_str());
          disk->fs().read(e, 0, e.size(),
          [e] (fs::error_t err, fs::buffer_t buffer, size_t len) {
            if (err) {
              printf("Failed to read %s!\n", e.name().c_str());
              panic("read() failed");
            }

            std::string contents((const char*) buffer.get(), len);
            printf("[%s contents]:\n%s\nEOF\n\n",
                   e.name().c_str(), contents.c_str());
            // ---
            INFO("Virtioblk Test", "SUCCESS");
          });

        } // is_file

      } // ents

    }); // ls

  }); // disk->auto_detect()

  printf("*** TEST SERVICE STARTED *** \n");

}

void list_partitions(decltype(disk) disk)
{
  disk->partitions([] (fs::error_t err, auto& parts) {

      CHECKSERT (not err, "Was able to fetch partition table");

      for (auto& part : parts)
        printf("[Partition]  '%s' at LBA %u\n",
               part.name().c_str(), part.lba());

    });
}
<|endoftext|>


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

#include "ImageCompare.h"

namespace sitk = itk::simple;

void ImageCompare::NormalizeAndSave ( const sitk::Image &input, const std::string &filename )
{
  sitk::Image image = input;

  // Extract the center slice of our image
  if ( input.GetDimension() == 3 )
    {
    std::vector<int> idx( 3, 0 );
    std::vector<unsigned int> sz = input.GetSize();

    // set to just the center slice
    idx[2] = (int)( input.GetDepth() / 2.0 );
    sz[2] = 1;
    image = sitk::Extract( input, sz, idx );
    }

  sitk::StatisticsImageFilter stats;
  stats.Execute ( image );
  sitk::Image out = sitk::IntensityWindowing ( image, stats.GetMinimum(), stats.GetMaximum(), 0, 255 );
  out = sitk::Cast ( out, sitk::sitkUInt8 );
  sitk::WriteImage ( out, filename );
}

ImageCompare::ImageCompare()
{
  mTolerance = 0.0;
  mMessage = "";
}

bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, std::string inTag )
{
  sitk::Image centerSlice( 0, 0, sitk::sitkUInt8 );
  std::string testCase = inTestCase;
  std::string tag = inTag;
  std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name();

  if ( testCase == "" )
    {
    testCase = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name();
    }

  std::cout << "Starting image compare on " << testCase << "_" << testName << "_" << tag << std::endl;
  // Does the baseline exist?
  std::string extension = ".nrrd";
  std::string OutputDir = dataFinder.GetOutputDirectory();

  std::string name = testCase
    .append( "_" )
    .append(testName);

  if ( tag != "" )
    {
    name.append("_").append ( tag );
    }

  // Extract the center slice of our image
  if ( image.GetDimension() == 3 )
    {
    std::vector<int> idx( 3, 0 );
    std::vector<unsigned int> sz = image.GetSize();

    // set to just the center slice
    idx[2] = (int)( image.GetDepth() / 2.0 );
    sz[2] = 1;
    centerSlice = sitk::RegionOfInterest( image, sz, idx );
    }
  else
    {
    centerSlice = image;
    }

  std::string baselineFileName = dataFinder.GetSourceDirectory() + "/Testing/Data/Baseline/" + name + extension;

  if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str() ) )
    {
    // Baseline does not exist, write out what we've been given
    std::string newBaselineDir = OutputDir + "/Newbaseline/";
    itksys::SystemTools::MakeDirectory ( newBaselineDir.c_str() );
    std::cout << "Making directory " << newBaselineDir << std::endl;
    std::string newBaseline = newBaselineDir + name + extension;
    sitk::ImageFileWriter().SetFileName ( newBaseline ).Execute ( centerSlice );
    mMessage = "Baseline does not exist, wrote " + newBaseline + "\ncp " + newBaseline + " " + baselineFileName;
    return false;
    }

  sitk::Image baseline( 0, 0, sitk::sitkUInt8 );
  std::cout << "Loading baseline " << baselineFileName << std::endl;

  try
    {
    baseline = sitk::ImageFileReader().SetFileName ( baselineFileName ).Execute();
    }
  catch ( std::exception& e )
    {
    mMessage = "ImageCompare: Failed to load image " + baselineFileName + " because: " + e.what();
    return false;
    }

  // verify they have the same size
  if ( baseline.GetHeight() != centerSlice.GetHeight()
       || baseline.GetWidth() != centerSlice.GetWidth()
       || baseline.GetDepth() != centerSlice.GetDepth() )
    {
    mMessage = "ImageCompare: Image dimensions are different";
    return false;
    }

  // Get the center slices
  sitk::Image diffSquared( 0, 0, itk::simple::sitkUInt8 );
  try
    {

    if ( baseline.GetPixelIDValue() == sitk::sitkComplexFloat32 ||
         baseline.GetPixelIDValue() == sitk::sitkComplexFloat64 )
      {

      sitk::Image diff =  sitk::Subtract( centerSlice, baseline );
      // for complex number we multiply the image by it's complex
      // conjugate, this will produce only a real value result
      sitk::Image conj = sitk::RealAndImaginaryToComplex( sitk::ComplexToReal( diff ),
                                                          sitk::MultiplyByConstant( sitk::ComplexToImaginary( diff ), -1 ) );
      diffSquared = sitk::ComplexToReal( sitk::Multiply( diff, conj ) );
      }
    else if ( baseline.GetNumberOfComponentsPerPixel() > 1 )
      {
      sitk::Image diff =  sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkVectorFloat32 ), sitk::Cast( baseline, sitk::sitkVectorFloat32 ) );

      // for vector image just do a sum of the components
      diffSquared  = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, 0 ), 2 );
      for ( unsigned int i = 1; i < diff.GetNumberOfComponentsPerPixel(); ++i )
        {
        sitk::Image temp = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, i ), 2 );
        diffSquared = sitk::Add( temp, diffSquared );
        }

      diffSquared = sitk::DivideByConstant( diffSquared, diff.GetNumberOfComponentsPerPixel() );
      }
    else
      {
      sitk::Image diff =  sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkFloat32 ), sitk::Cast( baseline, sitk::sitkFloat32 ) );
      diffSquared = sitk::Multiply( diff, diff );
      }

    }
  catch ( std::exception& e )
    {
    mMessage = "ImageCompare: Failed to subtract image " + baselineFileName + " because: " + e.what();
    return false;
    }

  sitk::StatisticsImageFilter stats;
  stats.Execute ( diffSquared );
  double rms = std::sqrt ( stats.GetMean() );

  if ( rms > fabs ( mTolerance ) )
    {
    std::ostringstream msg;
    msg << "ImageCompare: image Root Mean Square (RMS) difference was " << rms << " which exceeds the tolerance of " << mTolerance;
    msg << "\n";
    mMessage = msg.str();

    std::cout << "<DartMeasurement name=\"RMSeDifference\" type=\"numeric/float\">" << rms << "</DartMeasurement>" << std::endl;
    std::cout << "<DartMeasurement name=\"Tolerance\" type=\"numeric/float\">" << mTolerance << "</DartMeasurement>" << std::endl;

    std::string volumeName = OutputDir + "/" + name + ".nrrd";
    sitk::ImageFileWriter().SetFileName ( volumeName ).Execute ( centerSlice );

    // Save pngs
    std::string ExpectedImageFilename = OutputDir + "/" + name + "_Expected.png";
    std::string ActualImageFilename = OutputDir + "/" + name + "_Actual.png";
    std::string DifferenceImageFilename = OutputDir + "/" + name + "_Difference.png";

    NormalizeAndSave ( baseline, ExpectedImageFilename );
    NormalizeAndSave ( centerSlice, ActualImageFilename );
    NormalizeAndSave ( sitk::Sqrt(diffSquared), DifferenceImageFilename );

    // Let ctest know about it
    std::cout << "<DartMeasurementFile name=\"ExpectedImage\" type=\"image/png\">";
    std::cout << ExpectedImageFilename << "</DartMeasurementFile>" << std::endl;
    std::cout << "<DartMeasurementFile name=\"ActualImage\" type=\"image/png\">";
    std::cout << ActualImageFilename << "</DartMeasurementFile>" << std::endl;
    std::cout << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">";
    std::cout << DifferenceImageFilename << "</DartMeasurementFile>" << std::endl;

    return false;
  }

  return true;
}
<commit_msg>Fix runtime error in extracting slice.<commit_after>/*=========================================================================
*
*  Copyright Insight Software Consortium
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*         http://www.apache.org/licenses/LICENSE-2.0.txt
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*=========================================================================*/
#include <SimpleITK.h>
#include <memory>

#include "ImageCompare.h"

namespace sitk = itk::simple;

void ImageCompare::NormalizeAndSave ( const sitk::Image &input, const std::string &filename )
{
  sitk::Image image = input;

  // Extract the center slice of our image
  if ( input.GetDimension() == 3 )
    {
    std::vector<int> idx( 3, 0 );
    std::vector<unsigned int> sz = input.GetSize();

    // set to just the center slice
    idx[2] = (int)( input.GetDepth() / 2 );
    sz[2] = 0;
    image = sitk::Extract( input, sz, idx );
    }

  sitk::StatisticsImageFilter stats;
  stats.Execute ( image );
  sitk::Image out = sitk::IntensityWindowing ( image, stats.GetMinimum(), stats.GetMaximum(), 0, 255 );
  out = sitk::Cast ( out, sitk::sitkUInt8 );
  sitk::WriteImage ( out, filename );
}

ImageCompare::ImageCompare()
{
  mTolerance = 0.0;
  mMessage = "";
}

bool ImageCompare::compare ( const sitk::Image& image, std::string inTestCase, std::string inTag )
{
  sitk::Image centerSlice( 0, 0, sitk::sitkUInt8 );
  std::string testCase = inTestCase;
  std::string tag = inTag;
  std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name();

  if ( testCase == "" )
    {
    testCase = ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name();
    }

  std::cout << "Starting image compare on " << testCase << "_" << testName << "_" << tag << std::endl;
  // Does the baseline exist?
  std::string extension = ".nrrd";
  std::string OutputDir = dataFinder.GetOutputDirectory();

  std::string name = testCase
    .append( "_" )
    .append(testName);

  if ( tag != "" )
    {
    name.append("_").append ( tag );
    }

  // Extract the center slice of our image
  if ( image.GetDimension() == 3 )
    {
    std::vector<int> idx( 3, 0 );
    std::vector<unsigned int> sz = image.GetSize();

    // set to just the center slice
    idx[2] = (int)( image.GetDepth() / 2 );
    sz[2] = 1;
    centerSlice = sitk::RegionOfInterest( image, sz, idx );
    }
  else
    {
    centerSlice = image;
    }

  std::string baselineFileName = dataFinder.GetSourceDirectory() + "/Testing/Data/Baseline/" + name + extension;

  if ( !itksys::SystemTools::FileExists ( baselineFileName.c_str() ) )
    {
    // Baseline does not exist, write out what we've been given
    std::string newBaselineDir = OutputDir + "/Newbaseline/";
    itksys::SystemTools::MakeDirectory ( newBaselineDir.c_str() );
    std::cout << "Making directory " << newBaselineDir << std::endl;
    std::string newBaseline = newBaselineDir + name + extension;
    sitk::ImageFileWriter().SetFileName ( newBaseline ).Execute ( centerSlice );
    mMessage = "Baseline does not exist, wrote " + newBaseline + "\ncp " + newBaseline + " " + baselineFileName;
    return false;
    }

  sitk::Image baseline( 0, 0, sitk::sitkUInt8 );
  std::cout << "Loading baseline " << baselineFileName << std::endl;

  try
    {
    baseline = sitk::ImageFileReader().SetFileName ( baselineFileName ).Execute();
    }
  catch ( std::exception& e )
    {
    mMessage = "ImageCompare: Failed to load image " + baselineFileName + " because: " + e.what();
    return false;
    }

  // verify they have the same size
  if ( baseline.GetHeight() != centerSlice.GetHeight()
       || baseline.GetWidth() != centerSlice.GetWidth()
       || baseline.GetDepth() != centerSlice.GetDepth() )
    {
    mMessage = "ImageCompare: Image dimensions are different";
    return false;
    }

  // Get the center slices
  sitk::Image diffSquared( 0, 0, itk::simple::sitkUInt8 );
  try
    {

    if ( baseline.GetPixelIDValue() == sitk::sitkComplexFloat32 ||
         baseline.GetPixelIDValue() == sitk::sitkComplexFloat64 )
      {

      sitk::Image diff =  sitk::Subtract( centerSlice, baseline );
      // for complex number we multiply the image by it's complex
      // conjugate, this will produce only a real value result
      sitk::Image conj = sitk::RealAndImaginaryToComplex( sitk::ComplexToReal( diff ),
                                                          sitk::MultiplyByConstant( sitk::ComplexToImaginary( diff ), -1 ) );
      diffSquared = sitk::ComplexToReal( sitk::Multiply( diff, conj ) );
      }
    else if ( baseline.GetNumberOfComponentsPerPixel() > 1 )
      {
      sitk::Image diff =  sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkVectorFloat32 ), sitk::Cast( baseline, sitk::sitkVectorFloat32 ) );

      // for vector image just do a sum of the components
      diffSquared  = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, 0 ), 2 );
      for ( unsigned int i = 1; i < diff.GetNumberOfComponentsPerPixel(); ++i )
        {
        sitk::Image temp = sitk::PowToConstant( sitk::VectorIndexSelectionCast( diff, i ), 2 );
        diffSquared = sitk::Add( temp, diffSquared );
        }

      diffSquared = sitk::DivideByConstant( diffSquared, diff.GetNumberOfComponentsPerPixel() );
      }
    else
      {
      sitk::Image diff =  sitk::Subtract( sitk::Cast( centerSlice, sitk::sitkFloat32 ), sitk::Cast( baseline, sitk::sitkFloat32 ) );
      diffSquared = sitk::Multiply( diff, diff );
      }

    }
  catch ( std::exception& e )
    {
    mMessage = "ImageCompare: Failed to subtract image " + baselineFileName + " because: " + e.what();
    return false;
    }

  sitk::StatisticsImageFilter stats;
  stats.Execute ( diffSquared );
  double rms = std::sqrt ( stats.GetMean() );

  if ( rms > fabs ( mTolerance ) )
    {
    std::ostringstream msg;
    msg << "ImageCompare: image Root Mean Square (RMS) difference was " << rms << " which exceeds the tolerance of " << mTolerance;
    msg << "\n";
    mMessage = msg.str();

    std::cout << "<DartMeasurement name=\"RMSeDifference\" type=\"numeric/float\">" << rms << "</DartMeasurement>" << std::endl;
    std::cout << "<DartMeasurement name=\"Tolerance\" type=\"numeric/float\">" << mTolerance << "</DartMeasurement>" << std::endl;

    std::string volumeName = OutputDir + "/" + name + ".nrrd";
    sitk::ImageFileWriter().SetFileName ( volumeName ).Execute ( centerSlice );

    // Save pngs
    std::string ExpectedImageFilename = OutputDir + "/" + name + "_Expected.png";
    std::string ActualImageFilename = OutputDir + "/" + name + "_Actual.png";
    std::string DifferenceImageFilename = OutputDir + "/" + name + "_Difference.png";

    try
      {
      NormalizeAndSave ( baseline, ExpectedImageFilename );
      NormalizeAndSave ( centerSlice, ActualImageFilename );
      NormalizeAndSave ( sitk::Sqrt(diffSquared), DifferenceImageFilename );

      // Let ctest know about it
      std::cout << "<DartMeasurementFile name=\"ExpectedImage\" type=\"image/png\">";
      std::cout << ExpectedImageFilename << "</DartMeasurementFile>" << std::endl;
      std::cout << "<DartMeasurementFile name=\"ActualImage\" type=\"image/png\">";
      std::cout << ActualImageFilename << "</DartMeasurementFile>" << std::endl;
      std::cout << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">";
      std::cout << DifferenceImageFilename << "</DartMeasurementFile>" << std::endl;

      }
    catch( std::exception &e )
      {
      std::cerr << "Exception encountered while trying to normalize and save images for dashboard!" << std::endl;
      std::cerr << e.what() << std::endl;
      }
    catch(...)
      {
      std::cerr << "Unexpected error while trying to normalize and save images for dashboard!" << std::endl;
      }

    return false;
  }

  return true;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/api/operations_test.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia_base.hpp>
#include <c7a/net/endpoint.hpp>
#include <c7a/core/job_manager.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/reduce_node.hpp>
#include <c7a/api/sum_node.hpp>
#include <c7a/api/bootstrap.hpp>

#include <algorithm>
#include <random>

#include "gtest/gtest.h"

using namespace c7a::core;
using namespace c7a::net;

TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) {
    using c7a::Context;

    Context ctx;
    std::vector<std::string> self = { "127.0.0.1:1234" };
    ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self));

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(1000, 10000);

    size_t generate_size = distribution(generator);

    auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            std::cout << line << std::endl;
            return std::stoi(line);
        },
        generate_size);

    size_t writer_size = 0;

    input.WriteToFileSystem("test1.out",
                           [&writer_size](const int& item) {
                                //file contains ints between 1  and 15
                                //fails if wrong integer is generated
                                EXPECT_GE(item, 1);
                                EXPECT_GE(16, item);
                                writer_size++;
                                return std::to_string(item);
                           });

    ASSERT_EQ(generate_size, writer_size);
}

TEST(Operations, ReadAndAllGatherElementsCorrect) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::vector<int> out_vec;

        integers.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, i++);
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, MapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> double_elements = [](int in) {
            return (double) 2 * in;
        };

        auto doubled = integers.Map(double_elements);

        std::vector<double> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FlatMapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto flatmap_double = [](int in, auto emit) {
            emit((double) 2 * in);
            emit((double) 2 * (in + 16));
        };

        auto doubled = integers.FlatMap(flatmap_double);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 32, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FilterResultsCorrectly) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> even = [](int in) {
            return (in % 2 == 0);
        };

        auto doubled = integers.Filter(even);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 8, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, DISABLED_ReduceModulo2CorrectResults) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto modulo_two = [](int in) {
            return (in / 2);
        };

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        auto reduced = integers.ReduceBy(modulo_two, add_function);

        std::vector<int> out_vec;

         std::cout << "starting" << std::endl;

        reduced.AllGather(&out_vec);

        std::cout << "testing" << std::endl;

        std::sort(out_vec.begin(), out_vec.end());

        std::cout << "[";
        for (int element : out_vec) {
            std::cout << element << ",";
        }
        std::cout<<"]"<<std::endl;

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, 56 + (8 * i++));
        }

        ASSERT_EQ((size_t) 2, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::uniform_int_distribution<int> distribution2(1000, 10000);

    size_t generate_size = distribution2(generator);

    std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) {

        auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            return std::stoi(line);
        },
        generate_size);

        auto ones = input.Map([](int){
                return 1;
            });

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        ASSERT_EQ((int) generate_size, ones.Sum(add_function));
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

/******************************************************************************/
<commit_msg>re-enable reduce test, trying to fix clang build<commit_after>/*******************************************************************************
 * tests/api/operations_test.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/dia_base.hpp>
#include <c7a/net/endpoint.hpp>
#include <c7a/core/job_manager.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/reduce_node.hpp>
#include <c7a/api/sum_node.hpp>
#include <c7a/api/bootstrap.hpp>

#include <algorithm>
#include <random>
#include <string>

#include "gtest/gtest.h"

using namespace c7a::core;
using namespace c7a::net;

TEST(Operations, GenerateFromFileCorrectAmountOfCorrectIntegers) {
    using c7a::Context;

    Context ctx;
    std::vector<std::string> self = { "127.0.0.1:1234" };
    ctx.job_manager().Connect(0, Endpoint::ParseEndpointList(self));

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(1000, 10000);

    size_t generate_size = distribution(generator);

    auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            std::cout << line << std::endl;
            return std::stoi(line);
        },
        generate_size);

    size_t writer_size = 0;

    input.WriteToFileSystem("test1.out",
                           [&writer_size](const int& item) {
                                //file contains ints between 1  and 15
                                //fails if wrong integer is generated
                                EXPECT_GE(item, 1);
                                EXPECT_GE(16, item);
                                writer_size++;
                                return std::to_string(item);
                           });

    ASSERT_EQ(generate_size, writer_size);
}

TEST(Operations, ReadAndAllGatherElementsCorrect) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                try {
                    return std::stoi(line);
                } catch (const std::invalid_argument&) {
                    std::cout << "\"" << line << "\"" << std::endl;
                    return 0;
                }
            });

        std::vector<int> out_vec;

        integers.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, i++);
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, MapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> double_elements = [](int in) {
            return (double) 2 * in;
        };

        auto doubled = integers.Map(double_elements);

        std::vector<double> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 16, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FlatMapResultsCorrectChangingType) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto flatmap_double = [](int in, auto emit) {
            emit((double) 2 * in);
            emit((double) 2 * (in + 16));
        };

        auto doubled = integers.FlatMap(flatmap_double);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 32, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, FilterResultsCorrectly) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        std::function<double(int)> even = [](int in) {
            return (in % 2 == 0);
        };

        auto doubled = integers.Filter(even);

        std::vector<int> out_vec;

        doubled.AllGather(&out_vec);

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_DOUBLE_EQ(element, (i++ * 2));
        }

        ASSERT_EQ((size_t) 8, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, ReduceModulo2CorrectResults) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::function<void(c7a::Context&)> start_func = [](c7a::Context& ctx) {

        auto integers = ReadLines(
            ctx,
            "test1",
            [](const std::string& line) {
                return std::stoi(line);
            });

        auto modulo_two = [](int in) {
            return (in % 2);
        };

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        auto reduced = integers.ReduceBy(modulo_two, add_function);

        std::vector<int> out_vec;

         std::cout << "starting" << std::endl;

        reduced.AllGather(&out_vec);

        std::cout << "testing" << std::endl;

        std::sort(out_vec.begin(), out_vec.end());

        int i = 1;
        for (int element : out_vec) {
            ASSERT_EQ(element, 56 + (8 * i++));
        }

        ASSERT_EQ((size_t) 2, out_vec.size());
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

TEST(Operations, DISABLED_GenerateAndSumHaveEqualAmount) {

    std::random_device random_device;
    std::default_random_engine generator(random_device());
    std::uniform_int_distribution<int> distribution(2, 4);

    size_t workers = distribution(generator);
    size_t port_base = 8080;

    std::uniform_int_distribution<int> distribution2(1000, 10000);

    size_t generate_size = distribution2(generator);

    std::function<void(c7a::Context&)> start_func = [generate_size](c7a::Context& ctx) {

        auto input = GenerateFromFile(
        ctx,
        "test1",
        [](const std::string& line) {
            return std::stoi(line);
        },
        generate_size);

        auto ones = input.Map([](int){
                return 1;
            });

        auto add_function = [](int in1, int in2) {
            return in1 + in2;
        };

        ASSERT_EQ((int) generate_size, ones.Sum(add_function));
    };

    c7a::ExecuteThreads(workers, port_base, start_func);

}

/******************************************************************************/
<|endoftext|>


<commit_before><commit_msg>Files.app: Disable all browser tests of Files.app in slow environment.<commit_after><|endoftext|>


<commit_before>#include "SwitchingFunctionMaterial.h"

template<>
InputParameters validParams<SwitchingFunctionMaterial>()
{
  InputParameters params = validParams<OrderParameterFunctionMaterial>();
  params.addClassDescription("Helper material to provide h(eta) and its derivative in one of two polynomial forms.\nSIMPLE: 3*eta^2-2*eta^3\nHIGH: eta^3*(6*eta^2-15*eta+10)");
  MooseEnum h_order("SIMPLE=0 HIGH", "SIMPLE");
  params.addParam<MooseEnum>("h_order", h_order, "Polynomial order of the switching function h(eta)");
  params.set<std::string>("function_name") = std::string("h");
  return params;
}

SwitchingFunctionMaterial::SwitchingFunctionMaterial(const std::string & name,
                                                     InputParameters parameters) :
    OrderParameterFunctionMaterial(name, parameters),
    _h_order(getParam<MooseEnum>("h_order"))
{
}

void
SwitchingFunctionMaterial::computeQpProperties()
{
  switch (_h_order)
  {
    case 0: // SIMPLE
      _prop_f[_qp] =   3.0 * _eta[_qp]*_eta[_qp]
                     - 2.0 * _eta[_qp]*_eta[_qp]*_eta[_qp];
      _prop_df[_qp] =   6.0 * _eta[_qp]
                      - 6.0 * _eta[_qp]*_eta[_qp];
      _prop_d2f[_qp] = 6.0 - 12.0 * _eta[_qp];
      break;

    case 1: // HIGH
      _prop_f[_qp] =   _eta[_qp]*_eta[_qp]*_eta[_qp]
                     * (6.0 * _eta[_qp]*_eta[_qp] - 15.0 * _eta[_qp] + 10.0);
      _prop_df[_qp] =   30.0 * _eta[_qp]*_eta[_qp]
                      * (_eta[_qp]*_eta[_qp] - 2.0 * _eta[_qp] + 1.0);
      _prop_d2f[_qp] = _eta[_qp] * (120.0 * _eta[_qp]*_eta[_qp] - 180.0 * _eta[_qp] + 60.0);
      break;

    default:
      mooseError("Internal error");
  }
}
<commit_msg>Limit SwitchingFunctionMaterial (#4665)<commit_after>#include "SwitchingFunctionMaterial.h"

template<>
InputParameters validParams<SwitchingFunctionMaterial>()
{
  InputParameters params = validParams<OrderParameterFunctionMaterial>();
  params.addClassDescription("Helper material to provide h(eta) and its derivative in one of two polynomial forms.\nSIMPLE: 3*eta^2-2*eta^3\nHIGH: eta^3*(6*eta^2-15*eta+10)");
  MooseEnum h_order("SIMPLE=0 HIGH", "SIMPLE");
  params.addParam<MooseEnum>("h_order", h_order, "Polynomial order of the switching function h(eta)");
  params.set<std::string>("function_name") = std::string("h");
  return params;
}

SwitchingFunctionMaterial::SwitchingFunctionMaterial(const std::string & name,
                                                     InputParameters parameters) :
    OrderParameterFunctionMaterial(name, parameters),
    _h_order(getParam<MooseEnum>("h_order"))
{
}

void
SwitchingFunctionMaterial::computeQpProperties()
{
  Real n = _eta[_qp];
  n = n>1 ? 1 : (n<0 ? 0 : n);

  switch (_h_order)
  {
    case 0: // SIMPLE
      _prop_f[_qp]   = 3.0 * n*n - 2.0 * n*n*n;
      _prop_df[_qp]  = 6.0 * n - 6.0 * n*n;
      _prop_d2f[_qp] = 6.0 - 12.0 * n;
      break;

    case 1: // HIGH
      _prop_f[_qp]   = n*n*n * (6.0 * n*n - 15.0 * n + 10.0);
      _prop_df[_qp]  = 30.0 * n*n * (n*n - 2.0 * n + 1.0);
      _prop_d2f[_qp] = n * (120.0 * n*n - 180.0 * n + 60.0);
      break;

    default:
      mooseError("Internal error");
  }
}
<|endoftext|>


<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_GEO_TRAVERSAL_HPP_
#define RDB_PROTOCOL_GEO_TRAVERSAL_HPP_

#include <set>
#include <vector>

#include "errors.hpp"
#include <boost/optional.hpp>

#include "btree/keys.hpp"
#include "btree/slice.hpp"
#include "containers/counted.hpp"
#include "geo/indexing.hpp"
#include "rdb_protocol/datum.hpp"
#include "rdb_protocol/protocol.hpp"

namespace ql {
class datum_t;
class func_t;
class op_t;
}
class profile::disabler_t;
class profile::sampler_t;

class geo_io_data_t {
public:
    geo_io_data_t(intersecting_geo_read_response_t *_response, btree_slice_t *_slice)
        : response(_response), slice(_slice) { }
private:
    friend class geo_intersecting_cb_t;
    intersecting_geo_read_response_t *const response;
    btree_slice_t *const slice;
};

class geo_sindex_data_t {
public:
    geo_sindex_data_t(const key_range_t &_pkey_range,
                      const counted_t<const ql::datum_t> &_query_geometry,
                      ql::map_wire_func_t wire_func, sindex_multi_bool_t _multi)
        : pkey_range(_pkey_range), query_geometry(_query_geometry),
          func(wire_func.compile_wire_func()), multi(_multi) { }
private:
    friend class geo_intersecting_cb_t;
    const key_range_t pkey_range;
    const counted_t<const ql::datum_t> query_geometry;
    const counted_t<ql::func_t> func;
    const sindex_multi_bool_t multi;
};

class geo_intersecting_cb_t : public geo_index_traversal_helper_t {
public:
    geo_intersecting_cb_t(
            geo_io_data_t &&_io,
            const geo_sindex_data_t &&_sindex,
            ql::env_t *_env);

    void on_candidate(
            const btree_key_t *key,
            const void *value,
            buf_parent_t parent)
            THROWS_ONLY(interrupted_exc_t);

    void finish() THROWS_ONLY(interrupted_exc_t);
private:
    const geo_io_data_t io; // How do get data in/out.
    const geo_sindex_data_t sindex;

    ql::env_t *env;
    // Accumulates the data
    ql::datum_ptr_t result_acc;

    // Stores the primary key of previously processed documents
    std::set<store_key_t> already_processed;

    // State for profiling.
    scoped_ptr_t<profile::disabler_t> disabler;
    scoped_ptr_t<profile::sampler_t> sampler;
};

#endif  // RDB_PROTOCOL_GEO_TRAVERSAL_HPP_
<commit_msg>Compilation fix<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_GEO_TRAVERSAL_HPP_
#define RDB_PROTOCOL_GEO_TRAVERSAL_HPP_

#include <set>
#include <vector>

#include "errors.hpp"
#include <boost/optional.hpp>

#include "btree/keys.hpp"
#include "btree/slice.hpp"
#include "containers/counted.hpp"
#include "geo/indexing.hpp"
#include "rdb_protocol/datum.hpp"
#include "rdb_protocol/protocol.hpp"

namespace ql {
class datum_t;
class func_t;
class op_t;
}
namespace profile {
class disabler_t;
class sampler_t;
}

class geo_io_data_t {
public:
    geo_io_data_t(intersecting_geo_read_response_t *_response, btree_slice_t *_slice)
        : response(_response), slice(_slice) { }
private:
    friend class geo_intersecting_cb_t;
    intersecting_geo_read_response_t *const response;
    btree_slice_t *const slice;
};

class geo_sindex_data_t {
public:
    geo_sindex_data_t(const key_range_t &_pkey_range,
                      const counted_t<const ql::datum_t> &_query_geometry,
                      ql::map_wire_func_t wire_func, sindex_multi_bool_t _multi)
        : pkey_range(_pkey_range), query_geometry(_query_geometry),
          func(wire_func.compile_wire_func()), multi(_multi) { }
private:
    friend class geo_intersecting_cb_t;
    const key_range_t pkey_range;
    const counted_t<const ql::datum_t> query_geometry;
    const counted_t<ql::func_t> func;
    const sindex_multi_bool_t multi;
};

class geo_intersecting_cb_t : public geo_index_traversal_helper_t {
public:
    geo_intersecting_cb_t(
            geo_io_data_t &&_io,
            const geo_sindex_data_t &&_sindex,
            ql::env_t *_env);

    void on_candidate(
            const btree_key_t *key,
            const void *value,
            buf_parent_t parent)
            THROWS_ONLY(interrupted_exc_t);

    void finish() THROWS_ONLY(interrupted_exc_t);
private:
    const geo_io_data_t io; // How do get data in/out.
    const geo_sindex_data_t sindex;

    ql::env_t *env;
    // Accumulates the data
    ql::datum_ptr_t result_acc;

    // Stores the primary key of previously processed documents
    std::set<store_key_t> already_processed;

    // State for profiling.
    scoped_ptr_t<profile::disabler_t> disabler;
    scoped_ptr_t<profile::sampler_t> sampler;
};

#endif  // RDB_PROTOCOL_GEO_TRAVERSAL_HPP_
<|endoftext|>


<commit_before>#include "generatorBase/converters/stringPropertyConverter.h"

using namespace generatorBase::converters;
using namespace qReal;

QString StringPropertyConverter::convert(QString const &data) const
{
	QString result = data;
	return "\"" + result.replace("\"", "\\\"") + "\"";
}
<commit_msg>Fixed print text block containing line breaks generation<commit_after>#include "generatorBase/converters/stringPropertyConverter.h"

using namespace generatorBase::converters;
using namespace qReal;

QString StringPropertyConverter::convert(QString const &data) const
{
	QString result = data;
	return "\"" + result.replace("\"", "\\\"").replace("\n", "\"\\\n\t\t\"") + "\"";
}
<|endoftext|>


<commit_before>/* Copyright (c) 2012 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include <sys/types.h>  // Include something that will define __GLIBC__.

// The entire file is wrapped in this #if. We do this so this .cc file can be
// compiled, even on a non-newlib build.
#if defined(__native_client__) && !defined(__GLIBC__)

#include "nacl_io/kernel_wrap.h"
#include <dirent.h>
#include <errno.h>
#include <irt.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "nacl_io/kernel_intercept.h"

EXTERN_C_BEGIN

#define REAL(name) __nacl_irt_##name##_real
#define WRAP(name) __nacl_irt_##name##_wrap
#define STRUCT_NAME(group) __libnacl_irt_##group
#define DECLARE_STRUCT(group) \
  extern struct nacl_irt_##group STRUCT_NAME(group);
#define DECLARE_STRUCT_VERSION(group, version) \
  extern struct nacl_irt_##group##_##version STRUCT_NAME(group);
#define MUX(group, name) STRUCT_NAME(group).name
#define DECLARE(group, name) typeof(MUX(group, name)) REAL(name);
#define DO_WRAP(group, name) do { \
    REAL(name) = MUX(group, name); \
    MUX(group, name) = (typeof(REAL(name))) WRAP(name); \
  } while (0)

DECLARE_STRUCT(fdio)
DECLARE_STRUCT(filename)
DECLARE_STRUCT_VERSION(memory, v0_2)

DECLARE(fdio, close)
DECLARE(fdio, dup)
DECLARE(fdio, dup2)
DECLARE(fdio, fstat)
DECLARE(fdio, getdents)
DECLARE(fdio, read)
DECLARE(fdio, seek)
DECLARE(fdio, write)
DECLARE(filename, open)
DECLARE(filename, stat)
DECLARE(memory, mmap)
DECLARE(memory, munmap)

int access(const char* path, int amode) {
  return ki_access(path, amode);
}

int chdir(const char* path) {
  return ki_chdir(path);
}

int chmod(const char* path, mode_t mode) {
  return ki_chmod(path, mode);
}

int WRAP(close)(int fd) {
  return (ki_close(fd) < 0) ? errno : 0;
}

int WRAP(dup)(int fd, int* newfd) {
  *newfd = ki_dup(fd);
  return (*newfd < 0) ? errno : 0;
}

int WRAP(dup2)(int fd, int newfd) {
  newfd = ki_dup2(fd, newfd);
  return (newfd < 0) ? errno : 0;
}

int WRAP(fstat)(int fd, struct stat *buf) {
  return (ki_fstat(fd, buf) < 0) ? errno : 0;
}

int fsync(int fd) {
  return ki_fsync(fd);
}

char* getcwd(char* buf, size_t size) {
  return ki_getcwd(buf, size);
}

char* getwd(char* buf) {
  return ki_getwd(buf);
}

int getdents(int fd, void* buf, unsigned int count) {
  return ki_getdents(fd, buf, count);
}

int WRAP(getdents)(int fd, dirent* buf, size_t count, size_t *nread) {
  return (ki_getdents(fd, buf, count) < 0) ? errno : 0;
}

int isatty(int fd) {
  return ki_isatty(fd);
}

int link(const char* oldpath, const char* newpath) {
  return ki_link(oldpath, newpath);
}

int mkdir(const char* path, mode_t mode) {
  return ki_mkdir(path, mode);
}

int WRAP(mmap)(void** addr, size_t length, int prot, int flags, int fd,
               off_t offset) {
  if (flags & MAP_ANONYMOUS)
    return REAL(mmap)(addr, length, prot, flags, fd, offset);

  *addr = ki_mmap(*addr, length, prot, flags, fd, offset);
  return *addr == (void*)-1 ? errno : 0;
}

int mount(const char* source, const char* target, const char* filesystemtype,
          unsigned long mountflags, const void* data) {
  return ki_mount(source, target, filesystemtype, mountflags, data);
}

int WRAP(munmap)(void* addr, size_t length) {
  // Always let the real munmap run on the address range. It is not an error if
  // there are no mapped pages in that range.
  ki_munmap(addr, length);
  return REAL(munmap)(addr, length);
}

int WRAP(open)(const char* pathname, int oflag, mode_t cmode, int* newfd) {
  *newfd = ki_open(pathname, oflag);
  return (*newfd < 0) ? errno : 0;
}

int WRAP(read)(int fd, void *buf, size_t count, size_t *nread) {
  if (!ki_is_initialized())
    return REAL(read)(fd, buf, count, nread);

  ssize_t signed_nread = ki_read(fd, buf, count);
  *nread = static_cast<size_t>(signed_nread);
  return (signed_nread < 0) ? errno : 0;
}

int remove(const char* path) {
  return ki_remove(path);
}

int rmdir(const char* path) {
  return ki_rmdir(path);
}

int WRAP(seek)(int fd, off_t offset, int whence, off_t* new_offset) {
  *new_offset = ki_lseek(fd, offset, whence);
  return (*new_offset < 0) ? errno : 0;
}

int WRAP(stat)(const char *pathname, struct stat *buf) {
  return (ki_stat(pathname, buf) < 0) ? errno : 0;
}

int symlink(const char* oldpath, const char* newpath) {
  return ki_symlink(oldpath, newpath);
}

int umount(const char* path) {
  return ki_umount(path);
}

int unlink(const char* path) {
  return ki_unlink(path);
}

int WRAP(write)(int fd, const void *buf, size_t count, size_t *nwrote) {
  if (!ki_is_initialized())
    return REAL(write)(fd, buf, count, nwrote);

  ssize_t signed_nwrote = ki_write(fd, buf, count);
  *nwrote = static_cast<size_t>(signed_nwrote);
  return (signed_nwrote < 0) ? errno : 0;
}

// "real" functions, i.e. the unwrapped original functions.

int _real_close(int fd) {
  return REAL(close)(fd);
}

int _real_fstat(int fd, struct stat *buf) {
  return REAL(fstat)(fd, buf);
}

int _real_getdents(int fd, dirent* nacl_buf, size_t nacl_count, size_t *nread) {
  return REAL(getdents)(fd, nacl_buf, nacl_count, nread);
}

int _real_lseek(int fd, off_t offset, int whence, off_t* new_offset) {
  return REAL(seek)(fd, offset, whence, new_offset);
}

int _real_mkdir(const char* pathname, mode_t mode) {
  return ENOSYS;
}

int _real_mmap(void** addr, size_t length, int prot, int flags, int fd,
               off_t offset) {
  return REAL(mmap)(addr, length, prot, flags, fd, offset);
}

int _real_munmap(void* addr, size_t length) {
  return REAL(munmap)(addr, length);
}

int _real_open(const char* pathname, int oflag, mode_t cmode, int* newfd) {
  return REAL(open)(pathname, oflag, cmode, newfd);
}

int _real_open_resource(const char* file, int* fd) {
  return ENOSYS;
}

int _real_read(int fd, void *buf, size_t count, size_t *nread) {
  return REAL(read)(fd, buf, count, nread);
}

int _real_rmdir(const char* pathname) {
  return ENOSYS;
}

int _real_write(int fd, const void *buf, size_t count, size_t *nwrote) {
  return REAL(write)(fd, buf, count, nwrote);
}

void kernel_wrap_init() {
  static bool wrapped = false;

  if (!wrapped) {
    wrapped = true;
    DO_WRAP(fdio, close);
    DO_WRAP(fdio, dup);
    DO_WRAP(fdio, dup2);
    DO_WRAP(fdio, fstat);
    DO_WRAP(fdio, getdents);
    DO_WRAP(fdio, read);
    DO_WRAP(fdio, seek);
    DO_WRAP(fdio, write);
    DO_WRAP(filename, open);
    DO_WRAP(filename, stat);
    DO_WRAP(memory, mmap);
    DO_WRAP(memory, munmap);
  }
}

EXTERN_C_END

#endif  // defined(__native_client__) && !defined(__GLIBC__)
<commit_msg>[NaCl SDK] nacl_irt_memory renamed again, broke nacl_io build.<commit_after>/* Copyright (c) 2012 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include <sys/types.h>  // Include something that will define __GLIBC__.

// The entire file is wrapped in this #if. We do this so this .cc file can be
// compiled, even on a non-newlib build.
#if defined(__native_client__) && !defined(__GLIBC__)

#include "nacl_io/kernel_wrap.h"
#include <dirent.h>
#include <errno.h>
#include <irt.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "nacl_io/kernel_intercept.h"

EXTERN_C_BEGIN

#define REAL(name) __nacl_irt_##name##_real
#define WRAP(name) __nacl_irt_##name##_wrap
#define STRUCT_NAME(group) __libnacl_irt_##group
#define DECLARE_STRUCT(group) \
  extern struct nacl_irt_##group STRUCT_NAME(group);
#define DECLARE_STRUCT_VERSION(group, version) \
  extern struct nacl_irt_##group##_##version STRUCT_NAME(group);
#define MUX(group, name) STRUCT_NAME(group).name
#define DECLARE(group, name) typeof(MUX(group, name)) REAL(name);
#define DO_WRAP(group, name) do { \
    REAL(name) = MUX(group, name); \
    MUX(group, name) = (typeof(REAL(name))) WRAP(name); \
  } while (0)

DECLARE_STRUCT(fdio)
DECLARE_STRUCT(filename)
DECLARE_STRUCT(memory)

DECLARE(fdio, close)
DECLARE(fdio, dup)
DECLARE(fdio, dup2)
DECLARE(fdio, fstat)
DECLARE(fdio, getdents)
DECLARE(fdio, read)
DECLARE(fdio, seek)
DECLARE(fdio, write)
DECLARE(filename, open)
DECLARE(filename, stat)
DECLARE(memory, mmap)
DECLARE(memory, munmap)

int access(const char* path, int amode) {
  return ki_access(path, amode);
}

int chdir(const char* path) {
  return ki_chdir(path);
}

int chmod(const char* path, mode_t mode) {
  return ki_chmod(path, mode);
}

int WRAP(close)(int fd) {
  return (ki_close(fd) < 0) ? errno : 0;
}

int WRAP(dup)(int fd, int* newfd) {
  *newfd = ki_dup(fd);
  return (*newfd < 0) ? errno : 0;
}

int WRAP(dup2)(int fd, int newfd) {
  newfd = ki_dup2(fd, newfd);
  return (newfd < 0) ? errno : 0;
}

int WRAP(fstat)(int fd, struct stat *buf) {
  return (ki_fstat(fd, buf) < 0) ? errno : 0;
}

int fsync(int fd) {
  return ki_fsync(fd);
}

char* getcwd(char* buf, size_t size) {
  return ki_getcwd(buf, size);
}

char* getwd(char* buf) {
  return ki_getwd(buf);
}

int getdents(int fd, void* buf, unsigned int count) {
  return ki_getdents(fd, buf, count);
}

int WRAP(getdents)(int fd, dirent* buf, size_t count, size_t *nread) {
  return (ki_getdents(fd, buf, count) < 0) ? errno : 0;
}

int isatty(int fd) {
  return ki_isatty(fd);
}

int link(const char* oldpath, const char* newpath) {
  return ki_link(oldpath, newpath);
}

int mkdir(const char* path, mode_t mode) {
  return ki_mkdir(path, mode);
}

int WRAP(mmap)(void** addr, size_t length, int prot, int flags, int fd,
               off_t offset) {
  if (flags & MAP_ANONYMOUS)
    return REAL(mmap)(addr, length, prot, flags, fd, offset);

  *addr = ki_mmap(*addr, length, prot, flags, fd, offset);
  return *addr == (void*)-1 ? errno : 0;
}

int mount(const char* source, const char* target, const char* filesystemtype,
          unsigned long mountflags, const void* data) {
  return ki_mount(source, target, filesystemtype, mountflags, data);
}

int WRAP(munmap)(void* addr, size_t length) {
  // Always let the real munmap run on the address range. It is not an error if
  // there are no mapped pages in that range.
  ki_munmap(addr, length);
  return REAL(munmap)(addr, length);
}

int WRAP(open)(const char* pathname, int oflag, mode_t cmode, int* newfd) {
  *newfd = ki_open(pathname, oflag);
  return (*newfd < 0) ? errno : 0;
}

int WRAP(read)(int fd, void *buf, size_t count, size_t *nread) {
  if (!ki_is_initialized())
    return REAL(read)(fd, buf, count, nread);

  ssize_t signed_nread = ki_read(fd, buf, count);
  *nread = static_cast<size_t>(signed_nread);
  return (signed_nread < 0) ? errno : 0;
}

int remove(const char* path) {
  return ki_remove(path);
}

int rmdir(const char* path) {
  return ki_rmdir(path);
}

int WRAP(seek)(int fd, off_t offset, int whence, off_t* new_offset) {
  *new_offset = ki_lseek(fd, offset, whence);
  return (*new_offset < 0) ? errno : 0;
}

int WRAP(stat)(const char *pathname, struct stat *buf) {
  return (ki_stat(pathname, buf) < 0) ? errno : 0;
}

int symlink(const char* oldpath, const char* newpath) {
  return ki_symlink(oldpath, newpath);
}

int umount(const char* path) {
  return ki_umount(path);
}

int unlink(const char* path) {
  return ki_unlink(path);
}

int WRAP(write)(int fd, const void *buf, size_t count, size_t *nwrote) {
  if (!ki_is_initialized())
    return REAL(write)(fd, buf, count, nwrote);

  ssize_t signed_nwrote = ki_write(fd, buf, count);
  *nwrote = static_cast<size_t>(signed_nwrote);
  return (signed_nwrote < 0) ? errno : 0;
}

// "real" functions, i.e. the unwrapped original functions.

int _real_close(int fd) {
  return REAL(close)(fd);
}

int _real_fstat(int fd, struct stat *buf) {
  return REAL(fstat)(fd, buf);
}

int _real_getdents(int fd, dirent* nacl_buf, size_t nacl_count, size_t *nread) {
  return REAL(getdents)(fd, nacl_buf, nacl_count, nread);
}

int _real_lseek(int fd, off_t offset, int whence, off_t* new_offset) {
  return REAL(seek)(fd, offset, whence, new_offset);
}

int _real_mkdir(const char* pathname, mode_t mode) {
  return ENOSYS;
}

int _real_mmap(void** addr, size_t length, int prot, int flags, int fd,
               off_t offset) {
  return REAL(mmap)(addr, length, prot, flags, fd, offset);
}

int _real_munmap(void* addr, size_t length) {
  return REAL(munmap)(addr, length);
}

int _real_open(const char* pathname, int oflag, mode_t cmode, int* newfd) {
  return REAL(open)(pathname, oflag, cmode, newfd);
}

int _real_open_resource(const char* file, int* fd) {
  return ENOSYS;
}

int _real_read(int fd, void *buf, size_t count, size_t *nread) {
  return REAL(read)(fd, buf, count, nread);
}

int _real_rmdir(const char* pathname) {
  return ENOSYS;
}

int _real_write(int fd, const void *buf, size_t count, size_t *nwrote) {
  return REAL(write)(fd, buf, count, nwrote);
}

void kernel_wrap_init() {
  static bool wrapped = false;

  if (!wrapped) {
    wrapped = true;
    DO_WRAP(fdio, close);
    DO_WRAP(fdio, dup);
    DO_WRAP(fdio, dup2);
    DO_WRAP(fdio, fstat);
    DO_WRAP(fdio, getdents);
    DO_WRAP(fdio, read);
    DO_WRAP(fdio, seek);
    DO_WRAP(fdio, write);
    DO_WRAP(filename, open);
    DO_WRAP(filename, stat);
    DO_WRAP(memory, mmap);
    DO_WRAP(memory, munmap);
  }
}

EXTERN_C_END

#endif  // defined(__native_client__) && !defined(__GLIBC__)
<|endoftext|>


<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "batterywidget.h"
#include "batteryimage.h"
#include "batterydbusinterface.h"
#include "dcpbattery.h"
#include "slidercontainer.h"
#include "timecontainer.h"

#include <QGraphicsLinearLayout>
#include <QDebug>

#include <DuiButton>
#include <DuiContainer>
#include <DuiGridLayoutPolicy>
#include <DuiLayout>
#include <DuiLinearLayoutPolicy>

#define DEBUG
#include "../debug.h"
/*
TODO list:
1) what is the correct interval for updating the battery image when charging? Is there a difference between
   USB and normal charging?

*/

BatteryWidget::BatteryWidget (QGraphicsWidget *parent) :
        DcpWidget (parent),
        batteryIf (NULL),
        batteryImage (NULL),
        PSMButton (NULL),
        sliderContainer (NULL),
        standByTimeContainer (NULL),
        talkTimeContainer (NULL)
{
    SYS_DEBUG ("Starting in %p", this);
    /*
     * One can assume, that when the applet is started the power save mode is
     * not active. This way we show a value that makes sense even if the DBus
     * interface to the sysuid is not usable.
     */
    PSMButtonToggle = false;
    initWidget();
}

BatteryWidget::~BatteryWidget ()
{
    SYS_DEBUG ("Destroying %p", this);
    if (batteryIf) {
        delete batteryIf;
        batteryIf = NULL;
    }
}

bool BatteryWidget::back()
{
    return true; // back is handled by main window by default
}

void BatteryWidget::initWidget()
{
    SYS_DEBUG ("Start");
    // proxy for dbus interface on remote object
    batteryIf = new BatteryDBusInterface();

    // battery image
    batteryImage = new BatteryImage ();

    // talkTimeContainer
    //% "Estimated talk time:"
    talkTimeContainer = new TimeContainer (
            qtTrId ("qtn_ener_tt"), batteryImage);

    // standByTimeContainer
    //% "Estimated stand-by time:"
    standByTimeContainer = new TimeContainer (
            qtTrId ("qtn_ener_st"), new DuiImageWidget ());
                                  //"qgn_ener_standby" ^

    // PSMButton
    PSMButton = new DuiButton();
    connect (PSMButton, SIGNAL(released()),
            this, SLOT(PSMButtonReleased()));

    // sliderContainer
    sliderContainer = new SliderContainer();

    connect (sliderContainer, SIGNAL(PSMAutoToggled(bool)),
             batteryIf, SLOT(setPSMAutoValue(bool)));
    connect (sliderContainer, SIGNAL(PSMThresholdValueChanged(QString)),
             batteryIf, SLOT(setPSMThresholdValue(QString)));

    // mainContainer
    DuiLayout *orientationLayout = new DuiLayout();

    DuiGridLayoutPolicy *landscapeLayoutPolicy = new DuiGridLayoutPolicy(orientationLayout);
    landscapeLayoutPolicy->addItem(talkTimeContainer, 0, 0);
    landscapeLayoutPolicy->addItem(standByTimeContainer, 0, 1);
    landscapeLayoutPolicy->addItem(PSMButton, 1, 0, 1, 2);
    landscapeLayoutPolicy->addItem(sliderContainer, 2, 0, 1, 2);
    landscapeLayoutPolicy->setSpacing (10);
    orientationLayout->setLandscapePolicy(landscapeLayoutPolicy);

    DuiLinearLayoutPolicy *portraitLayoutPolicy = new DuiLinearLayoutPolicy(orientationLayout, Qt::Vertical);
    portraitLayoutPolicy->addItem(talkTimeContainer, Qt::AlignLeft);
    portraitLayoutPolicy->addItem(standByTimeContainer, Qt::AlignLeft);
    portraitLayoutPolicy->addItem(PSMButton, Qt::AlignCenter);
    portraitLayoutPolicy->addItem (sliderContainer, Qt::AlignLeft);
    portraitLayoutPolicy->setSpacing(10);
    orientationLayout->setPortraitPolicy(portraitLayoutPolicy);

    DuiContainer *mainContainer = new DuiContainer();
    mainContainer->setHeaderVisible(false);
    mainContainer->centralWidget()->setLayout(orientationLayout);

    // connect the value receive signals
    connect (batteryIf, SIGNAL(remainingTimeValuesReceived(QStringList)),
             this, SLOT(remainingTimeValuesReceived(QStringList)));
    connect (batteryIf, SIGNAL(batteryCharging(int)),
             batteryImage, SLOT(startCharging(int)));
    connect (batteryIf, SIGNAL(batteryNotCharging()),
             batteryImage, SLOT(stopCharging()));
    connect (batteryIf, SIGNAL(batteryNotCharging()),
             batteryIf, SLOT(batteryBarValueRequired()));
    connect (batteryIf, SIGNAL(batteryBarValueReceived(int)),
             batteryImage, SLOT(updateBatteryLevel(int)));
    connect (batteryIf, SIGNAL(PSMValueReceived(bool)),
             this, SLOT(updatePSMButton(bool)));
    connect (batteryIf, SIGNAL(PSMAutoValueReceived(bool)),
             sliderContainer, SLOT(initPSMAutoButton(bool)));
    connect (batteryIf, SIGNAL(PSMAutoDisabled()),
             sliderContainer, SLOT(PSMAutoDisabled()));
    connect (batteryIf, SIGNAL(PSMThresholdValuesReceived(QStringList)),
             sliderContainer, SLOT(initSlider(QStringList)));
    connect (batteryIf, SIGNAL(PSMThresholdValuesReceived(QStringList)),
             batteryIf, SLOT(PSMThresholdValueRequired()));
    connect (batteryIf, SIGNAL(PSMThresholdValueReceived(QString)),
             sliderContainer, SLOT(updateSlider(QString)));

    // send value requests over dbus
    batteryIf->remainingTimeValuesRequired();
    batteryIf->batteryBarValueRequired();
    batteryIf->batteryChargingStateRequired();
    batteryIf->PSMValueRequired();
    batteryIf->PSMAutoValueRequired();
    batteryIf->PSMThresholdValuesRequired();

    // mainLayout
    QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->addItem(mainContainer);
    this->setLayout(mainLayout);

    SYS_DEBUG ("End");
}

/*!
 * This function is called when the user clicked on the 'power save mode' button
 * that activates and disactivates the power saving mode. The function will call
 * the battery interface, but the UI will be changed only when the sysuid
 * reports the change.
 */
void
BatteryWidget::PSMButtonReleased ()
{
    batteryIf->setPSMValue (!PSMButtonToggle);
}

void
BatteryWidget::updatePSMButton (
        bool toggle)
{
    PSMButtonToggle = toggle;

    SYS_DEBUG ("PSMButtonToggle now is %s", PSMButtonToggle ? "on" : "off");
    if (toggle) {
        //% "Deactivate power save now"
        PSMButton->setText (qtTrId ("qtn_ener_dps"));
    } else {
        //% "Activate power save now"
        PSMButton->setText (qtTrId ("qtn_ener_aps"));
    }
}

void BatteryWidget::remainingTimeValuesReceived(const QStringList &timeValues)
{
    qDebug() << "BatteryWidget::remainingTimeValuesReceived(" << timeValues.at(0) << ", " << timeValues.at(1) << ")";
    talkTimeContainer->updateTimeLabel(timeValues.at(0));
    standByTimeContainer->updateTimeLabel(timeValues.at(1));
}

void
BatteryWidget::retranslateUi ()
{
    // This call will reload the translated text on PSButton
    updatePSMButton (PSMButtonToggle);

    // This call will retranslate the label (infoText)
    sliderContainer->retranslate ();

    talkTimeContainer->setText(qtTrId ("qtn_ener_tt"));
    standByTimeContainer->setText (qtTrId ("qtn_ener_st"));

    // This call will reload timelabels on timercontainers
    batteryIf->remainingTimeValuesRequired();
}
<commit_msg>Code-reformat<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "batterywidget.h"
#include "batteryimage.h"
#include "batterydbusinterface.h"
#include "dcpbattery.h"
#include "slidercontainer.h"
#include "timecontainer.h"

#include <QGraphicsLinearLayout>

#include <DuiButton>
#include <DuiContainer>
#include <DuiGridLayoutPolicy>
#include <DuiLayout>
#include <DuiLinearLayoutPolicy>

#define DEBUG
#include "../debug.h"

/*
TODO list:
1) what is the correct interval for updating the battery image when charging? Is there a difference between
   USB and normal charging?

*/

BatteryWidget::BatteryWidget (QGraphicsWidget *parent) :
        DcpWidget (parent),
        batteryIf (NULL),
        batteryImage (NULL),
        PSMButton (NULL),
        sliderContainer (NULL),
        standByTimeContainer (NULL),
        talkTimeContainer (NULL)
{
    SYS_DEBUG ("Starting in %p", this);
    /*
     * One can assume, that when the applet is started the power save mode is
     * not active. This way we show a value that makes sense even if the DBus
     * interface to the sysuid is not usable.
     */
    PSMButtonToggle = false;
    initWidget();
}

BatteryWidget::~BatteryWidget ()
{
    SYS_DEBUG ("Destroying %p", this);
    if (batteryIf) {
        delete batteryIf;
        batteryIf = NULL;
    }
}

bool BatteryWidget::back ()
{
    return true; // back is handled by main window by default
}

void BatteryWidget::initWidget ()
{
    SYS_DEBUG ("Start");
    // proxy for dbus interface on remote object
    batteryIf = new BatteryDBusInterface;

    // battery image
    batteryImage = new BatteryImage;

    // talkTimeContainer
    //% "Estimated talk time:"
    talkTimeContainer = new TimeContainer (
            qtTrId ("qtn_ener_tt"), batteryImage);

    // standByTimeContainer
    //% "Estimated stand-by time:"
    standByTimeContainer = new TimeContainer (
            qtTrId ("qtn_ener_st"), new DuiImageWidget);
                                  //"qgn_ener_standby" ^

    // PSMButton
    PSMButton = new DuiButton ;
    connect (PSMButton, SIGNAL (released ()),
             this, SLOT (PSMButtonReleased ()));

    // sliderContainer
    sliderContainer = new SliderContainer;

    connect (sliderContainer, SIGNAL (PSMAutoToggled (bool)),
             batteryIf, SLOT (setPSMAutoValue (bool)));
    connect (sliderContainer, SIGNAL (PSMThresholdValueChanged (QString)),
             batteryIf, SLOT (setPSMThresholdValue (QString)));

    // mainContainer
    DuiLayout *orientationLayout = new DuiLayout;

    DuiGridLayoutPolicy *landscapeLayoutPolicy =
        new DuiGridLayoutPolicy (orientationLayout);
    landscapeLayoutPolicy->addItem (talkTimeContainer, 0, 0);
    landscapeLayoutPolicy->addItem (standByTimeContainer, 0, 1);
    landscapeLayoutPolicy->addItem (PSMButton, 1, 0, 1, 2);
    landscapeLayoutPolicy->addItem (sliderContainer, 2, 0, 1, 2);
    landscapeLayoutPolicy->setSpacing (10);
    orientationLayout->setLandscapePolicy (landscapeLayoutPolicy);

    DuiLinearLayoutPolicy *portraitLayoutPolicy =
        new DuiLinearLayoutPolicy (orientationLayout, Qt::Vertical);
    portraitLayoutPolicy->addItem (talkTimeContainer, Qt::AlignLeft);
    portraitLayoutPolicy->addItem (standByTimeContainer, Qt::AlignLeft);
    portraitLayoutPolicy->addItem (PSMButton, Qt::AlignCenter);
    portraitLayoutPolicy->addItem (sliderContainer, Qt::AlignLeft);
    portraitLayoutPolicy->setSpacing (10);
    orientationLayout->setPortraitPolicy (portraitLayoutPolicy);

    DuiContainer *mainContainer = new DuiContainer;
    mainContainer->setHeaderVisible (false);
    mainContainer->centralWidget ()->setLayout (orientationLayout);

    // connect the value receive signals
    connect (batteryIf, SIGNAL (remainingTimeValuesReceived (QStringList)),
             this, SLOT (remainingTimeValuesReceived (QStringList)));
    connect (batteryIf, SIGNAL (batteryCharging (int)),
             batteryImage, SLOT (startCharging (int)));
    connect (batteryIf, SIGNAL (batteryNotCharging ()),
             batteryImage, SLOT (stopCharging ()));
    connect (batteryIf, SIGNAL (batteryNotCharging ()),
             batteryIf, SLOT (batteryBarValueRequired ()));
    connect (batteryIf, SIGNAL (batteryBarValueReceived (int)),
             batteryImage, SLOT (updateBatteryLevel (int)));
    connect (batteryIf, SIGNAL (PSMValueReceived (bool)),
             this, SLOT (updatePSMButton (bool)));
    connect (batteryIf, SIGNAL (PSMAutoValueReceived (bool)),
             sliderContainer, SLOT (initPSMAutoButton (bool)));
    connect (batteryIf, SIGNAL (PSMAutoDisabled ()),
             sliderContainer, SLOT (PSMAutoDisabled ()));
    connect (batteryIf, SIGNAL (PSMThresholdValuesReceived (QStringList)),
             sliderContainer, SLOT (initSlider (QStringList)));
    connect (batteryIf, SIGNAL (PSMThresholdValuesReceived (QStringList)),
             batteryIf, SLOT (PSMThresholdValueRequired ()));
    connect (batteryIf, SIGNAL (PSMThresholdValueReceived (QString)),
             sliderContainer, SLOT (updateSlider (QString)));

    // send value requests over dbus
    batteryIf->remainingTimeValuesRequired ();
    batteryIf->batteryBarValueRequired ();
    batteryIf->batteryChargingStateRequired ();
    batteryIf->PSMValueRequired ();
    batteryIf->PSMAutoValueRequired ();
    batteryIf->PSMThresholdValuesRequired ();

    // mainLayout
    QGraphicsLinearLayout *mainLayout =
        new QGraphicsLinearLayout (Qt::Vertical);
    mainLayout->setContentsMargins (0, 0, 0, 0);
    mainLayout->addItem (mainContainer);
    this->setLayout (mainLayout);

    SYS_DEBUG ("End");
}

/*!
 * This function is called when the user clicked on the 'power save mode' button
 * that activates and disactivates the power saving mode. The function will call
 * the battery interface, but the UI will be changed only when the sysuid
 * reports the change.
 */
void
BatteryWidget::PSMButtonReleased ()
{
    batteryIf->setPSMValue (!PSMButtonToggle);
}

void
BatteryWidget::updatePSMButton (
        bool toggle)
{
    PSMButtonToggle = toggle;

    SYS_DEBUG ("PSMButtonToggle now is %s", PSMButtonToggle ? "on" : "off");
    if (toggle) {
        //% "Deactivate power save now"
        PSMButton->setText (qtTrId ("qtn_ener_dps"));
    } else {
        //% "Activate power save now"
        PSMButton->setText (qtTrId ("qtn_ener_aps"));
    }
}

void BatteryWidget::remainingTimeValuesReceived(const QStringList &timeValues)
{
    SYS_DEBUG ("timevalues = %s, %s",
               SYS_STR (timeValues.at (0)),
               SYS_STR (timeValues.at (1)));

    talkTimeContainer->updateTimeLabel (timeValues.at (0));
    standByTimeContainer->updateTimeLabel (timeValues.at (1));
}

void
BatteryWidget::retranslateUi ()
{
    // This call will reload the translated text on PSButton
    updatePSMButton (PSMButtonToggle);

    // This call will retranslate the label (infoText)
    sliderContainer->retranslate ();

    talkTimeContainer->setText(qtTrId ("qtn_ener_tt"));
    standByTimeContainer->setText (qtTrId ("qtn_ener_st"));

    // This call will reload timelabels on timercontainers
    batteryIf->remainingTimeValuesRequired ();
}

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2017, Nagoya University
 *  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 Autoware 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 HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "pacmod_interface.h"

namespace pacmod
{
// Constructor
PacmodInterface::PacmodInterface() :
    private_nh_("~"),
    control_mode_(false)
{
  initForROS();
}

// Destructor
PacmodInterface::~PacmodInterface()
{
}

void PacmodInterface::initForROS()
{
  // ros parameter settings
  private_nh_.param<double>("acceleration_limit", acceleration_limit_, 3.0);
  private_nh_.param<double>("deceleration_limit", deceleration_limit_, 3.0);
  private_nh_.param<double>("max_curvature_rate", max_curvature_rate_, 0.75);

  // setup subscriber
  twist_cmd_sub_    = nh_.subscribe("twist_cmd", 10, &PacmodInterface::callbackFromTwistCmd, this);
  control_mode_sub_ = nh_.subscribe("/as/control_mode", 10, &PacmodInterface::callbackFromControlMode, this);
  speed_sub_        = nh_.subscribe("/vehicle/steering_report", 10, &PacmodInterface::callbackFromTwistCmd, this);

  // setup publisher
  steer_mode_pub_    = nh_.advertise<module_comm_msgs::SteerMode>("/as/arbitrated_steering_commands", 10);
  speed_mode_pub_    = nh_.advertise<module_comm_msgs::SpeedMode>("/as/arbitrated_speed_commands", 10);
  current_twist_pub_ = nh_.advertise<geometry_msgs::TwistStamped>("as_current_twist", 10);
}

void PacmodInterface::run()
{
  ros::spin();
}

void PacmodInterface::callbackFromTwistCmd(const geometry_msgs::TwistStampedConstPtr &msg)
{
  int mode;
  if (control_mode_)
  {
    mode = 1;
  }
  else
  {
    mode = 0;
  }

  module_comm_msgs::SpeedMode speed_mode;
  speed_mode.header = msg->header;
  speed_mode.mode = mode;
  speed_mode.speed = msg->twist.linear.x;
  speed_mode.acceleration_limit = 3.0;
  speed_mode.deceleration_limit = 3.0;

  module_comm_msgs::SteerMode steer_mode;
  steer_mode.header = msg->header;
  steer_mode.mode = mode;
  double curvature = msg->twist.angular.z / msg->twist.linear.x;
  steer_mode.curvature = msg->twist.linear.x <= 0 ? 0 : curvature;
  steer_mode.max_curvature_rate = 0.75;

  std::cout << "mode: "  << mode << std::endl;
  std::cout << "speed: " << speed_mode.speed << std::endl;
  std::cout << "steer: " << steer_mode.curvature << std::endl;

  speed_mode_pub_.publish(speed_mode);
  steer_mode_pub_.publish(steer_mode);
}

void PacmodInterface::callbackFromControlMode(const std_msgs::BoolConstPtr &msg)
{
  control_mode_ = msg->data;
}

void PacmodInterface::callbackFromSteeringReport(const dbw_mkz_msgs::SteeringReportConstPtr &msg)
{
  geometry_msgs::TwistStamped ts;
  std_msgs::Header header;
  header.stamp = ros::Time::now();
  ts.header = header;
  ts.twist.linear.x = msg->speed; // [m/sec]
  // Can we get angular velocity?

  current_twist_pub_.publish(ts);
}

}  // pacmod
<commit_msg>Use correct callback function<commit_after>/*
 *  Copyright (c) 2017, Nagoya University
 *  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 Autoware 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 HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 *  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "pacmod_interface.h"

namespace pacmod
{
// Constructor
PacmodInterface::PacmodInterface() :
    private_nh_("~"),
    control_mode_(false)
{
  initForROS();
}

// Destructor
PacmodInterface::~PacmodInterface()
{
}

void PacmodInterface::initForROS()
{
  // ros parameter settings
  private_nh_.param<double>("acceleration_limit", acceleration_limit_, 3.0);
  private_nh_.param<double>("deceleration_limit", deceleration_limit_, 3.0);
  private_nh_.param<double>("max_curvature_rate", max_curvature_rate_, 0.75);

  // setup subscriber
  twist_cmd_sub_    = nh_.subscribe("twist_cmd", 10, &PacmodInterface::callbackFromTwistCmd, this);
  control_mode_sub_ = nh_.subscribe("/as/control_mode", 10, &PacmodInterface::callbackFromControlMode, this);
  speed_sub_        = nh_.subscribe("/vehicle/steering_report", 10, &PacmodInterface::callbackFromSteeringReport, this);

  // setup publisher
  steer_mode_pub_    = nh_.advertise<module_comm_msgs::SteerMode>("/as/arbitrated_steering_commands", 10);
  speed_mode_pub_    = nh_.advertise<module_comm_msgs::SpeedMode>("/as/arbitrated_speed_commands", 10);
  current_twist_pub_ = nh_.advertise<geometry_msgs::TwistStamped>("as_current_twist", 10);
}

void PacmodInterface::run()
{
  ros::spin();
}

void PacmodInterface::callbackFromTwistCmd(const geometry_msgs::TwistStampedConstPtr &msg)
{
  int mode;
  if (control_mode_)
  {
    mode = 1;
  }
  else
  {
    mode = 0;
  }

  module_comm_msgs::SpeedMode speed_mode;
  speed_mode.header = msg->header;
  speed_mode.mode = mode;
  speed_mode.speed = msg->twist.linear.x;
  speed_mode.acceleration_limit = 3.0;
  speed_mode.deceleration_limit = 3.0;

  module_comm_msgs::SteerMode steer_mode;
  steer_mode.header = msg->header;
  steer_mode.mode = mode;
  double curvature = msg->twist.angular.z / msg->twist.linear.x;
  steer_mode.curvature = msg->twist.linear.x <= 0 ? 0 : curvature;
  steer_mode.max_curvature_rate = 0.75;

  std::cout << "mode: "  << mode << std::endl;
  std::cout << "speed: " << speed_mode.speed << std::endl;
  std::cout << "steer: " << steer_mode.curvature << std::endl;

  speed_mode_pub_.publish(speed_mode);
  steer_mode_pub_.publish(steer_mode);
}

void PacmodInterface::callbackFromControlMode(const std_msgs::BoolConstPtr &msg)
{
  control_mode_ = msg->data;
}

void PacmodInterface::callbackFromSteeringReport(const dbw_mkz_msgs::SteeringReportConstPtr &msg)
{
  geometry_msgs::TwistStamped ts;
  std_msgs::Header header;
  header.stamp = ros::Time::now();
  ts.header = header;
  ts.twist.linear.x = msg->speed; // [m/sec]
  // Can we get angular velocity?

  current_twist_pub_.publish(ts);
}

}  // pacmod
<|endoftext|>