<commit_before>#ifndef _EIGEN3_HDF5_HPP
#define _EIGEN3_HDF5_HPP

#include <array>
#include <cassert>
#include <complex>
#include <cstddef>
#include <stdexcept>
#include <string>
#include <vector>

//#include <hdf5.h>
#include <H5Cpp.h>
#include <Eigen/Dense>

namespace EigenHDF5
{

template <typename T>
struct DatatypeSpecialization;

// floating-point types

template <>
struct DatatypeSpecialization<float>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_FLOAT;
        }
};

template <>
struct DatatypeSpecialization<double>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_DOUBLE;
        }
};

template <>
struct DatatypeSpecialization<long double>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_LDOUBLE;
        }
};

// integer types

template <>
struct DatatypeSpecialization<int>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_INT;
        }
};

template <>
struct DatatypeSpecialization<unsigned int>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_UINT;
        }
};

// complex types
//
// inspired by http://www.mail-archive.com/hdf-forum@hdfgroup.org/msg00759.html

template <typename T>
class ComplexH5Type : public H5::CompType
{
public:
    ComplexH5Type (void)
        : CompType(sizeof(std::complex<T>))
        {
            const H5::DataType * const datatype = DatatypeSpecialization<T>::get();
            assert(datatype->getSize() == sizeof(T));
            // If we call the members "r" and "i", h5py interprets the
            // structure correctly as complex numbers.
            this->insertMember(std::string("r"), 0, *datatype);
            this->insertMember(std::string("i"), sizeof(T), *datatype);
            this->pack();
        }

    static const ComplexH5Type<T> * get_singleton (void)
        {
            // NOTE: constructing this could be a race condition
            static ComplexH5Type<T> singleton;
            return &singleton;
        }
};

template <typename T>
struct DatatypeSpecialization<std::complex<T> >
{
    static inline const H5::DataType * get (void)
        {
            return ComplexH5Type<T>::get_singleton();
        }
};

// see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html

template <typename Derived>
void save (H5::CommonFG &h5group, const std::string &name, const Eigen::EigenBase<Derived> &mat, const H5::DSetCreatPropList &plist=H5::DSetCreatPropList::DEFAULT)
{
    typedef typename Derived::Scalar Scalar;
    const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat);
    const std::array<hsize_t, 2> dimensions = { {
        static_cast<hsize_t>(mat.rows()),
        static_cast<hsize_t>(mat.cols())
    } };
    const H5::DataSpace dataspace(dimensions.size(), dimensions.data());
    const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();
    H5::DataSet dataset = h5group.createDataSet(name, *datatype, dataspace, plist);
    dataset.write(row_major_mat.data(), *datatype);
}

template <typename Derived>
void load (const H5::CommonFG &h5group, const std::string &name, const Eigen::DenseBase<Derived> &mat)
{
    typedef typename Derived::Scalar Scalar;
    const H5::DataSet dataset = h5group.openDataSet(name);
    const H5::DataSpace dataspace = dataset.getSpace();
    const std::size_t ndims = dataspace.getSimpleExtentNdims();
    assert(ndims > 0);
    std::array<hsize_t, 2> dimensions;
    dimensions[1] = 1; // in case it's 1D
    if (ndims > dimensions.size()) {
        throw std::runtime_error("HDF5 array has too many dimensions.");
    }
    dataspace.getSimpleExtentDims(dimensions.data());
    const hsize_t rows = dimensions[0], cols = dimensions[1];
    std::vector<Scalar> data(rows * cols);
    const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();
    dataset.read(data.data(), *datatype, dataspace);
    // see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
    Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat);
    mat_.derived().resize(rows, cols);
    mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols);
}

} // namespace EigenHDF5

#endif
<commit_msg>work for long integer types<commit_after>#ifndef _EIGEN3_HDF5_HPP
#define _EIGEN3_HDF5_HPP

#include <array>
#include <cassert>
#include <complex>
#include <cstddef>
#include <stdexcept>
#include <string>
#include <vector>

//#include <hdf5.h>
#include <H5Cpp.h>
#include <Eigen/Dense>

namespace EigenHDF5
{

template <typename T>
struct DatatypeSpecialization;

// floating-point types

template <>
struct DatatypeSpecialization<float>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_FLOAT;
        }
};

template <>
struct DatatypeSpecialization<double>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_DOUBLE;
        }
};

template <>
struct DatatypeSpecialization<long double>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_LDOUBLE;
        }
};

// integer types

template <>
struct DatatypeSpecialization<int>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_INT;
        }
};

template <>
struct DatatypeSpecialization<unsigned int>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_UINT;
        }
};

template <>
struct DatatypeSpecialization<long>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_LONG;
        }
};

template <>
struct DatatypeSpecialization<unsigned long>
{
    static inline const H5::DataType * get (void)
        {
            return &H5::PredType::NATIVE_ULONG;
        }
};

// complex types
//
// inspired by http://www.mail-archive.com/hdf-forum@hdfgroup.org/msg00759.html

template <typename T>
class ComplexH5Type : public H5::CompType
{
public:
    ComplexH5Type (void)
        : CompType(sizeof(std::complex<T>))
        {
            const H5::DataType * const datatype = DatatypeSpecialization<T>::get();
            assert(datatype->getSize() == sizeof(T));
            // If we call the members "r" and "i", h5py interprets the
            // structure correctly as complex numbers.
            this->insertMember(std::string("r"), 0, *datatype);
            this->insertMember(std::string("i"), sizeof(T), *datatype);
            this->pack();
        }

    static const ComplexH5Type<T> * get_singleton (void)
        {
            // NOTE: constructing this could be a race condition
            static ComplexH5Type<T> singleton;
            return &singleton;
        }
};

template <typename T>
struct DatatypeSpecialization<std::complex<T> >
{
    static inline const H5::DataType * get (void)
        {
            return ComplexH5Type<T>::get_singleton();
        }
};

// see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html

template <typename Derived>
void save (H5::CommonFG &h5group, const std::string &name, const Eigen::EigenBase<Derived> &mat, const H5::DSetCreatPropList &plist=H5::DSetCreatPropList::DEFAULT)
{
    typedef typename Derived::Scalar Scalar;
    const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat);
    const std::array<hsize_t, 2> dimensions = { {
        static_cast<hsize_t>(mat.rows()),
        static_cast<hsize_t>(mat.cols())
    } };
    const H5::DataSpace dataspace(dimensions.size(), dimensions.data());
    const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();
    H5::DataSet dataset = h5group.createDataSet(name, *datatype, dataspace, plist);
    dataset.write(row_major_mat.data(), *datatype);
}

template <typename Derived>
void load (const H5::CommonFG &h5group, const std::string &name, const Eigen::DenseBase<Derived> &mat)
{
    typedef typename Derived::Scalar Scalar;
    const H5::DataSet dataset = h5group.openDataSet(name);
    const H5::DataSpace dataspace = dataset.getSpace();
    const std::size_t ndims = dataspace.getSimpleExtentNdims();
    assert(ndims > 0);
    std::array<hsize_t, 2> dimensions;
    dimensions[1] = 1; // in case it's 1D
    if (ndims > dimensions.size()) {
        throw std::runtime_error("HDF5 array has too many dimensions.");
    }
    dataspace.getSimpleExtentDims(dimensions.data());
    const hsize_t rows = dimensions[0], cols = dimensions[1];
    std::vector<Scalar> data(rows * cols);
    const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();
    dataset.read(data.data(), *datatype, dataspace);
    // see http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
    Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat);
    mat_.derived().resize(rows, cols);
    mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols);
}

} // namespace EigenHDF5

#endif
<|endoftext|>


<commit_before>#include "rapid_display/display.h"

#include "actionlib/client/simple_action_client.h"
#include "blinky/FaceAction.h"
#include "ros/ros.h"

#include "rapid_ros/action_client.h"

using ros::Duration;

namespace rapid {
namespace display {
Blinky::Blinky(rapid_ros::ActionClientInterface<blinky::FaceAction>* client)
    : client_(client), server_wait_time_(5) {}

Blinky::~Blinky() {
  if (client_ != NULL) {
    delete client_;
  } else {
    ROS_ERROR("Pointer to ActionClient was null!");
  }
}

bool Blinky::ShowDefault() {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  if (!WaitForServer(server_wait_time_)) {
    ROS_ERROR("Timed out waiting for the Blinky server.");
    return false;
  }
  blinky::FaceGoal goal;
  goal.display_type = goal.DEFAULT;
  client_->sendGoal(goal);
  if (!client_->waitForResult(Duration(server_wait_time_))) {
    ROS_ERROR("Timed out waiting for Blinky result.");
    return false;
  }
  return true;
}

bool Blinky::ShowMessage(const std::string& h1_text,
                         const std::string& h2_text) {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  if (!WaitForServer(server_wait_time_)) {
    ROS_ERROR("Timed out waiting for the Blinky server.");
    return false;
  }
  blinky::FaceGoal goal;
  goal.display_type = goal.DISPLAY_MESSAGE;
  goal.h1_text = h1_text;
  goal.h2_text = h2_text;
  client_->sendGoal(goal);
  if (!client_->waitForResult(Duration(server_wait_time_))) {
    ROS_ERROR("Timed out waiting for Blinky result.");
    return false;
  }
  return true;
}

bool Blinky::AskMultipleChoice(const std::string& question,
                               const std::vector<std::string>& choices,
                               std::string* choice) {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  if (!WaitForServer(server_wait_time_)) {
    ROS_ERROR("Timed out waiting for the Blinky server.");
    return false;
  }
  blinky::FaceGoal goal;
  goal.display_type = goal.ASK_CHOICE;
  goal.question = question;
  goal.choices = choices;
  client_->sendGoal(goal);
  blinky::FaceResultConstPtr result = client_->getResult();
  *choice = result->choice;
  return true;
}

bool Blinky::WaitForServer(const int seconds) {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  Duration duration(seconds);
  return client_->waitForServer(duration);
}
}  // namespace display
}  // namespace rapid
<commit_msg>Actually wait for the result.<commit_after>#include "rapid_display/display.h"

#include "actionlib/client/simple_action_client.h"
#include "blinky/FaceAction.h"
#include "ros/ros.h"

#include "rapid_ros/action_client.h"

using ros::Duration;

namespace rapid {
namespace display {
Blinky::Blinky(rapid_ros::ActionClientInterface<blinky::FaceAction>* client)
    : client_(client), server_wait_time_(5) {}

Blinky::~Blinky() {
  if (client_ != NULL) {
    delete client_;
  } else {
    ROS_ERROR("Pointer to ActionClient was null!");
  }
}

bool Blinky::ShowDefault() {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  if (!WaitForServer(server_wait_time_)) {
    ROS_ERROR("Timed out waiting for the Blinky server.");
    return false;
  }
  blinky::FaceGoal goal;
  goal.display_type = goal.DEFAULT;
  client_->sendGoal(goal);
  if (!client_->waitForResult(Duration(server_wait_time_))) {
    ROS_ERROR("Timed out waiting for Blinky result.");
    return false;
  }
  return true;
}

bool Blinky::ShowMessage(const std::string& h1_text,
                         const std::string& h2_text) {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  if (!WaitForServer(server_wait_time_)) {
    ROS_ERROR("Timed out waiting for the Blinky server.");
    return false;
  }
  blinky::FaceGoal goal;
  goal.display_type = goal.DISPLAY_MESSAGE;
  goal.h1_text = h1_text;
  goal.h2_text = h2_text;
  client_->sendGoal(goal);
  if (!client_->waitForResult(Duration(server_wait_time_))) {
    ROS_ERROR("Timed out waiting for Blinky result.");
    return false;
  }
  return true;
}

bool Blinky::AskMultipleChoice(const std::string& question,
                               const std::vector<std::string>& choices,
                               std::string* choice) {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  if (!WaitForServer(server_wait_time_)) {
    ROS_ERROR("Timed out waiting for the Blinky server.");
    return false;
  }
  blinky::FaceGoal goal;
  goal.display_type = goal.ASK_CHOICE;
  goal.question = question;
  goal.choices = choices;
  client_->sendGoal(goal);
  client_->waitForResult();
  blinky::FaceResultConstPtr result = client_->getResult();
  *choice = result->choice;
  return true;
}

bool Blinky::WaitForServer(const int seconds) {
  if (client_ == NULL) {
    ROS_ERROR("Pointer to ActionClient was null!");
    return false;
  }
  Duration duration(seconds);
  return client_->waitForServer(duration);
}
}  // namespace display
}  // namespace rapid
<|endoftext|>


<commit_before>/****************************/
/* readschematicnetlist.cpp */
/****************************/

/* Read a nelist type Eeschema or OrcadPCB2 and build the component list
 * Manages the lines like :
 * ( XXXXXX VALEUR|(pin1,pin2,...=newalim) ID VALEUR
 */

#include "fctsys.h"
#include "wxstruct.h"
#include "common.h"
#include "confirm.h"
#include "kicad_string.h"
#include "macros.h"

#include "cvpcb.h"
#include "protos.h"
#include "cvstruct.h"

#define SEPARATEUR '|'  /* caractere separateur dans netliste */

/* routines locales : */

static int ReadPinConnection( FILE* f, COMPONENT* CurrentCmp );

/* Tri la liste des composants par ordre alphabetique et met a jour le nouveau
 * chainage avant/arriere retourne un pointeur sur le 1er element de la liste */

#define BUFFER_CHAR_SIZE 1024   // Size of buffers used to  store netlist data

/**
 * Function ReadSchematicNetlist
 * Read a Eeschema (or OrcadPCB) netlist
 * like:
 * # EESchema Netlist Version 1.1 created  15/5/2008-12:09:21
 * (
 *  ( /32568D1E $noname  JP1 CONN_8X2 {Lib=CONN_8X2}
 *   (    1 GND )
 *   (    2 /REF10 )
 *   (    3 GND )
 *   (    4 /REF11 )
 *   (    5 GND )
 *   (    6 /REF7 )
 *   (    7 GND )
 *   (    8 /REF9 )
 *   (    9 GND )
 *   (   10 /REF6 )
 *   (   11 GND )
 *   (   12 /REF8 )
 *   (   13 GND )
 *   (   14 /REF4 )
 *   (   15 GND )
 *   (   16 /REF5 )
 *  )
 *  ( /325679C1 $noname  RR1 9x1K {Lib=RR9}
 *   (    1 VCC )
 *   (    2 /REF5 )
 *   (    3 /REF4 )
 *   (    4 /REF8 )
 *   (    5 /REF6 )
 *   (    6 /REF9 )
 *   (    7 /REF7 )
 *   (    8 /REF11 )
 *   (    9 /REF10 )
 *   (   10  ? )
 *  )
 * )
 * *
 * { Allowed footprints by component:
 * $component R5
 * R?
 * SM0603
 * SM0805
 * $endlist
 * $component C2
 * SM*
 * C?
 * C1-1
 * $endlist
 * $endfootprintlist
 * }
 */
int WinEDA_CvpcbFrame::ReadSchematicNetlist()
{
    char       alim[1024];
    int        i, k, l;
    char*      LibName;
    char       Line[BUFFER_CHAR_SIZE + 1];
    wxString   component_reference;  /* buffer for component reference (U1, R4...) */
    wxString   schematic_timestamp;  /* buffer for component time stamp */
    wxString   footprint_name;       /* buffer for component footprint field */
    wxString   component_value;      /* buffer for component values (470K, 22nF ...) */
    char*      ptchar;
    COMPONENT* Cmp;
    FILE*      source;

    m_modified = false;
    m_isEESchemaNetlist = false;

    /* Clear components buffer */
    if( !m_components.empty() )
    {
        m_components.clear();
    }

    source = wxFopen( m_NetlistFileName.GetFullPath(), wxT( "rt" ) );

    if( source == 0 )
    {
        DisplayError( this,  _( "File <" ) + m_NetlistFileName.GetFullPath() +
                      _( "> not found" )  );
        return -1;
    }

    /* Read the file header (must be  "( { OrCAD PCB" or "({ OrCAD PCB" )
     * or "# EESchema Netliste"
     */
    (void) fgets( Line, BUFFER_CHAR_SIZE, source );
    /* test for netlist type PCB2 */
    i = strnicmp( Line, "( {", 3 );
    if( i != 0 )
        i = strnicmp( Line, "({", 2 );
    if( i != 0 )
    {
        i = strnicmp( Line, "# EESchema", 7 ); /* net type EESchema */
        if( i == 0 )
            m_isEESchemaNetlist = TRUE;
    }

    if( i != 0 )
    {
        wxString msg, Lineconv = CONV_FROM_UTF8( Line );
        msg.Printf( _( "Unknown file format <%s>" ), Lineconv.GetData() );
        DisplayError( this, msg );
        fclose( source );
        return -3;
    }

    SetStatusText( _( "Netlist Format: EESchema" ), 0 );

    /* Read the netlist */
    for( ; ; )
    {
        /* Search the beginning of a component description */

        if( fgets( Line, BUFFER_CHAR_SIZE, source )  == 0 )
            break;

        /* Remove blanks */
        i = 0; while( Line[i] == ' ' )
            i++;

        /* remove empty lines : */
        if( Line[i] < ' ' )
            continue;

        if( strnicmp( &Line[i], "{ Allowed footprints", 20 ) == 0 )
        {
            ReadFootprintFilterList( source );
            continue;
        }

        if( strnicmp( &Line[i], "( ", 2 ) != 0 )
            continue;

        /*******************************/
        /* Component description found */
        /*******************************/
        while( Line[i] != ' ' )
            i++;

        while( Line[i] == ' ' )
            i++;

        /* i points the beginning of the schematic time stamp */

        schematic_timestamp.Empty();
        while( Line[i] != ' ' )
            schematic_timestamp.Append( Line[i++] );

        /* search val/ref.lib */
        while( Line[i] == ' ' )
            i++;

        /* i points the component value */
        LibName = Line + i;

        component_reference.Empty();
        footprint_name.Empty();
        component_value.Empty();
        memset( alim, 0, sizeof(alim) );

        /* Read value */

        ptchar = strstr( &Line[i], " " );  // Search end of value field (space)
        if( ptchar == 0 )
        {
            wxString msg;
            msg.Printf( _( "Netlist error: %s" ), Line );
            DisplayError( this, msg );
            k = 0;
        }
        else
            k = ptchar - Line;

        for( ; i < k; i++ )
        {
            if( Line[i] == SEPARATEUR )
                break;
            footprint_name.Append( Line[i] );
        }

        if( (Line[++i] == '(') && (Line[k - 1] == ')' ) )
        {
            i++; l = 0; while( k - 1 > i )
                alim[l++] = Line[i++];
        }
        else
            i = k;

        /* Search component reference */
        while( Line[i] != ' ' )
            i++;

        /* goto end of value field */
        while( Line[i] == ' ' )
            i++;

        /* goto beginning of  reference */

        /* debut reference trouv */
        for( ; ; i++ )
        {
#if defined(KICAD_GOST)
            if( Line[i] == ' ' )
#else
            if( Line[i] <= ' ' )
#endif
                break;
            component_reference.Append( Line[i] );
        }

        /* Search component value */
        while( Line[i] == ' ' )
            i++;

        /** goto beginning of  value */

        for( ; ; i++ )
        {
#if defined(KICAD_GOST)
            if( (Line[i] == ' ')  || (Line[i] == '\n') )
#else
            if( Line[i] <= ' ' )
#endif
                break;
            component_value.Append( Line[i] );
        }

        /* Store info for this component */
        Cmp = new COMPONENT();
        Cmp->m_Reference = component_reference;
        Cmp->m_Value     = component_value;
        m_components.push_back( Cmp );

        if(  m_isEESchemaNetlist )   /* copy footprint name: */
        {
            if( strnicmp( LibName, "$noname", 7 ) != 0 )
            {
                while( *LibName > ' ' )
                {
                    Cmp->m_Module.Append( *LibName );
                    LibName++;
                }
            }
        }
        Cmp->m_TimeStamp = schematic_timestamp;

        ReadPinConnection( source, Cmp );
    }

    fclose( source );

    m_components.sort();

    return 0;
}

int WinEDA_CvpcbFrame::ReadFootprintFilterList( FILE* f )
{
    char       Line[BUFFER_CHAR_SIZE + 1];
    wxString   CmpRef;
    COMPONENT* Cmp = NULL;

    for( ; ; )
    {
        if( fgets( Line, BUFFER_CHAR_SIZE, f )  == 0 )
            break;
        if( strnicmp( Line, "$endlist", 8 ) == 0 )
        {
            Cmp = NULL;
            continue;
        }
        if( strnicmp( Line, "$endfootprintlist", 4 ) == 0 )
            return 0;

        if( strnicmp( Line, "$component", 10 ) == 0 ) // New component ref found
        {
            CmpRef = CONV_FROM_UTF8( Line + 11 );
            CmpRef.Trim( TRUE );
            CmpRef.Trim( FALSE );

            /* Search the new component in list */
            BOOST_FOREACH( COMPONENT& component, m_components )
            {
                Cmp = &component;

                if( Cmp->m_Reference == CmpRef )
                    break;
            }
        }
        else if( Cmp )
        {
            wxString fp = CONV_FROM_UTF8( Line + 1 );
            fp.Trim( FALSE );
            fp.Trim( TRUE );
            Cmp->m_FootprintFilter.Add( fp );
        }
    }

    return 1;
}

int ReadPinConnection( FILE* f, COMPONENT* Cmp )
{
    int      i, jj;
    wxString numpin;
    wxString net;
    char     Line[BUFFER_CHAR_SIZE + 1];
    PIN*     Pin     = NULL;

    for( ; ; )
    {
        /* debut description trouv */
        for( ; ; )
        {
            if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 )
                return -1;

            /* remove blanks from the beginning of the line */
            i = 0; while( Line[i] == ' ' )
                i++;

            while( Line[i] == '(' )
                i++;

            while( Line[i] == ' ' )
                i++;

            /* remove empty lines : */
            if( Line[i] < ' ' )
                continue;

            /* fin de description ? */
            if( Line[i] == ')' )
                return 0;

            net.Empty();
            numpin.Empty();

            /* Read pin name , 4 letters */
            for( jj = 0; jj < 4; jj++, i++ )
            {
                if( Line[i] == ' ' )
                    break;
                numpin.Append( Line[i] );
            }

            /* Read netname */
            while( Line[i] == ' ' )
                i++;

            for( ; ; i++ )
            {
                if( Line[i] <= ' ' )
                    break;
                net.Append( Line[i] );
            }

            Pin           = new PIN();
            Pin->m_Number = numpin;
            Pin->m_Net = net;
            Cmp->m_Pins.push_back( Pin );
        }
    }
}
<commit_msg>cvpcb: russian GOST windows bug fix<commit_after>/****************************/
/* readschematicnetlist.cpp */
/****************************/

/* Read a nelist type Eeschema or OrcadPCB2 and build the component list
 * Manages the lines like :
 * ( XXXXXX VALEUR|(pin1,pin2,...=newalim) ID VALEUR
 */

#include "fctsys.h"
#include "wxstruct.h"
#include "common.h"
#include "confirm.h"
#include "kicad_string.h"
#include "macros.h"

#include "cvpcb.h"
#include "protos.h"
#include "cvstruct.h"

#define SEPARATEUR '|'  /* caractere separateur dans netliste */

/* routines locales : */

static int ReadPinConnection( FILE* f, COMPONENT* CurrentCmp );

/* Tri la liste des composants par ordre alphabetique et met a jour le nouveau
 * chainage avant/arriere retourne un pointeur sur le 1er element de la liste */

#define BUFFER_CHAR_SIZE 1024   // Size of buffers used to  store netlist data

/**
 * Function ReadSchematicNetlist
 * Read a Eeschema (or OrcadPCB) netlist
 * like:
 * # EESchema Netlist Version 1.1 created  15/5/2008-12:09:21
 * (
 *  ( /32568D1E $noname  JP1 CONN_8X2 {Lib=CONN_8X2}
 *   (    1 GND )
 *   (    2 /REF10 )
 *   (    3 GND )
 *   (    4 /REF11 )
 *   (    5 GND )
 *   (    6 /REF7 )
 *   (    7 GND )
 *   (    8 /REF9 )
 *   (    9 GND )
 *   (   10 /REF6 )
 *   (   11 GND )
 *   (   12 /REF8 )
 *   (   13 GND )
 *   (   14 /REF4 )
 *   (   15 GND )
 *   (   16 /REF5 )
 *  )
 *  ( /325679C1 $noname  RR1 9x1K {Lib=RR9}
 *   (    1 VCC )
 *   (    2 /REF5 )
 *   (    3 /REF4 )
 *   (    4 /REF8 )
 *   (    5 /REF6 )
 *   (    6 /REF9 )
 *   (    7 /REF7 )
 *   (    8 /REF11 )
 *   (    9 /REF10 )
 *   (   10  ? )
 *  )
 * )
 * *
 * { Allowed footprints by component:
 * $component R5
 * R?
 * SM0603
 * SM0805
 * $endlist
 * $component C2
 * SM*
 * C?
 * C1-1
 * $endlist
 * $endfootprintlist
 * }
 */
int WinEDA_CvpcbFrame::ReadSchematicNetlist()
{
    char       alim[1024];
    int        i, k, l;
    char*      LibName;
    char       Line[BUFFER_CHAR_SIZE + 1];
    wxString   component_reference;  /* buffer for component reference (U1, R4...) */
    wxString   schematic_timestamp;  /* buffer for component time stamp */
    wxString   footprint_name;       /* buffer for component footprint field */
    wxString   component_value;      /* buffer for component values (470K, 22nF ...) */
    char*      ptchar;
    COMPONENT* Cmp;
    FILE*      source;

    m_modified = false;
    m_isEESchemaNetlist = false;

    /* Clear components buffer */
    if( !m_components.empty() )
    {
        m_components.clear();
    }

    source = wxFopen( m_NetlistFileName.GetFullPath(), wxT( "rt" ) );

    if( source == 0 )
    {
        DisplayError( this,  _( "File <" ) + m_NetlistFileName.GetFullPath() +
                      _( "> not found" )  );
        return -1;
    }

    /* Read the file header (must be  "( { OrCAD PCB" or "({ OrCAD PCB" )
     * or "# EESchema Netliste"
     */
    (void) fgets( Line, BUFFER_CHAR_SIZE, source );
    /* test for netlist type PCB2 */
    i = strnicmp( Line, "( {", 3 );
    if( i != 0 )
        i = strnicmp( Line, "({", 2 );
    if( i != 0 )
    {
        i = strnicmp( Line, "# EESchema", 7 ); /* net type EESchema */
        if( i == 0 )
            m_isEESchemaNetlist = TRUE;
    }

    if( i != 0 )
    {
        wxString msg, Lineconv = CONV_FROM_UTF8( Line );
        msg.Printf( _( "Unknown file format <%s>" ), Lineconv.GetData() );
        DisplayError( this, msg );
        fclose( source );
        return -3;
    }

    SetStatusText( _( "Netlist Format: EESchema" ), 0 );

    /* Read the netlist */
    for( ; ; )
    {
        /* Search the beginning of a component description */

        if( fgets( Line, BUFFER_CHAR_SIZE, source )  == 0 )
            break;

        /* Remove blanks */
        i = 0; while( Line[i] == ' ' )
            i++;

        /* remove empty lines : */
        if( Line[i] < ' ' )
            continue;

        if( strnicmp( &Line[i], "{ Allowed footprints", 20 ) == 0 )
        {
            ReadFootprintFilterList( source );
            continue;
        }

        if( strnicmp( &Line[i], "( ", 2 ) != 0 )
            continue;

        /*******************************/
        /* Component description found */
        /*******************************/
        while( Line[i] != ' ' )
            i++;

        while( Line[i] == ' ' )
            i++;

        /* i points the beginning of the schematic time stamp */

        schematic_timestamp.Empty();
        while( Line[i] != ' ' )
            schematic_timestamp.Append( Line[i++] );

        /* search val/ref.lib */
        while( Line[i] == ' ' )
            i++;

        /* i points the component value */
        LibName = Line + i;

        component_reference.Empty();
        footprint_name.Empty();
        component_value.Empty();
        memset( alim, 0, sizeof(alim) );

        /* Read value */

        ptchar = strstr( &Line[i], " " );  // Search end of value field (space)
        if( ptchar == 0 )
        {
            wxString msg;
            msg.Printf( _( "Netlist error: %s" ), Line );
            DisplayError( this, msg );
            k = 0;
        }
        else
            k = ptchar - Line;

        for( ; i < k; i++ )
        {
            if( Line[i] == SEPARATEUR )
                break;
            footprint_name.Append( Line[i] );
        }

        if( (Line[++i] == '(') && (Line[k - 1] == ')' ) )
        {
            i++; l = 0; while( k - 1 > i )
                alim[l++] = Line[i++];
        }
        else
            i = k;

        /* Search component reference */
        while( Line[i] != ' ' )
            i++;

        /* goto end of value field */
        while( Line[i] == ' ' )
            i++;

        /* goto beginning of  reference */

        /* debut reference trouv */
        for( ; ; i++ )
        {
#if defined(KICAD_GOST)
            if( Line[i] == ' ' )
#else
            if( Line[i] <= ' ' )
#endif
                break;
            component_reference.Append( Line[i] );
        }

        /* Search component value */
        while( Line[i] == ' ' )
            i++;

        /** goto beginning of  value */

        for( ; ; i++ )
        {
#if defined(KICAD_GOST)
            if( (Line[i] == ' ') || (Line[i] == '\n') || (Line[i] == '\r') )
#else
            if( Line[i] <= ' ' )
#endif
                break;
            component_value.Append( Line[i] );
        }

        /* Store info for this component */
        Cmp = new COMPONENT();
        Cmp->m_Reference = component_reference;
        Cmp->m_Value     = component_value;
        m_components.push_back( Cmp );

        if(  m_isEESchemaNetlist )   /* copy footprint name: */
        {
            if( strnicmp( LibName, "$noname", 7 ) != 0 )
            {
                while( *LibName > ' ' )
                {
                    Cmp->m_Module.Append( *LibName );
                    LibName++;
                }
            }
        }
        Cmp->m_TimeStamp = schematic_timestamp;

        ReadPinConnection( source, Cmp );
    }

    fclose( source );

    m_components.sort();

    return 0;
}

int WinEDA_CvpcbFrame::ReadFootprintFilterList( FILE* f )
{
    char       Line[BUFFER_CHAR_SIZE + 1];
    wxString   CmpRef;
    COMPONENT* Cmp = NULL;

    for( ; ; )
    {
        if( fgets( Line, BUFFER_CHAR_SIZE, f )  == 0 )
            break;
        if( strnicmp( Line, "$endlist", 8 ) == 0 )
        {
            Cmp = NULL;
            continue;
        }
        if( strnicmp( Line, "$endfootprintlist", 4 ) == 0 )
            return 0;

        if( strnicmp( Line, "$component", 10 ) == 0 ) // New component ref found
        {
            CmpRef = CONV_FROM_UTF8( Line + 11 );
            CmpRef.Trim( TRUE );
            CmpRef.Trim( FALSE );

            /* Search the new component in list */
            BOOST_FOREACH( COMPONENT& component, m_components )
            {
                Cmp = &component;

                if( Cmp->m_Reference == CmpRef )
                    break;
            }
        }
        else if( Cmp )
        {
            wxString fp = CONV_FROM_UTF8( Line + 1 );
            fp.Trim( FALSE );
            fp.Trim( TRUE );
            Cmp->m_FootprintFilter.Add( fp );
        }
    }

    return 1;
}

int ReadPinConnection( FILE* f, COMPONENT* Cmp )
{
    int      i, jj;
    wxString numpin;
    wxString net;
    char     Line[BUFFER_CHAR_SIZE + 1];
    PIN*     Pin     = NULL;

    for( ; ; )
    {
        /* debut description trouv */
        for( ; ; )
        {
            if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 )
                return -1;

            /* remove blanks from the beginning of the line */
            i = 0; while( Line[i] == ' ' )
                i++;

            while( Line[i] == '(' )
                i++;

            while( Line[i] == ' ' )
                i++;

            /* remove empty lines : */
            if( Line[i] < ' ' )
                continue;

            /* fin de description ? */
            if( Line[i] == ')' )
                return 0;

            net.Empty();
            numpin.Empty();

            /* Read pin name , 4 letters */
            for( jj = 0; jj < 4; jj++, i++ )
            {
                if( Line[i] == ' ' )
                    break;
                numpin.Append( Line[i] );
            }

            /* Read netname */
            while( Line[i] == ' ' )
                i++;

            for( ; ; i++ )
            {
                if( Line[i] <= ' ' )
                    break;
                net.Append( Line[i] );
            }

            Pin           = new PIN();
            Pin->m_Number = numpin;
            Pin->m_Net = net;
            Cmp->m_Pins.push_back( Pin );
        }
    }
}
<|endoftext|>


<commit_before>/*
* @Copyright: Copyright[2015]<Alejandro Bordallo>
* @Date:      2015-05-17
* @Email:     alex.bordallo@ed.ac.uk
* @Desc:      Joystick remote control node
*/

#include "joy_remote.h"

JoyRemote::JoyRemote(ros::NodeHandle* nh) {
  nh_ = nh;
  joy_sub_ = nh_->subscribe("joy", 1000, &JoyRemote::joyCallback, this);
  moveTowardClient = nh_->serviceClient<motion::MoveToward>(
                       "/motion/move_toward", true);
  wakeUpClient = nh_->serviceClient<std_srvs::Empty>(
                   "/motion/wake_up", true);
  moveInitClient = nh_->serviceClient<std_srvs::Empty>(
                     "/motion/move_init", true);
  standClient = nh_->serviceClient<motion::SetPosture>(
                  "/motion/goto_posture", true);
  restClient = nh_->serviceClient<std_srvs::Empty>(
                 "/motion/rest", true);
  stopMoveClient = nh_->serviceClient<std_srvs::Empty>(
                     "/motion/stop_move", true);
  INFO("Joystick remote node initialised" << std::endl);
  wakeUpFlag = false;
  moveInitFlag = false;
  standFlag = false;
  restFlag = false;
  standSrv.request.speed = 1.0f;
}

JoyRemote::~JoyRemote() {
  ros::shutdown();
}

void JoyRemote::joyCallback(const sensor_msgs::Joy::ConstPtr& msg) {
  if (msg->buttons[1]) {
    wakeUpFlag = true;
  } else if (msg->buttons[2]) {
    moveInitFlag = true;
  } else if (msg->buttons[3]) {
    standFlag = true;
  } else if (msg->buttons[0]) {
    restFlag = true;
  } else {
    float x = msg->axes[1];
    float y = msg->axes[0];
    float theta = msg->axes[3];
    moveSrv.request.norm_velocity.x = x;
    moveSrv.request.norm_velocity.y = y;
    moveSrv.request.norm_velocity.theta = theta;
  }
}

void JoyRemote::sendCmd() {
  if (wakeUpFlag) {
    this->wakeUp();
  } else if (moveInitFlag) {
    this->moveInit();
  } else if (standFlag) {
    this->stand();
  } else if (restFlag) {
    this->rest();
  } else {moveTowardClient.call(moveSrv);}
}

void JoyRemote::wakeUp() {
  wakeUpClient.call(wakeUpSrv);
  wakeUpFlag = false;
}

void JoyRemote::moveInit() {
  moveInitClient.call(moveInitSrv);
  moveInitFlag = false;
}

void JoyRemote::stand() {
  wakeUpClient.call(wakeUpSrv);
  standSrv.request.posture_name = "Stand";
  standClient.call(standSrv);
  moveInitClient.call(moveInitSrv);
  standFlag = false;
}

void JoyRemote::rest() {
  stopMoveClient.call(stopSrv);
  sleep(0.25);
  moveInitClient.call(moveInitSrv);
  sleep(0.25);
  restClient.call(restSrv);
  restFlag = false;
}

int main(int argc, char *argv[]) {
  ros::init(argc, argv, "JoyRemote");
  ros::NodeHandle nh;

  JoyRemote joyTest(&nh);

  ros::Rate r(5);

  while (ros::ok()) {
    joyTest.sendCmd();
    ros::spinOnce();
    r.sleep();
  }

  return 0;
}

<commit_msg>Add check if first required service is available for remote control<commit_after>/*
* @Copyright: Copyright[2015]<Alejandro Bordallo>
* @Date:      2015-05-17
* @Email:     alex.bordallo@ed.ac.uk
* @Desc:      Joystick remote control node
*/

#include "joy_remote.h"

JoyRemote::JoyRemote(ros::NodeHandle* nh) {
  nh_ = nh;
  joy_sub_ = nh_->subscribe("joy", 1000, &JoyRemote::joyCallback, this);
  moveTowardClient = nh_->serviceClient<motion::MoveToward>(
                       "/motion/move_toward", true);
  moveTowardClient.waitForExistence();
  wakeUpClient = nh_->serviceClient<std_srvs::Empty>(
                   "/motion/wake_up", true);
  moveInitClient = nh_->serviceClient<std_srvs::Empty>(
                     "/motion/move_init", true);
  standClient = nh_->serviceClient<motion::SetPosture>(
                  "/motion/goto_posture", true);
  restClient = nh_->serviceClient<std_srvs::Empty>(
                 "/motion/rest", true);
  stopMoveClient = nh_->serviceClient<std_srvs::Empty>(
                     "/motion/stop_move", true);
  INFO("Joystick remote node initialised" << std::endl);
  wakeUpFlag = false;
  moveInitFlag = false;
  standFlag = false;
  restFlag = false;
  standSrv.request.speed = 1.0f;
}

JoyRemote::~JoyRemote() {
  ros::shutdown();
}

void JoyRemote::joyCallback(const sensor_msgs::Joy::ConstPtr& msg) {
  if (msg->buttons[1]) {
    wakeUpFlag = true;
  } else if (msg->buttons[2]) {
    moveInitFlag = true;
  } else if (msg->buttons[3]) {
    standFlag = true;
  } else if (msg->buttons[0]) {
    restFlag = true;
  } else {
    float x = msg->axes[1];
    float y = msg->axes[0];
    float theta = msg->axes[3];
    moveSrv.request.norm_velocity.x = x;
    moveSrv.request.norm_velocity.y = y;
    moveSrv.request.norm_velocity.theta = theta;
  }
}

void JoyRemote::sendCmd() {
  if (wakeUpFlag) {
    this->wakeUp();
  } else if (moveInitFlag) {
    this->moveInit();
  } else if (standFlag) {
    this->stand();
  } else if (restFlag) {
    this->rest();
  } else {moveTowardClient.call(moveSrv);}
}

void JoyRemote::wakeUp() {
  wakeUpClient.call(wakeUpSrv);
  wakeUpFlag = false;
}

void JoyRemote::moveInit() {
  moveInitClient.call(moveInitSrv);
  moveInitFlag = false;
}

void JoyRemote::stand() {
  wakeUpClient.call(wakeUpSrv);
  standSrv.request.posture_name = "Stand";
  standClient.call(standSrv);
  moveInitClient.call(moveInitSrv);
  standFlag = false;
}

void JoyRemote::rest() {
  stopMoveClient.call(stopSrv);
  sleep(0.25);
  moveInitClient.call(moveInitSrv);
  sleep(0.25);
  restClient.call(restSrv);
  restFlag = false;
}

int main(int argc, char *argv[]) {
  ros::init(argc, argv, "JoyRemote");
  ros::NodeHandle nh;

  JoyRemote joyTest(&nh);

  ros::Rate r(5);

  while (ros::ok()) {
    joyTest.sendCmd();
    ros::spinOnce();
    r.sleep();
  }

  return 0;
}

<|endoftext|>


<commit_before>/**
 * @file CommonAPIService.hpp
 * @author Denis Kotov
 * @date 3 Apr 2017
 * @brief Contains CommonAPIService wrapper class for creating service
 * @copyright MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git
 */

#ifndef ICC_COMMONAPISERVICE_HPP
#define ICC_COMMONAPISERVICE_HPP

#include <CommonAPI/CommonAPI.hpp>
#include <helpers/concept_base_of_template.hpp>

namespace icc {

namespace commonapi {

template<typename Service>
class CommonAPIService
    : public Service {
  static_assert(icc::helpers::is_base_of_template<Service, CommonAPI::Stub>::value,
                "Service does not derived from CommonAPI::Stub");
 public:
  CommonAPIService() = default;
  CommonAPIService(const std::string &_domain,
                   const std::string &_instance)
      : domain_(_domain),
        instance_(_instance) {
    registerService(domain_, instance_);
  }

  CommonAPIService(CommonAPIService const &_service) = delete;
  CommonAPIService(const Service &_service) = delete;

  ~CommonAPIService() {
    unregisterService();
  }

 public:
  bool registerService(const std::string &_domain,
                       const std::string &_instance) {
    if (!is_registered) {
      std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();
      service_ = std::shared_ptr<Service>(this, [](Service *) {
        // Do nothing to prevent double deletion
      });
      if (service_) {
        is_registered = runtime->registerService(_domain, _instance, service_);
        if (is_registered) {
          domain_ = _domain;
          instance_ = _instance;
        }
      }
    }
    return is_registered;
  }

  bool unregisterService() {
    if (is_registered) {
      std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();
      if (!(is_registered = !runtime->unregisterService(domain_, this->getStubAdapter()->getInterface(), instance_))) {
        service_ = nullptr;
      }
    }
    return !is_registered;
  }

 private:
  bool is_registered = false;
  std::string domain_;
  std::string instance_;
  std::shared_ptr<Service> service_ = nullptr;
};

}

}

#endif  // ICC_COMMONAPISERVICE_HPP
<commit_msg>Improved registring of services<commit_after>/**
 * @file CommonAPIService.hpp
 * @author Denis Kotov
 * @date 3 Apr 2017
 * @brief Contains CommonAPIService wrapper class for creating service
 * @copyright MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git
 */

#ifndef ICC_COMMONAPISERVICE_HPP
#define ICC_COMMONAPISERVICE_HPP

#include <CommonAPI/CommonAPI.hpp>
#include <helpers/concept_base_of_template.hpp>

namespace icc {

namespace commonapi {

template<typename Service>
class CommonAPIService
    : public Service {
  static_assert(icc::helpers::is_base_of_template<Service, CommonAPI::Stub>::value,
                "Service does not derived from CommonAPI::Stub");
 public:
  CommonAPIService() = default;
  CommonAPIService(const std::string &_domain,
                   const std::string &_instance)
      : domain_(_domain),
        instance_(_instance) {
    registerService(domain_, instance_);
  }

  CommonAPIService(CommonAPIService const &_service) = delete;
  CommonAPIService(const Service &_service) = delete;

  ~CommonAPIService() {
    unregisterService();
  }

 public:
  bool registerService(const std::string &_domain,
                       const std::string &_instance) {
    if (!is_registered) {
      std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();
      service_ = std::shared_ptr<Service>(this, [](Service *) {
        // Do nothing to prevent double deletion
      });
      if (service_) {
        is_registered = runtime->registerService(_domain, _instance, service_);
        if (is_registered) {
          domain_ = _domain;
          instance_ = _instance;
        } else {
          service_ = nullptr;
        }
      }
    }
    return is_registered;
  }

  bool unregisterService() {
    if (is_registered) {
      std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();
      if (!(is_registered = !runtime->unregisterService(domain_, this->getStubAdapter()->getInterface(), instance_))) {
        service_ = nullptr;
      }
    }
    return !is_registered;
  }

 private:
  bool is_registered = false;
  std::string domain_;
  std::string instance_;
  std::shared_ptr<Service> service_ = nullptr;
};

}

}

#endif  // ICC_COMMONAPISERVICE_HPP
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkPluginActivator.h"
#include "DicomEventHandler.h"
#include <service/event/ctkEventConstants.h>
#include <ctkDictionary.h>
#include <mitkLogMacros.h>
#include <mitkDicomSeriesReader.h>
#include <mitkDataNode.h>
#include <QmitkBaseFunctionalityComponent.h>
#include <mitkIDataStorageService.h>
#include <service/event/ctkEventAdmin.h>
#include <ctkServiceReference.h>
#include <mitkRenderingManager.h>

DicomEventHandler::DicomEventHandler()
{
}

DicomEventHandler::~DicomEventHandler()
{
}

void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent)
{
    QString patientName = ctkEvent.getProperty("PatientName").toString();
    QString studyUID = ctkEvent.getProperty("StudyUID").toString();
    QString studyName = ctkEvent.getProperty("StudyName").toString();
    QString seriesUID = ctkEvent.getProperty("SeriesUID").toString();
    QString seriesName = ctkEvent.getProperty("SeriesName").toString();
    QString path = ctkEvent.getProperty("Path").toString();

    std::list<std::string> qualifiedUIDs;
    mitk::DicomSeriesReader::StringContainer seriesToLoad;
    std::size_t found;

    mitk::DicomSeriesReader::UidFileNamesMap dicomSeriesMap = mitk::DicomSeriesReader::GetSeries(path.toStdString(),false);
    mitk::DicomSeriesReader::UidFileNamesMap::const_iterator qualifiedSeriesInstanceUIDIterator;

    for(qualifiedSeriesInstanceUIDIterator = dicomSeriesMap.begin();
        qualifiedSeriesInstanceUIDIterator != dicomSeriesMap.end();
        ++qualifiedSeriesInstanceUIDIterator)
    {
        found = qualifiedSeriesInstanceUIDIterator->first.find(seriesUID.toStdString());
        if(found!= qualifiedSeriesInstanceUIDIterator->first.npos)
        {
            qualifiedUIDs.push_back(qualifiedSeriesInstanceUIDIterator->first);
            seriesToLoad = qualifiedSeriesInstanceUIDIterator->second;
        }
    }

    mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad);
    if (node.IsNull())
    {
        MITK_ERROR << "Could not load series: " << seriesUID.toStdString();
    }
    else
    {
        //Get Reference for default data storage.
        ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
        mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);
        mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();

        dataStorage->Add(node);

        // Initialize the RenderWindow
        mitk::TimeSlicedGeometry::Pointer geometry = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll());
        mitk::RenderingManager::GetInstance()->InitializeViews(geometry);

    }
}

void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent)
{
}

void DicomEventHandler::SubscribeSlots()
{
    ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>();
    if (ref)
    {
        ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref);
        ctkDictionary properties;
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties);
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties);
    }
}
<commit_msg>avoided EventHandler to iterate over the dicom folder another time. DicomSeriesReader::GetSeries() won't be called anymore. Now LoadDicomSeries() is called directly with a list of all files from the series provided due event properies.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkPluginActivator.h"
#include "DicomEventHandler.h"
#include <service/event/ctkEventConstants.h>
#include <ctkDictionary.h>
#include <mitkLogMacros.h>
#include <mitkDicomSeriesReader.h>
#include <mitkDataNode.h>
#include <QmitkBaseFunctionalityComponent.h>
#include <mitkIDataStorageService.h>
#include <service/event/ctkEventAdmin.h>
#include <ctkServiceReference.h>
#include <mitkRenderingManager.h>
#include <QVector>

DicomEventHandler::DicomEventHandler()
{
}

DicomEventHandler::~DicomEventHandler()
{
}

void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent)
{
    QStringList listOfFilesForSeries;
    mitk::DicomSeriesReader::StringContainer seriesToLoad;

    listOfFilesForSeries = ctkEvent.getProperty("FilesForSeries").toStringList();

    if (!listOfFilesForSeries.isEmpty()){

        QStringListIterator it(listOfFilesForSeries);

        while (it.hasNext())
        {
            seriesToLoad.push_back(it.next().toStdString());
        }

        mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad);
        if (node.IsNull())
        {
            MITK_ERROR << "Error loading series: " << ctkEvent.getProperty("SeriesName").toString().toStdString()
                << " id: " <<ctkEvent.getProperty("SeriesUID").toString().toStdString();
        }
        else
        {
            //Get Reference for default data storage.
            ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
            mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);
            mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();

            dataStorage->Add(node);

            // Initialize the RenderWindow
            mitk::TimeSlicedGeometry::Pointer geometry = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll());
            mitk::RenderingManager::GetInstance()->InitializeViews(geometry);
        }
    }
    else
    {
        MITK_INFO << "There are no files for the current series";
    }
}

void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent)
{
}

void DicomEventHandler::SubscribeSlots()
{
    ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>();
    if (ref)
    {
        ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref);
        ctkDictionary properties;
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties);
        properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED";
        eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties);
    }
}
<|endoftext|>


<commit_before>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: user_fs.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: Jun  4, 2015
 *  Time: 22:52:30
 *  Description: main class of this GSFS
 *****************************************************************************/
#include "user_fs.h"
#include <stdexcept>
#include "bytes_order.h"

    // calling order of functions below:
    // master node: setMaster -> initDirTree -> initHost -> initTCPNetwork
    // slave node: initDirTree -> initHost -> initTCPNetwork

    void UserFS::setMaster() { _host_id = 1; }

    void UserFS::initHost(const std::string& addr, const uint16_t tcp_port, const uint16_t ssh_port) {
        boost::unique_lock< boost::shared_mutex > lock(_access);

        // this functions should only be called when program initializes

        Hosts::Host host;
        host.id = _host_id;
        host.address = addr;
        host.mountdir = _dir;
        host.tmpdir = _tmpdir;
        host.tcp_port = tcp_port;
        host.ssh_port = ssh_port;

        // push self's host at 0
        _hosts.push(host);
    }

    // this function may throw exceptions
    void UserFS::initDirTree(const std::string& dir, const std::string& tmpdir) {
        using namespace boost::filesystem;

        boost::unique_lock< boost::shared_mutex > lock(_access);

        if (!exists(dir))
            throw std::invalid_argument(dir + " not exists. ");

        if (!is_directory(dir))
            throw std::invalid_argument(dir + " is not directory. ");

        if (exists(tmpdir / dir))
            throw std::invalid_argument(std::string("Assert ") + path(tmpdir / dir).string() + " not exists. ");

        if (!is_directory(dir))
            throw std::invalid_argument(dir + " is not directory. ");

        if (!create_directory(tmpdir / dir))
            throw std::invalid_argument(std::string("Failed creating directory ") + path(tmpdir / dir).string() + ".");

        _tmpdir = absolute(tmpdir).string();
        _dir = dir;

        _dir_tree.initialize();
        _dir_tree.root()->type = DirTree::TreeNode::DIRECTORY;
        // It seems there's is a portable way to get dir size, just set it to 0
        // If anybody knows how to do that, please tell me. Thanks.
        _dir_tree.root()->size = 0;
        _dir_tree.root()->host_id = _host_id;
        _dir_tree.root()->mtime = last_write_time(dir);
        _dir_tree.root()->num_links = hard_link_count(dir);

        std::function< void (const path&, const path&, const DirTree::TreeNode&) > traverseDirectory;
        traverseDirectory = [this, &traverseDirectory]
            (const path& dir, const path& _tmpdir, const DirTree::TreeNode& parent)->void {
            for (auto& f: directory_iterator(dir)) {
                auto file_type = symlink_status(f).type();

                decltype(DirTree::TreeNode::type) treenode_type;

                switch (file_type) {
                    case file_type::directory_file:
                        treenode_type = DirTree::TreeNode::DIRECTORY;
                        break;
                    case file_type::regular_file:
                        treenode_type = DirTree::TreeNode::REGULAR;
                        break;
                    case file_type::character_file:
                        treenode_type = DirTree::TreeNode::CHRDEVICE;
                        break;
                    case file_type::block_file:
                        treenode_type = DirTree::TreeNode::BLKDEVICE;
                        break;
                    case file_type::fifo_file:
                        treenode_type = DirTree::TreeNode::FIFO;
                        break;
                    case file_type::symlink_file:
                        treenode_type = DirTree::TreeNode::SYMLINK;
                        break;
                    case file_type::socket_file:
                        treenode_type = DirTree::TreeNode::SOCKET;
                        break;
                    case file_type::type_unknown:
                    default:
                        treenode_type = DirTree::TreeNode::UNKNOWN;
                }

                if (treenode_type == DirTree::TreeNode::UNKNOWN)
                    continue;
                else if (treenode_type == DirTree::TreeNode::DIRECTORY) {
                    create_directory(_tmpdir / f.path());

                    DirTree::TreeNode dirnode;
                    dirnode.type = treenode_type;
                    dirnode.name = f.path().filename().string();
                    dirnode.size = 0;
                    dirnode.mtime = last_write_time(f.path());
                    dirnode.host_id = _host_id;
                    dirnode.num_links = hard_link_count(f.path());

                    auto insert_rtv = parent.children.insert(dirnode);

                    traverseDirectory(f, _tmpdir, *(insert_rtv.first));
                } else {
                    // create hard link (src, dst)
                    create_hard_link(f, _tmpdir / f.path());

                    DirTree::TreeNode filenode;
                    filenode.type = treenode_type;
                    filenode.name = f.path().filename().string();
                    filenode.size = file_size(f);
                    filenode.mtime = last_write_time(f.path());
                    filenode.host_id = _host_id;
                    // GSFS create another hard link for files except directory
                    filenode.num_links = 1 + hard_link_count(f.path());

                    parent.children.insert(filenode);
                }
            }
        };

        traverseDirectory(_dir, _tmpdir, *_dir_tree.root());
    }

    // returns true on error
    bool UserFS::initTCPNetwork(const std::string& addr, const uint16_t port) {
        bool is_master = _host_id == 1;

        bool init_rtv = _tcp_manager.initialize(is_master, addr, port);

        if (init_rtv) return 1;

        _tcp_manager.start();

        // push master's host
        if (is_master)
            _hosts.push(_hosts[0]);
        // else wait for master's recognition or rejection
        else {
            std::string dir_tree_seq;
            std::string host_seq;

            {
                boost::shared_lock< boost::shared_mutex > lock(_access);
                dir_tree_seq = DirTree::serialize(_dir_tree);
                host_seq = Hosts::Host::serialize(_hosts[0]);
            }

            std::string dir_tree_seq_len = host_to_network_64(dir_tree_seq.length());
            std::string host_seq_len = host_to_network_64(host_seq.length());
            std::string protocol_type = host_to_network_64(0x00);

            std::string message = protocol_type +
                                  dir_tree_seq_len + dir_tree_seq +
                                  host_seq_len + host_seq;

            _tcp_manager.write(message);

            _slave_wait_sem.wait();
        }

        return 0;
    }

    const DirTree::TreeNode* UserFS::find(const std::string& path) {
        boost::shared_lock< boost::shared_mutex > lock(_access);
        return _dir_tree.find(path);
    }

    // returns num of bytes read on success
    // returns < 0 on error
    intmax_t UserFS::read(const uint64_t node_id, const std::string path,
                  const size_t offset, const size_t size, char* buff) {
        // remote node isn't inserted into ssh manager
        if (!_ssh_manager.findHost(node_id)) {
            bool rtv = _ssh_manager.insertHost(node_id, _hosts[node_id].address, _hosts[node_id].ssh_port);
            if (rtv) return -1;
        }

        boost::filesystem::path remote_path = _hosts[node_id].tmpdir;
        remote_path /= _hosts[node_id].mountdir;
        remote_path /= path;

        std::string remote_path_string = remote_path.string();

        // read local file
        if (node_id == _host_id) {
            std::ifstream fin(remote_path_string);
            fin.seekg(offset);
            fin.read(buff, size);
            if (fin.fail() || fin.bad()) return -1;
            size_t bytes_read = fin.gcount();
            return bytes_read;
        }

        // read remote file
        return _ssh_manager.read(node_id, remote_path_string, offset, size, buff);
    }

    // send update packet to all slaves
    void UserFS::sendUpdate() {
        std::string dir_tree_seq;
        std::string hosts_seq;

        {
            boost::shared_lock< boost::shared_mutex > lock(_access);
            dir_tree_seq = DirTree::serialize(_dir_tree);
            hosts_seq = Hosts::serialize(_hosts);
        }

        sendUpdate(dir_tree_seq, hosts_seq);
    }

    void UserFS::sendUpdate(const std::string& dir_tree_seq, const std::string& hosts_seq) {
        std::string message = host_to_network_64(0x02);
        message += host_to_network_64(dir_tree_seq.length());
        message += dir_tree_seq;
        message += host_to_network_64(hosts_seq.length());
        message += hosts_seq;

        // send to all slaves
        _tcp_manager.write(message);
    }

    // Callback Functions for slaves' tcp manager:

    // slave get recognized from master
    void UserFS::slaveRecognized(const uint64_t slave_id, const std::string& dir_tree_seq, const std::string& hosts_seq) {
        // deploy dir tree
        DirTree merged_tree = DirTree::deserialize(dir_tree_seq);

        // deploy hosts
        _host_id = slave_id;
        Hosts merged_hosts = Hosts::deserialize(hosts_seq);

        {
            boost::unique_lock< boost::shared_mutex > lock(_access);
            _dir_tree.root()->children = merged_tree.root()->children;
            _hosts = merged_hosts;
        }
        // wake up main thread
        _slave_wait_sem.post();
    }

    // master sent a update packet, update dirtree and hosts
    void UserFS::updateInfo(const std::string& dir_tree_seq, const std::string& hosts_seq) {
        DirTree new_tree = DirTree::deserialize(dir_tree_seq);
        Hosts merged_hosts = Hosts::deserialize(hosts_seq);

        {
            boost::unique_lock< boost::shared_mutex > lock(_access);
            _dir_tree.root()->children = new_tree.root()->children;
            _hosts = merged_hosts;
        }
    }

    // connect failed or slave disconnect from master
    void UserFS::disconnect() {
        // clear dir tree
        {
            boost::unique_lock< boost::shared_mutex > lock(_access);
            _dir_tree.removeNotOf(_host_id);
        }
    }

    // Callback Functions for master' tcp manager:

    // slave disconnect from master
    void UserFS::disconnect(const TCPMasterMessager::Connection::iterator handle) {
        uint64_t& slave_id = std::get<4>(*handle);

        // slave is initializting
        if (slave_id == 0) return;

        // remove this slave's node in dir tree
        {
            boost::unique_lock< boost::shared_mutex > lock(_access);
            _dir_tree.removeOf(slave_id);
        }

        slave_id = 0;
        sendUpdate();
    }

    // new slave coming, chekc dirtree, allocate host_id, merge dir_tree and hosts
    void UserFS::newConnection(const std::string& dir_tree_seq,
                       const std::string& host_seq,
                       const TCPMasterMessager::Connection::iterator handle) {
        // deserialize
        DirTree slave_dir_tree = DirTree::deserialize(dir_tree_seq);
        Hosts::Host slave_host = Hosts::Host::deserialize(host_seq);

        // check conflicts
        std::vector<std::string> conflicts;

        {
           boost::shared_lock< boost::shared_mutex > lock(_access);
           conflicts = _dir_tree.hasConflict(slave_dir_tree);
        }

        // there's conflict, close connection
        if (conflicts.size()) return _tcp_manager.close(handle);
        // else

        // alloc slave id
        uint64_t slave_id = _max_host_id++;
        slave_host.id = slave_id;
        slave_dir_tree.root()->setHostID(slave_id);

        std::get<4>(*handle) = slave_id;

        {
            boost::unique_lock< boost::shared_mutex > lock(_access);

            // merge dir tree
            _dir_tree.merge(slave_dir_tree);

            // merge host
            _hosts.push(slave_host);
        }

        // construct response message

        std::string merged_dir_tree_seq;
        std::string merged_hosts_seq;

        {
            boost::shared_lock< boost::shared_mutex > lock(_access);
            merged_dir_tree_seq = DirTree::serialize(_dir_tree);
            merged_hosts_seq = Hosts::serialize(_hosts);
        }

        std::string merged_dir_tree_seq_len = host_to_network_64(merged_dir_tree_seq.length());
        std::string merged_hosts_seq_len = host_to_network_64(merged_hosts_seq.length());
        std::string protocol_type = host_to_network_64(0x01);
        std::string slave_id_seq = host_to_network_64(slave_id);

        std::string message = protocol_type + slave_id_seq +
                              merged_dir_tree_seq_len + merged_dir_tree_seq +
                              merged_hosts_seq_len + merged_hosts_seq;

        // send to slave
        _tcp_manager.writeTo(message, handle);
        sendUpdate(merged_dir_tree_seq, merged_hosts_seq);
    }

<commit_msg>adjust indent<commit_after>/******************************************************************************
 *  Copyright (c) 2015 Jamis Hoo
 *  Distributed under the MIT license
 *  (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
 *
 *  Project:
 *  Filename: user_fs.cc
 *  Version: 1.0
 *  Author: Jamis Hoo
 *  E-mail: hoojamis@gmail.com
 *  Date: Jun  4, 2015
 *  Time: 22:52:30
 *  Description: main class of this GSFS
 *****************************************************************************/
#include "user_fs.h"
#include <stdexcept>
#include "bytes_order.h"

// calling order of functions below:
// master node: setMaster -> initDirTree -> initHost -> initTCPNetwork
// slave node: initDirTree -> initHost -> initTCPNetwork

void UserFS::setMaster() { _host_id = 1; }

void UserFS::initHost(const std::string& addr, const uint16_t tcp_port, const uint16_t ssh_port) {
    boost::unique_lock< boost::shared_mutex > lock(_access);

    // this functions should only be called when program initializes

    Hosts::Host host;
    host.id = _host_id;
    host.address = addr;
    host.mountdir = _dir;
    host.tmpdir = _tmpdir;
    host.tcp_port = tcp_port;
    host.ssh_port = ssh_port;

    // push self's host at 0
    _hosts.push(host);
}

// this function may throw exceptions
void UserFS::initDirTree(const std::string& dir, const std::string& tmpdir) {
    using namespace boost::filesystem;

    boost::unique_lock< boost::shared_mutex > lock(_access);

    if (!exists(dir))
        throw std::invalid_argument(dir + " not exists. ");

    if (!is_directory(dir))
        throw std::invalid_argument(dir + " is not directory. ");

    if (exists(tmpdir / dir))
        throw std::invalid_argument(std::string("Assert ") + path(tmpdir / dir).string() + " not exists. ");

    if (!is_directory(dir))
        throw std::invalid_argument(dir + " is not directory. ");

    if (!create_directory(tmpdir / dir))
        throw std::invalid_argument(std::string("Failed creating directory ") + path(tmpdir / dir).string() + ".");

    _tmpdir = absolute(tmpdir).string();
    _dir = dir;

    _dir_tree.initialize();
    _dir_tree.root()->type = DirTree::TreeNode::DIRECTORY;
    // It seems there's is a portable way to get dir size, just set it to 0
    // If anybody knows how to do that, please tell me. Thanks.
    _dir_tree.root()->size = 0;
    _dir_tree.root()->host_id = _host_id;
    _dir_tree.root()->mtime = last_write_time(dir);
    _dir_tree.root()->num_links = hard_link_count(dir);

    std::function< void (const path&, const path&, const DirTree::TreeNode&) > traverseDirectory;
    traverseDirectory = [this, &traverseDirectory]
        (const path& dir, const path& _tmpdir, const DirTree::TreeNode& parent)->void {
        for (auto& f: directory_iterator(dir)) {
            auto file_type = symlink_status(f).type();

            decltype(DirTree::TreeNode::type) treenode_type;

            switch (file_type) {
                case file_type::directory_file:
                    treenode_type = DirTree::TreeNode::DIRECTORY;
                    break;
                case file_type::regular_file:
                    treenode_type = DirTree::TreeNode::REGULAR;
                    break;
                case file_type::character_file:
                    treenode_type = DirTree::TreeNode::CHRDEVICE;
                    break;
                case file_type::block_file:
                    treenode_type = DirTree::TreeNode::BLKDEVICE;
                    break;
                case file_type::fifo_file:
                    treenode_type = DirTree::TreeNode::FIFO;
                    break;
                case file_type::symlink_file:
                    treenode_type = DirTree::TreeNode::SYMLINK;
                    break;
                case file_type::socket_file:
                    treenode_type = DirTree::TreeNode::SOCKET;
                    break;
                case file_type::type_unknown:
                default:
                    treenode_type = DirTree::TreeNode::UNKNOWN;
            }

            if (treenode_type == DirTree::TreeNode::UNKNOWN)
                continue;
            else if (treenode_type == DirTree::TreeNode::DIRECTORY) {
                create_directory(_tmpdir / f.path());

                DirTree::TreeNode dirnode;
                dirnode.type = treenode_type;
                dirnode.name = f.path().filename().string();
                dirnode.size = 0;
                dirnode.mtime = last_write_time(f.path());
                dirnode.host_id = _host_id;
                dirnode.num_links = hard_link_count(f.path());

                auto insert_rtv = parent.children.insert(dirnode);

                traverseDirectory(f, _tmpdir, *(insert_rtv.first));
            } else {
                // create hard link (src, dst)
                create_hard_link(f, _tmpdir / f.path());

                DirTree::TreeNode filenode;
                filenode.type = treenode_type;
                filenode.name = f.path().filename().string();
                filenode.size = file_size(f);
                filenode.mtime = last_write_time(f.path());
                filenode.host_id = _host_id;
                // GSFS create another hard link for files except directory
                filenode.num_links = 1 + hard_link_count(f.path());

                parent.children.insert(filenode);
            }
        }
    };

    traverseDirectory(_dir, _tmpdir, *_dir_tree.root());
}

// returns true on error
bool UserFS::initTCPNetwork(const std::string& addr, const uint16_t port) {
    bool is_master = _host_id == 1;

    bool init_rtv = _tcp_manager.initialize(is_master, addr, port);

    if (init_rtv) return 1;

    _tcp_manager.start();

    // push master's host
    if (is_master)
        _hosts.push(_hosts[0]);
    // else wait for master's recognition or rejection
    else {
        std::string dir_tree_seq;
        std::string host_seq;

        {
            boost::shared_lock< boost::shared_mutex > lock(_access);
            dir_tree_seq = DirTree::serialize(_dir_tree);
            host_seq = Hosts::Host::serialize(_hosts[0]);
        }

        std::string dir_tree_seq_len = host_to_network_64(dir_tree_seq.length());
        std::string host_seq_len = host_to_network_64(host_seq.length());
        std::string protocol_type = host_to_network_64(0x00);

        std::string message = protocol_type +
                              dir_tree_seq_len + dir_tree_seq +
                              host_seq_len + host_seq;

        _tcp_manager.write(message);

        _slave_wait_sem.wait();
    }

    return 0;
}

const DirTree::TreeNode* UserFS::find(const std::string& path) {
    boost::shared_lock< boost::shared_mutex > lock(_access);
    return _dir_tree.find(path);
}

// returns num of bytes read on success
// returns < 0 on error
intmax_t UserFS::read(const uint64_t node_id, const std::string path,
              const size_t offset, const size_t size, char* buff) {
    // remote node isn't inserted into ssh manager
    if (!_ssh_manager.findHost(node_id)) {
        bool rtv = _ssh_manager.insertHost(node_id, _hosts[node_id].address, _hosts[node_id].ssh_port);
        if (rtv) return -1;
    }

    boost::filesystem::path remote_path = _hosts[node_id].tmpdir;
    remote_path /= _hosts[node_id].mountdir;
    remote_path /= path;

    std::string remote_path_string = remote_path.string();

    // read local file
    if (node_id == _host_id) {
        std::ifstream fin(remote_path_string);
        fin.seekg(offset);
        fin.read(buff, size);
        if (fin.fail() || fin.bad()) return -1;
        size_t bytes_read = fin.gcount();
        return bytes_read;
    }

    // read remote file
    return _ssh_manager.read(node_id, remote_path_string, offset, size, buff);
}

// send update packet to all slaves
void UserFS::sendUpdate() {
    std::string dir_tree_seq;
    std::string hosts_seq;

    {
        boost::shared_lock< boost::shared_mutex > lock(_access);
        dir_tree_seq = DirTree::serialize(_dir_tree);
        hosts_seq = Hosts::serialize(_hosts);
    }

    sendUpdate(dir_tree_seq, hosts_seq);
}

void UserFS::sendUpdate(const std::string& dir_tree_seq, const std::string& hosts_seq) {
    std::string message = host_to_network_64(0x02);
    message += host_to_network_64(dir_tree_seq.length());
    message += dir_tree_seq;
    message += host_to_network_64(hosts_seq.length());
    message += hosts_seq;

    // send to all slaves
    _tcp_manager.write(message);
}

// Callback Functions for slaves' tcp manager:

// slave get recognized from master
void UserFS::slaveRecognized(const uint64_t slave_id, const std::string& dir_tree_seq, const std::string& hosts_seq) {
    // deploy dir tree
    DirTree merged_tree = DirTree::deserialize(dir_tree_seq);

    // deploy hosts
    _host_id = slave_id;
    Hosts merged_hosts = Hosts::deserialize(hosts_seq);

    {
        boost::unique_lock< boost::shared_mutex > lock(_access);
        _dir_tree.root()->children = merged_tree.root()->children;
        _hosts = merged_hosts;
    }
    // wake up main thread
    _slave_wait_sem.post();
}

// master sent a update packet, update dirtree and hosts
void UserFS::updateInfo(const std::string& dir_tree_seq, const std::string& hosts_seq) {
    DirTree new_tree = DirTree::deserialize(dir_tree_seq);
    Hosts merged_hosts = Hosts::deserialize(hosts_seq);

    {
        boost::unique_lock< boost::shared_mutex > lock(_access);
        _dir_tree.root()->children = new_tree.root()->children;
        _hosts = merged_hosts;
    }
}

// connect failed or slave disconnect from master
void UserFS::disconnect() {
    // clear dir tree
    {
        boost::unique_lock< boost::shared_mutex > lock(_access);
        _dir_tree.removeNotOf(_host_id);
    }
}

// Callback Functions for master' tcp manager:

// slave disconnect from master
void UserFS::disconnect(const TCPMasterMessager::Connection::iterator handle) {
    uint64_t& slave_id = std::get<4>(*handle);

    // slave is initializting
    if (slave_id == 0) return;

    // remove this slave's node in dir tree
    {
        boost::unique_lock< boost::shared_mutex > lock(_access);
        _dir_tree.removeOf(slave_id);
    }

    slave_id = 0;
    sendUpdate();
}

// new slave coming, chekc dirtree, allocate host_id, merge dir_tree and hosts
void UserFS::newConnection(const std::string& dir_tree_seq,
                   const std::string& host_seq,
                   const TCPMasterMessager::Connection::iterator handle) {
    // deserialize
    DirTree slave_dir_tree = DirTree::deserialize(dir_tree_seq);
    Hosts::Host slave_host = Hosts::Host::deserialize(host_seq);

    // check conflicts
    std::vector<std::string> conflicts;

    {
       boost::shared_lock< boost::shared_mutex > lock(_access);
       conflicts = _dir_tree.hasConflict(slave_dir_tree);
    }

    // there's conflict, close connection
    if (conflicts.size()) return _tcp_manager.close(handle);
    // else

    // alloc slave id
    uint64_t slave_id = _max_host_id++;
    slave_host.id = slave_id;
    slave_dir_tree.root()->setHostID(slave_id);

    std::get<4>(*handle) = slave_id;

    {
        boost::unique_lock< boost::shared_mutex > lock(_access);

        // merge dir tree
        _dir_tree.merge(slave_dir_tree);

        // merge host
        _hosts.push(slave_host);
    }

    // construct response message

    std::string merged_dir_tree_seq;
    std::string merged_hosts_seq;

    {
        boost::shared_lock< boost::shared_mutex > lock(_access);
        merged_dir_tree_seq = DirTree::serialize(_dir_tree);
        merged_hosts_seq = Hosts::serialize(_hosts);
    }

    std::string merged_dir_tree_seq_len = host_to_network_64(merged_dir_tree_seq.length());
    std::string merged_hosts_seq_len = host_to_network_64(merged_hosts_seq.length());
    std::string protocol_type = host_to_network_64(0x01);
    std::string slave_id_seq = host_to_network_64(slave_id);

    std::string message = protocol_type + slave_id_seq +
                          merged_dir_tree_seq_len + merged_dir_tree_seq +
                          merged_hosts_seq_len + merged_hosts_seq;

    // send to slave
    _tcp_manager.writeTo(message, handle);
    sendUpdate(merged_dir_tree_seq, merged_hosts_seq);
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbVirtualDimensionality.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingStatisticsVectorImageFilter.h"

const unsigned int Dimension = 2;
typedef double PixelType;

typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType;

typedef otb::VirtualDimensionality<double> VDType;

int otbVirtualDimensionalityNewTest(int argc, char * argv[])
{
  VDType::Pointer vd = VDType::New();
  std::cout << vd << std::endl;
  return EXIT_SUCCESS;
}

int otbVirtualDimensionalityTest(int argc, char * argv[])
{
  const char * infname = argv[1];
  const char * outfname = argv[2];
  double far = atof(argv[3]); // False Alarm Rate

  StreamingStatisticsVectorImageFilterType::Pointer stats = StreamingStatisticsVectorImageFilterType::New();

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(infname);

  stats->SetInput(reader->GetOutput());
  stats->Update();

  VDType::Pointer vd = VDType::New();
  vd->SetCovariance(stats->GetCovariance().GetVnlMatrix());
  vd->SetCorrelation(stats->GetCorrelation().GetVnlMatrix());
  vd->SetNumberOfPixels(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels());

  std::ofstream file;
  file.open(outfname);
  file.precision(5);

  for (int i = 2; i < 10; ++i)
    {
    double far = vcl_pow(static_cast<double>(10),static_cast<double>(-i));
    vd->SetFAR(far);
    vd->Compute();

    std::cout << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl;
    file << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl;
    }

  file.close();

  return EXIT_SUCCESS;
}
<commit_msg>STYLE<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbVirtualDimensionality.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingStatisticsVectorImageFilter.h"

const unsigned int Dimension = 2;
typedef double PixelType;

typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType;

typedef otb::VirtualDimensionality<double> VDType;

int otbVirtualDimensionalityNewTest(int argc, char * argv[])
{
  VDType::Pointer vd = VDType::New();
  std::cout << vd << std::endl;
  return EXIT_SUCCESS;
}

int otbVirtualDimensionalityTest(int argc, char * argv[])
{
  const char * infname = argv[1];
  const char * outfname = argv[2];
  double far = atof(argv[3]); // False Alarm Rate

  StreamingStatisticsVectorImageFilterType::Pointer stats = StreamingStatisticsVectorImageFilterType::New();

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(infname);

  stats->SetInput(reader->GetOutput());
  stats->Update();

  VDType::Pointer vd = VDType::New();
  vd->SetCovariance(stats->GetCovariance().GetVnlMatrix());
  vd->SetCorrelation(stats->GetCorrelation().GetVnlMatrix());
  vd->SetNumberOfPixels(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels());

  std::ofstream file;
  file.open(outfname);
  file.precision(5);

  for (int i = 2; i < 10; ++i)
    {
    double far = vcl_pow(static_cast<double>(10), static_cast<double>(-i));
    vd->SetFAR(far);
    vd->Compute();

    std::cout << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl;
    file << "FAR : 1E-" << i << " -> Nb Endmembers: " << vd->GetNumberOfEndmembers() << std::endl;
    }

  file.close();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef EBITEN_GRAPHICS_TEXTURE_HPP
#define EBITEN_GRAPHICS_TEXTURE_HPP

#include "ebiten/platform.hpp"

#ifdef EBITEN_MACOSX
#include "ebiten/graphics/detail/opengl/texture_id.hpp"
#endif

namespace ebiten {
namespace graphics {

typedef detail::texture_id texture_id;

class texture {
private:
  texture_id id_;
  std::size_t width_;
  std::size_t height_;
public:
  // TODO: Is 0 a magic number?
  texture()
    : id_(0),
      width_(0),
      height_(0) {
  }
  texture(texture const&) = default;
  texture& operator=(texture const&) = default;
  texture(texture_id const& id_,
          std::size_t width_,
          std::size_t height_)
    : id_(id_),
      width_(width_),
      height_(height_) {
  }
  texture_id
  id() const {
    return this->id_;
  }
  std::size_t
  width() const {
    return this->width_;
  }
  std::size_t
  height() const {
    return this->height_;
  }
  operator bool() const {
    return this->id_ != 0;
  }
};

}
}

#endif
<commit_msg>Added comments<commit_after>#ifndef EBITEN_GRAPHICS_TEXTURE_HPP
#define EBITEN_GRAPHICS_TEXTURE_HPP

#include "ebiten/platform.hpp"

#ifdef EBITEN_MACOSX
#include "ebiten/graphics/detail/opengl/texture_id.hpp"
#endif

namespace ebiten {
namespace graphics {

typedef detail::texture_id texture_id;

class texture {
private:
  texture_id id_;
  std::size_t width_;
  std::size_t height_;
public:
  // TODO: Is 0 a magic number?
  texture()
    : id_(0),
      width_(0),
      height_(0) {
  }
  texture(texture const&) = default;
  texture& operator=(texture const&) = default;
  texture(texture_id const& id_,
          std::size_t width_,
          std::size_t height_)
    : id_(id_),
      width_(width_),
      height_(height_) {
  }
  texture_id
  id() const {
    return this->id_;
  }
  std::size_t
  width() const {
    return this->width_;
  }
  std::size_t
  height() const {
    return this->height_;
  }
  operator bool() const {
    return this->id_ != 0;
  }
};

}
}

// TODO: implement operator= (with nullptr), swap, and so on?

#endif
<|endoftext|>


<commit_before>// Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     22
#define BUILD_NUMBER      6
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
                 GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
                 is_simulator);
  } else {
    OS::SNPrintF(str, "%d.%d.%d%s%s",
                 GetMajor(), GetMinor(), GetBuild(), candidate,
                 is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    OS::SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>Prepare push to trunk.  Now working on version 3.22.7.<commit_after>// Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     22
#define BUILD_NUMBER      7
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
                 GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
                 is_simulator);
  } else {
    OS::SNPrintF(str, "%d.%d.%d%s%s",
                 GetMajor(), GetMinor(), GetBuild(), candidate,
                 is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    OS::SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>