<commit_before>/*****************************************************************************
 * vlcpeer.cpp: scriptable peer descriptor
 *****************************************************************************
 * Copyright (C) 2002-2005 the VideoLAN team
 * $Id$
 *
 * Authors: Samuel Hocevar <sam@zoy.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include "config.h"

#include <vlc/vlc.h>

#ifdef DEBUG
/* We do not want to use nsDebug.h */
#   undef DEBUG
#endif

#ifdef HAVE_MOZILLA_CONFIG_H
#   include <mozilla-config.h>
#endif
#include <nsISupports.h>
#include <nsMemory.h>
#include <npapi.h>

#if !defined(XP_MACOSX) && !defined(XP_UNIX) && !defined(XP_WIN)
#define XP_UNIX 1
#elif defined(XP_MACOSX)
#undef XP_UNIX
#endif

#include "vlcpeer.h"
#include "vlcplugin.h"

NS_IMPL_ISUPPORTS2( VlcPeer, VlcIntf, nsIClassInfo )

/*****************************************************************************
 * Scriptable peer constructor and destructor
 *****************************************************************************/
VlcPeer::VlcPeer()
{
    NS_INIT_ISUPPORTS();
}

VlcPeer::VlcPeer( VlcPlugin * plugin )
{
    NS_INIT_ISUPPORTS();
    p_plugin = plugin;
}

VlcPeer::~VlcPeer()
{
    ;
}

/*****************************************************************************
 * Scriptable peer methods
 *****************************************************************************/
void VlcPeer::Disable()
{
    p_plugin = NULL;
}

/*****************************************************************************
 * Scriptable peer plugin methods
 *****************************************************************************/
NS_IMETHODIMP VlcPeer::Play()
{
    if( p_plugin )
    {
        if( !p_plugin->b_stream && p_plugin->psz_target )
        {
            VLC_AddTarget( p_plugin->i_vlc, p_plugin->psz_target, 0, 0,
                           PLAYLIST_APPEND | PLAYLIST_GO, PLAYLIST_END );
            p_plugin->b_stream = 1;
        }

        VLC_Play( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Pause()
{
    if( p_plugin )
    {
        VLC_Pause( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Stop()
{
    if( p_plugin )
    {
        VLC_Stop( p_plugin->i_vlc );
        p_plugin->b_stream = 0;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Fullscreen()
{
    if( p_plugin )
    {
#ifdef XP_MACOSX
#else
        VLC_FullScreen( p_plugin->i_vlc );
#endif
    }
    return NS_OK;
}

/* Set/Get vlc variables */
NS_IMETHODIMP VlcPeer::Set_int_variable(const char *psz_var, PRInt64 value )
{
    vlc_value_t val;
    val.i_int = value;
    if( p_plugin )
    {
        VLC_VariableSet( p_plugin->i_vlc, psz_var, val );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_str_variable(const char *psz_var, const char *value )
{
    vlc_value_t val;
    val.psz_string = strdup( value );
    if( p_plugin )
    {
        VLC_VariableSet( p_plugin->i_vlc, psz_var, val );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_bool_variable(const char *psz_var, PRBool value )
{
    vlc_value_t val;
    val.b_bool = value >= 1 ? VLC_TRUE : VLC_FALSE;
    if( p_plugin )
    {
        VLC_VariableSet( p_plugin->i_vlc, psz_var, val );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_int_variable( const char *psz_var, PRInt64 *result )
{
    vlc_value_t val;
    if( p_plugin )
    {
        fprintf(stderr, "Choppage de %s\n", psz_var );
        VLC_VariableGet( p_plugin->i_vlc, psz_var, &val );
        fprintf(stderr, "Valeur %i\n", val.i_int );
        *result = (PRInt64)val.i_int;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_bool_variable(  const char *psz_var,PRBool *result )
{
    vlc_value_t val;
    if( p_plugin )
    {
        VLC_VariableGet( p_plugin->i_vlc, psz_var, &val );
        *result = (PRBool)val.b_bool;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_str_variable( const char *psz_var, char **result )
{
    vlc_value_t val;
    if( p_plugin )
    {
        fprintf(stderr, "Choppage de %s\n", psz_var );
        VLC_VariableGet( p_plugin->i_vlc, psz_var, &val );
        if( val.psz_string )
        {
            *result = strdup( val.psz_string );
        }
        else
        {
            *result = strdup( "" );
        }
    }
    return NS_OK;
}

/* Playlist control */
NS_IMETHODIMP VlcPeer::Clear_playlist()
{
    if( p_plugin )
    {
        VLC_PlaylistClear( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Add_item( const char *psz_item )
{
     if( p_plugin )
     {
          VLC_AddTarget( p_plugin->i_vlc, psz_item, NULL, 0,
                         PLAYLIST_APPEND, PLAYLIST_END);
     }
     return NS_OK;
}

NS_IMETHODIMP VlcPeer::Isplaying( PRBool *b_playing )
{
    if( p_plugin->i_vlc )
    {
        *b_playing = VLC_IsPlaying( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_position( PRInt64 *i_position )
{
    if( p_plugin->i_vlc )
    {
        *i_position = (PRInt64)VLC_PositionGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_time( PRInt64 *i_time )
{
    if( p_plugin->i_vlc )
    {
        *i_time = VLC_TimeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_length( PRInt64 *i_length )
{
    if( p_plugin->i_vlc )
    {
        *i_length = VLC_LengthGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Seek( PRInt64 i_secs, PRInt64 b_relative )
{
    if( p_plugin->i_vlc )
    {
        VLC_TimeSet( p_plugin->i_vlc, i_secs, b_relative );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Next()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistNext( p_plugin->i_vlc);
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Previous()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistPrev( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_volume( PRInt64 i_volume )
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeSet( p_plugin->i_vlc, i_volume );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_volume( PRInt64 *i_volume )
{
    if( p_plugin->i_vlc )
    {
        *i_volume = VLC_VolumeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Mute()
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeMute( p_plugin->i_vlc );
    }
    return NS_OK;
}
<commit_msg>Remove debug (Refs:#438)<commit_after>/*****************************************************************************
 * vlcpeer.cpp: scriptable peer descriptor
 *****************************************************************************
 * Copyright (C) 2002-2005 the VideoLAN team
 * $Id$
 *
 * Authors: Samuel Hocevar <sam@zoy.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include "config.h"

#include <vlc/vlc.h>

#ifdef DEBUG
/* We do not want to use nsDebug.h */
#   undef DEBUG
#endif

#ifdef HAVE_MOZILLA_CONFIG_H
#   include <mozilla-config.h>
#endif
#include <nsISupports.h>
#include <nsMemory.h>
#include <npapi.h>

#if !defined(XP_MACOSX) && !defined(XP_UNIX) && !defined(XP_WIN)
#define XP_UNIX 1
#elif defined(XP_MACOSX)
#undef XP_UNIX
#endif

#include "vlcpeer.h"
#include "vlcplugin.h"

NS_IMPL_ISUPPORTS2( VlcPeer, VlcIntf, nsIClassInfo )

/*****************************************************************************
 * Scriptable peer constructor and destructor
 *****************************************************************************/
VlcPeer::VlcPeer()
{
    NS_INIT_ISUPPORTS();
}

VlcPeer::VlcPeer( VlcPlugin * plugin )
{
    NS_INIT_ISUPPORTS();
    p_plugin = plugin;
}

VlcPeer::~VlcPeer()
{
    ;
}

/*****************************************************************************
 * Scriptable peer methods
 *****************************************************************************/
void VlcPeer::Disable()
{
    p_plugin = NULL;
}

/*****************************************************************************
 * Scriptable peer plugin methods
 *****************************************************************************/
NS_IMETHODIMP VlcPeer::Play()
{
    if( p_plugin )
    {
        if( !p_plugin->b_stream && p_plugin->psz_target )
        {
            VLC_AddTarget( p_plugin->i_vlc, p_plugin->psz_target, 0, 0,
                           PLAYLIST_APPEND | PLAYLIST_GO, PLAYLIST_END );
            p_plugin->b_stream = 1;
        }

        VLC_Play( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Pause()
{
    if( p_plugin )
    {
        VLC_Pause( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Stop()
{
    if( p_plugin )
    {
        VLC_Stop( p_plugin->i_vlc );
        p_plugin->b_stream = 0;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Fullscreen()
{
    if( p_plugin )
    {
#ifdef XP_MACOSX
#else
        VLC_FullScreen( p_plugin->i_vlc );
#endif
    }
    return NS_OK;
}

/* Set/Get vlc variables */
NS_IMETHODIMP VlcPeer::Set_int_variable(const char *psz_var, PRInt64 value )
{
    vlc_value_t val;
    val.i_int = value;
    if( p_plugin )
    {
        VLC_VariableSet( p_plugin->i_vlc, psz_var, val );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_str_variable(const char *psz_var, const char *value )
{
    vlc_value_t val;
    val.psz_string = strdup( value );
    if( p_plugin )
    {
        VLC_VariableSet( p_plugin->i_vlc, psz_var, val );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_bool_variable(const char *psz_var, PRBool value )
{
    vlc_value_t val;
    val.b_bool = value >= 1 ? VLC_TRUE : VLC_FALSE;
    if( p_plugin )
    {
        VLC_VariableSet( p_plugin->i_vlc, psz_var, val );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_int_variable( const char *psz_var, PRInt64 *result )
{
    vlc_value_t val;
    if( p_plugin )
    {
        VLC_VariableGet( p_plugin->i_vlc, psz_var, &val );
        *result = (PRInt64)val.i_int;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_bool_variable(  const char *psz_var,PRBool *result )
{
    vlc_value_t val;
    if( p_plugin )
    {
        VLC_VariableGet( p_plugin->i_vlc, psz_var, &val );
        *result = (PRBool)val.b_bool;
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_str_variable( const char *psz_var, char **result )
{
    vlc_value_t val;
    if( p_plugin )
    {
        VLC_VariableGet( p_plugin->i_vlc, psz_var, &val );
        if( val.psz_string )
        {
            *result = strdup( val.psz_string );
        }
        else
        {
            *result = strdup( "" );
        }
    }
    return NS_OK;
}

/* Playlist control */
NS_IMETHODIMP VlcPeer::Clear_playlist()
{
    if( p_plugin )
    {
        VLC_PlaylistClear( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Add_item( const char *psz_item )
{
     if( p_plugin )
     {
          VLC_AddTarget( p_plugin->i_vlc, psz_item, NULL, 0,
                         PLAYLIST_APPEND, PLAYLIST_END);
     }
     return NS_OK;
}

NS_IMETHODIMP VlcPeer::Isplaying( PRBool *b_playing )
{
    if( p_plugin->i_vlc )
    {
        *b_playing = VLC_IsPlaying( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_position( PRInt64 *i_position )
{
    if( p_plugin->i_vlc )
    {
        *i_position = (PRInt64)VLC_PositionGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_time( PRInt64 *i_time )
{
    if( p_plugin->i_vlc )
    {
        *i_time = VLC_TimeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_length( PRInt64 *i_length )
{
    if( p_plugin->i_vlc )
    {
        *i_length = VLC_LengthGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Seek( PRInt64 i_secs, PRInt64 b_relative )
{
    if( p_plugin->i_vlc )
    {
        VLC_TimeSet( p_plugin->i_vlc, i_secs, b_relative );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Next()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistNext( p_plugin->i_vlc);
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Previous()
{
    if( p_plugin->i_vlc )
    {
        VLC_PlaylistPrev( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Set_volume( PRInt64 i_volume )
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeSet( p_plugin->i_vlc, i_volume );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Get_volume( PRInt64 *i_volume )
{
    if( p_plugin->i_vlc )
    {
        *i_volume = VLC_VolumeGet( p_plugin->i_vlc );
    }
    return NS_OK;
}

NS_IMETHODIMP VlcPeer::Mute()
{
    if( p_plugin->i_vlc )
    {
        VLC_VolumeMute( p_plugin->i_vlc );
    }
    return NS_OK;
}
<|endoftext|>


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

/* Author: Ioan Sucan, Mathias Lüdtke, Dave Coleman */

// MoveIt
#include <moveit/rdf_loader/rdf_loader.h>
#include <moveit/profiler/profiler.h>

// ROS
#include <ros/ros.h>
#include <ros/package.h>

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

// C++
#include <fstream>
#include <streambuf>
#include <algorithm>

#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#endif

rdf_loader::RDFLoader::RDFLoader(const std::string& robot_description)
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("RDFLoader(robot_description)");

  ros::WallTime start = ros::WallTime::now();
  ros::NodeHandle nh("~");
  std::string content;

  if (!nh.searchParam(robot_description, robot_description_) || !nh.getParam(robot_description_, content))
  {
    ROS_ERROR_NAMED("rdf_loader", "Robot model parameter not found! Did you remap '%s'?", robot_description.c_str());
    return;
  }

  urdf::Model* umodel = new urdf::Model();
  if (!umodel->initString(content))
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to parse URDF from parameter '%s'", robot_description_.c_str());
    return;
  }
  urdf_.reset(umodel);

  const std::string srdf_description(robot_description_ + "_semantic");
  std::string scontent;
  if (!nh.getParam(srdf_description, scontent))
  {
    ROS_ERROR_NAMED("rdf_loader", "Robot semantic description not found. Did you forget to define or remap '%s'?",
                    srdf_description.c_str());
    return;
  }

  srdf_.reset(new srdf::Model());
  if (!srdf_->initString(*urdf_, scontent))
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to parse SRDF from parameter '%s'", srdf_description.c_str());
    srdf_.reset();
    return;
  }

  ROS_DEBUG_STREAM_NAMED("rdf", "Loaded robot model in " << (ros::WallTime::now() - start).toSec() << " seconds");
}

rdf_loader::RDFLoader::RDFLoader(const std::string& urdf_string, const std::string& srdf_string)
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("RDFLoader(string)");

  urdf::Model* umodel = new urdf::Model();
  urdf_.reset(umodel);
  if (umodel->initString(urdf_string))
  {
    srdf_.reset(new srdf::Model());
    if (!srdf_->initString(*urdf_, srdf_string))
    {
      ROS_ERROR_NAMED("rdf_loader", "Unable to parse SRDF");
      srdf_.reset();
    }
  }
  else
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to parse URDF");
    urdf_.reset();
  }
}

bool rdf_loader::RDFLoader::isXacroFile(const std::string& path)
{
  std::string lower_path = path;
  std::transform(lower_path.begin(), lower_path.end(), lower_path.begin(), ::tolower);

  return lower_path.find(".xacro") != std::string::npos;
}

bool rdf_loader::RDFLoader::loadFileToString(std::string& buffer, const std::string& path)
{
  if (path.empty())
  {
    ROS_ERROR_NAMED("rdf_loader", "Path is empty");
    return false;
  }

  if (!boost::filesystem::exists(path))
  {
    ROS_ERROR_NAMED("rdf_loader", "File does not exist");
    return false;
  }

  std::ifstream stream(path.c_str());
  if (!stream.good())
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to load path");
    return false;
  }

  // Load the file to a string using an efficient memory allocation technique
  stream.seekg(0, std::ios::end);
  buffer.reserve(stream.tellg());
  stream.seekg(0, std::ios::beg);
  buffer.assign((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
  stream.close();

  return true;
}

bool rdf_loader::RDFLoader::loadXacroFileToString(std::string& buffer, const std::string& path,
                                                  const std::vector<std::string>& xacro_args)
{
  if (path.empty())
  {
    ROS_ERROR_NAMED("rdf_loader", "Path is empty");
    return false;
  }

  if (!boost::filesystem::exists(path))
  {
    ROS_ERROR_NAMED("rdf_loader", "File does not exist");
    return false;
  }

  std::string cmd = "rosrun xacro xacro ";
  for (const std::string& xacro_arg : xacro_args)
    cmd += xacro_arg + " ";
  cmd += path;

  FILE* pipe = popen(cmd.c_str(), "r");
  if (!pipe)
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to load path");
    return false;
  }

  char pipe_buffer[128];
  while (!feof(pipe))
  {
    if (fgets(pipe_buffer, 128, pipe) != nullptr)
      buffer += pipe_buffer;
  }
  pclose(pipe);

  return true;
}

bool rdf_loader::RDFLoader::loadXmlFileToString(std::string& buffer, const std::string& path,
                                                const std::vector<std::string>& xacro_args)
{
  if (isXacroFile(path))
  {
    return loadXacroFileToString(buffer, path, xacro_args);
  }

  return loadFileToString(buffer, path);
}

bool rdf_loader::RDFLoader::loadPkgFileToString(std::string& buffer, const std::string& package_name,
                                                const std::string& relative_path,
                                                const std::vector<std::string>& xacro_args)
{
  std::string package_path = ros::package::getPath(package_name);

  if (package_path.empty())
  {
    ROS_ERROR_STREAM_NAMED("rdf_loader", "ROS was unable to find the package name '" << package_name << "'");
    return false;
  }

  boost::filesystem::path path(package_path);
  // Use boost to cross-platform combine paths
  path = path / relative_path;

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

/* Author: Ioan Sucan, Mathias Lüdtke, Dave Coleman */

// MoveIt
#include <moveit/rdf_loader/rdf_loader.h>
#include <moveit/profiler/profiler.h>

// ROS
#include <ros/ros.h>
#include <ros/package.h>

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

// C++
#include <fstream>
#include <streambuf>
#include <algorithm>

#ifdef _WIN32
#define popen _popen
#define pclose _pclose
#endif

rdf_loader::RDFLoader::RDFLoader(const std::string& robot_description)
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("RDFLoader(robot_description)");

  ros::WallTime start = ros::WallTime::now();
  ros::NodeHandle nh("~");
  std::string content;

  if (!nh.searchParam(robot_description, robot_description_) || !nh.getParam(robot_description_, content))
  {
    ROS_ERROR_NAMED("rdf_loader", "Robot model parameter not found! Did you remap '%s'?", robot_description.c_str());
    return;
  }

  std::unique_ptr<urdf::Model> urdf(new urdf::Model());
  if (!urdf->initString(content))
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to parse URDF from parameter '%s'", robot_description_.c_str());
    return;
  }
  urdf_ = std::move(urdf);

  const std::string srdf_description(robot_description_ + "_semantic");
  std::string scontent;
  if (!nh.getParam(srdf_description, scontent))
  {
    ROS_ERROR_NAMED("rdf_loader", "Robot semantic description not found. Did you forget to define or remap '%s'?",
                    srdf_description.c_str());
    return;
  }

  srdf::ModelSharedPtr srdf(new srdf::Model());
  if (!srdf->initString(*urdf_, scontent))
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to parse SRDF from parameter '%s'", srdf_description.c_str());
    return;
  }
  srdf_ = std::move(srdf);

  ROS_DEBUG_STREAM_NAMED("rdf", "Loaded robot model in " << (ros::WallTime::now() - start).toSec() << " seconds");
}

rdf_loader::RDFLoader::RDFLoader(const std::string& urdf_string, const std::string& srdf_string)
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("RDFLoader(string)");

  urdf::Model* umodel = new urdf::Model();
  urdf_.reset(umodel);
  if (umodel->initString(urdf_string))
  {
    srdf_.reset(new srdf::Model());
    if (!srdf_->initString(*urdf_, srdf_string))
    {
      ROS_ERROR_NAMED("rdf_loader", "Unable to parse SRDF");
      srdf_.reset();
    }
  }
  else
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to parse URDF");
    urdf_.reset();
  }
}

bool rdf_loader::RDFLoader::isXacroFile(const std::string& path)
{
  std::string lower_path = path;
  std::transform(lower_path.begin(), lower_path.end(), lower_path.begin(), ::tolower);

  return lower_path.find(".xacro") != std::string::npos;
}

bool rdf_loader::RDFLoader::loadFileToString(std::string& buffer, const std::string& path)
{
  if (path.empty())
  {
    ROS_ERROR_NAMED("rdf_loader", "Path is empty");
    return false;
  }

  if (!boost::filesystem::exists(path))
  {
    ROS_ERROR_NAMED("rdf_loader", "File does not exist");
    return false;
  }

  std::ifstream stream(path.c_str());
  if (!stream.good())
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to load path");
    return false;
  }

  // Load the file to a string using an efficient memory allocation technique
  stream.seekg(0, std::ios::end);
  buffer.reserve(stream.tellg());
  stream.seekg(0, std::ios::beg);
  buffer.assign((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
  stream.close();

  return true;
}

bool rdf_loader::RDFLoader::loadXacroFileToString(std::string& buffer, const std::string& path,
                                                  const std::vector<std::string>& xacro_args)
{
  if (path.empty())
  {
    ROS_ERROR_NAMED("rdf_loader", "Path is empty");
    return false;
  }

  if (!boost::filesystem::exists(path))
  {
    ROS_ERROR_NAMED("rdf_loader", "File does not exist");
    return false;
  }

  std::string cmd = "rosrun xacro xacro ";
  for (const std::string& xacro_arg : xacro_args)
    cmd += xacro_arg + " ";
  cmd += path;

  FILE* pipe = popen(cmd.c_str(), "r");
  if (!pipe)
  {
    ROS_ERROR_NAMED("rdf_loader", "Unable to load path");
    return false;
  }

  char pipe_buffer[128];
  while (!feof(pipe))
  {
    if (fgets(pipe_buffer, 128, pipe) != nullptr)
      buffer += pipe_buffer;
  }
  pclose(pipe);

  return true;
}

bool rdf_loader::RDFLoader::loadXmlFileToString(std::string& buffer, const std::string& path,
                                                const std::vector<std::string>& xacro_args)
{
  if (isXacroFile(path))
  {
    return loadXacroFileToString(buffer, path, xacro_args);
  }

  return loadFileToString(buffer, path);
}

bool rdf_loader::RDFLoader::loadPkgFileToString(std::string& buffer, const std::string& package_name,
                                                const std::string& relative_path,
                                                const std::vector<std::string>& xacro_args)
{
  std::string package_path = ros::package::getPath(package_name);

  if (package_path.empty())
  {
    ROS_ERROR_STREAM_NAMED("rdf_loader", "ROS was unable to find the package name '" << package_name << "'");
    return false;
  }

  boost::filesystem::path path(package_path);
  // Use boost to cross-platform combine paths
  path = path / relative_path;

  return loadXmlFileToString(buffer, path.string(), xacro_args);
}
<|endoftext|>


<commit_before>#include "rampancy/ClangCompiler.h"

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

namespace rampancy {
   llvm::sys::Path getExecutablePath(const char* argv0) {
      void *MainAddr = (void*) (intptr_t) getExecutablePath;
      return llvm::sys::Path::GetMainExecutable(argv0, MainAddr);
   }
   ClangCompiler::ClangCompiler(CLIPSEnvironment& e, char* const *ep) {
      envp = ep;
      env = &e;
      builder = new KnowledgeConstructor;
   }
   ClangCompiler::~ClangCompiler() {
      if(builder) delete builder;
   }

   void ClangCompiler::resetKnowledgeBuilder() {
      builder->resetInstanceStream();
   }
   int ClangCompiler::execute(llvm::Module* mod, std::vector<std::string>& args, char* functionName) {
      llvm::InitializeNativeTarget();

      std::string error;
      std::vector<std::string>::iterator it;
      it = args.begin();
      OwningPtr<llvm::ExecutionEngine> ee(
            llvm::ExecutionEngine::createJIT(mod, &error));
      if(!ee) {
         llvm::errs() << "unable to make execution engine: " << error << '\n';
         return 255;
      }
      llvm::Function* entryFunction = mod->getFunction(functionName);
      if(!entryFunction) {
         llvm::errs() << functionName << " function not found in module.\n";
         return 255;
      }
      args.insert(it, mod->getModuleIdentifier());
      return ee->runFunctionAsMain(entryFunction, args, envp);
   }
   int ClangCompiler::executeMain(llvm::Module* mod, std::vector<std::string>& args) {
      return execute(mod, args, "main");
   }

   llvm::Module* ClangCompiler::compile(int argc, const char **argv, bool constructKnowledge) {
      resetKnowledgeBuilder();

      void* mainAddr = (void*) (intptr_t) getExecutablePath;
      llvm::sys::Path path = getExecutablePath(argv[0]);
      TextDiagnosticPrinter* diagClient = new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
      IntrusiveRefCntPtr<DiagnosticIDs> diagID(new DiagnosticIDs());
      DiagnosticsEngine diags (diagID, diagClient);
      Driver theDriver(path.str(), llvm::sys::getDefaultTargetTriple(),
            "a.out", false, diags);
      theDriver.setTitle("rampancy knowledge compiler");

      llvm::SmallVector<const char*, 16> args(argv, argv + argc);
      args.push_back("-fsyntax-only");
      //args.push_back("-S");
      OwningPtr<Compilation> c(theDriver.BuildCompilation(args));
      if(!c) return 0;

      const driver::JobList &jobs = c->getJobs();
      if(jobs.size() != 1 || !isa<driver::Command>(*jobs.begin())) {
         SmallString<256> msg;
         llvm::raw_svector_ostream os(msg);
         c->PrintJob(os, c->getJobs(), "; ", true);
         diags.Report(diag::err_fe_expected_compiler_job) << os.str();
         return 0;
      }

      const driver::Command *cmd = cast<driver::Command>(*jobs.begin());
      if(llvm::StringRef(cmd->getCreator().getName()) != "clang") {
         diags.Report(diag::err_fe_expected_clang_command);
         return 0;
      }

      const driver::ArgStringList &ccArgs = cmd->getArguments();
      OwningPtr<CompilerInvocation> ci(new CompilerInvocation);
      CompilerInvocation::CreateFromArgs(*ci,
            const_cast<const char **>(ccArgs.data()),
            const_cast<const char **>(ccArgs.data()) +
            ccArgs.size(),
            diags);
      if(ci->getHeaderSearchOpts().Verbose) {
         llvm::errs() << "rampancy compilation:\n";
         llvm::errs() << "  clang invocation:\n";
         c->PrintJob(llvm::errs(), c->getJobs(), "\n", true);
         llvm::errs() << "\n";
      }

      CompilerInstance clang;
      clang.setInvocation(ci.take());

      clang.createDiagnostics(int(ccArgs.size()),
            const_cast<char**>(ccArgs.data()));
      if(!clang.hasDiagnostics())
         return 0;
      if(clang.getHeaderSearchOpts().UseBuiltinIncludes &&
            clang.getHeaderSearchOpts().ResourceDir.empty()) {
         clang.getHeaderSearchOpts().ResourceDir =
            CompilerInvocation::GetResourcesPath(argv[0], mainAddr);
      }

      OwningPtr<CodeGenAction> act(new EmitLLVMOnlyAction());
      if(!clang.ExecuteAction(*act))
         return 0;
      llvm::Module* module = act->takeModule();
      if(module && constructKnowledge) {
         builder->route(module);
         std::string result = getCompleteKnowledgeString();
         env->makeInstances((char*)result.c_str());
      }
      return module;
   }
   std::string ClangCompiler::getCompleteKnowledgeString() {
      return builder->getInstancesAsString();
   }
}

<commit_msg>Finished updating the ClangCompiler.<commit_after>#include "rampancy/ClangCompiler.h"

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

namespace rampancy {
#define msg(a) (char*) a
   llvm::sys::Path getExecutablePath(const char* argv0) {
      void *MainAddr = (void*) (intptr_t) getExecutablePath;
      return llvm::sys::Path::GetMainExecutable(argv0, MainAddr);
   }
   const char* ClangCompiler::getArgv0() {
      return argv0;
   }
   void ClangCompiler::setArgv0(const char* arg0) {
      argv0 = arg0;
   }
   ClangCompiler::ClangCompiler() : Compiler(ID) { }
   llvm::Module* ClangCompiler::compile() {
      void* theEnv = getEnvironment()->getEnvironment();
      DATA_OBJECT multifield;
      //if we've gotten this far then it's safe to say the routing was
      //successful
      if(!EnvArgTypeCheck(theEnv, msg("compile"), 2, MULTIFIELD,
               &multifield)) {
         EnvPrintRouter(theEnv, msg("werror"),
               msg("\nThe second argument must be a multifield!\n"));
         return 0;
      }
      //if we don't have any args then just kick back
      if(GetDOLength(multifield) == 0) {
         EnvPrintRouter(theEnv, msg("werror"),
               msg("\nNo arguments provided!\n"));
         return 0;
      }
      void* mainAddr = (void*) (intptr_t) getExecutablePath;
      llvm::sys::Path path = getExecutablePath(getArgv0());
      TextDiagnosticPrinter* diagClient =
         new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
      IntrusiveRefCntPtr<DiagnosticIDs> diagID(new DiagnosticIDs());
      DiagnosticsEngine diags (diagID, diagClient);
      Driver theDriver(path.str(), llvm::sys::getDefaultTargetTriple(),
            "a.out", false, diags);
      theDriver.setTitle("rampancy knowledge compiler");

      llvm::SmallVector<const char*, 16> args;
      void* mfptr = GetValue(multifield);
      int mfEnd = GetDOEnd(multifield);
      for(int i = GetDOBegin(multifield); i <= mfEnd; ++i) {
         int mfType = GetMFType(mfptr, i);
         if(mfType == STRING || mfType == SYMBOL) {
            //we need to do this to prevent the CLIPS gc from crashing the
            //party.
            std::string argument(ValueToString(GetMFValue(mfptr, i)));
            args.push_back(argument.c_str());
         } else if(mfType == INTEGER) {
            char* arg = CharBuffer(256);
            sprintf(arg, "%lld", ValueToLong(GetMFValue(mfptr, i)));
            std::string argument(arg);
            free(arg);
            args.push_back(argument.c_str());
         } else if(mfType == FLOAT) {
            char* arg = CharBuffer(256);
            sprintf(arg, "%f", ValueToDouble(GetMFValue(mfptr, i)));
            std::string argument(arg);
            free(arg);
            args.push_back(argument.c_str());
         } else {
            EnvPrintRouter(theEnv, msg("werror"),
                  msg("\nFound an argument that was not a string, symbol, or number\n"));
            return 0;
         }
      }
      //we need to iterate through the multifield
      //we have our
      args.push_back("-fsyntax-only");
      OwningPtr<Compilation> c(theDriver.BuildCompilation(args));
      if(!c) return 0;

      const driver::JobList &jobs = c->getJobs();
      if(jobs.size() != 1 || !isa<driver::Command>(*jobs.begin())) {
         SmallString<256> msg;
         llvm::raw_svector_ostream os(msg);
         c->PrintJob(os, c->getJobs(), "; ", true);
         diags.Report(diag::err_fe_expected_compiler_job) << os.str();
         return 0;
      }

      const driver::Command *cmd = cast<driver::Command>(*jobs.begin());
      if(llvm::StringRef(cmd->getCreator().getName()) != "clang") {
         diags.Report(diag::err_fe_expected_clang_command);
         return 0;
      }

      const driver::ArgStringList &ccArgs = cmd->getArguments();
      OwningPtr<CompilerInvocation> ci(new CompilerInvocation);
      CompilerInvocation::CreateFromArgs(*ci,
            const_cast<const char **>(ccArgs.data()),
            const_cast<const char **>(ccArgs.data()) +
            ccArgs.size(),
            diags);
      if(ci->getHeaderSearchOpts().Verbose) {
         llvm::errs() << "rampancy compilation:\n";
         llvm::errs() << "  clang invocation:\n";
         c->PrintJob(llvm::errs(), c->getJobs(), "\n", true);
         llvm::errs() << "\n";
      }

      CompilerInstance clang;
      clang.setInvocation(ci.take());

      clang.createDiagnostics(int(ccArgs.size()),
            const_cast<char**>(ccArgs.data()));
      if(!clang.hasDiagnostics())
         return 0;
      if(clang.getHeaderSearchOpts().UseBuiltinIncludes &&
            clang.getHeaderSearchOpts().ResourceDir.empty()) {
         clang.getHeaderSearchOpts().ResourceDir =
            CompilerInvocation::GetResourcesPath(getArgv0(), mainAddr);
      }

      OwningPtr<CodeGenAction> act(new EmitLLVMOnlyAction(getContext()));
      if(!clang.ExecuteAction(*act))
         return 0;
      return act->takeModule();
   }

   llvm::Module* ClangCompiler::compile(int argc, char **argv) {
      void* mainAddr = (void*) (intptr_t) getExecutablePath;
      llvm::sys::Path path = getExecutablePath(argv[0]);
      TextDiagnosticPrinter* diagClient = new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
      IntrusiveRefCntPtr<DiagnosticIDs> diagID(new DiagnosticIDs());
      DiagnosticsEngine diags (diagID, diagClient);
      Driver theDriver(path.str(), llvm::sys::getDefaultTargetTriple(),
            "a.out", false, diags);
      theDriver.setTitle("rampancy knowledge compiler");

      llvm::SmallVector<const char*, 16> args(argv, argv + argc);
      args.push_back("-fsyntax-only");
      //args.push_back("-S");
      OwningPtr<Compilation> c(theDriver.BuildCompilation(args));
      if(!c) return 0;

      const driver::JobList &jobs = c->getJobs();
      if(jobs.size() != 1 || !isa<driver::Command>(*jobs.begin())) {
         SmallString<256> msg;
         llvm::raw_svector_ostream os(msg);
         c->PrintJob(os, c->getJobs(), "; ", true);
         diags.Report(diag::err_fe_expected_compiler_job) << os.str();
         return 0;
      }

      const driver::Command *cmd = cast<driver::Command>(*jobs.begin());
      if(llvm::StringRef(cmd->getCreator().getName()) != "clang") {
         diags.Report(diag::err_fe_expected_clang_command);
         return 0;
      }

      const driver::ArgStringList &ccArgs = cmd->getArguments();
      OwningPtr<CompilerInvocation> ci(new CompilerInvocation);
      CompilerInvocation::CreateFromArgs(*ci,
            const_cast<const char **>(ccArgs.data()),
            const_cast<const char **>(ccArgs.data()) +
            ccArgs.size(),
            diags);
      if(ci->getHeaderSearchOpts().Verbose) {
         llvm::errs() << "rampancy compilation:\n";
         llvm::errs() << "  clang invocation:\n";
         c->PrintJob(llvm::errs(), c->getJobs(), "\n", true);
         llvm::errs() << "\n";
      }

      CompilerInstance clang;
      clang.setInvocation(ci.take());

      clang.createDiagnostics(int(ccArgs.size()),
            const_cast<char**>(ccArgs.data()));
      if(!clang.hasDiagnostics())
         return 0;
      if(clang.getHeaderSearchOpts().UseBuiltinIncludes &&
            clang.getHeaderSearchOpts().ResourceDir.empty()) {
         clang.getHeaderSearchOpts().ResourceDir =
            CompilerInvocation::GetResourcesPath(argv[0], mainAddr);
      }

      OwningPtr<CodeGenAction> act(new EmitLLVMOnlyAction(getContext()));
      if(!clang.ExecuteAction(*act))
         return 0;
      return act->takeModule();
   }
   llvm::Module* ClangCompiler::interpret() {
      EnvPrintRouter(getEnvironment()->getEnvironment(),
            msg("werror"),
            msg("\nInterpreting code isn't supported with clang!\n"));
      return 0;
   }
   llvm::Module* ClangCompiler::interpret(llvm::StringRef input) {
      EnvPrintRouter(getEnvironment()->getEnvironment(),
            msg("werror"),
            msg("\nInterpreting code isn't supported with clang!\n"));
      return 0;
   }
#undef msg
}

<|endoftext|>


<commit_before>/**
 * Exercise 2 : Read in a xml-file, validate via sheme and generate a csv with the values.
 *
 * @author FirstSanny
 */

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <vector>

#include "MeasurePointFromDocumentReader.h"
#include "XMLParser.h"
#include "MeasurePoint.h"

namespace {

	const char* SEPERATOR = "; ";

	const char* URL_MEASURED_XSD = "http://gaslab.zib.de/kwpt/measured";
	const char* FILE_MEASURED_XSD = "measured-1-1-0.xsd";
//	const char* FILE_FRAMEWORK_XSD = "Framework-1-1-0.xsd";
//	const char* FILE_PHYSICS_XSD = "PhysicalValues-1-1-0.xsd";
//	const char* FILE_TOPO_XSD = "Topology-1-1-0.xsd";
//	const char* FILE_PROG_XSD = "prognosis-1-1-0.xsd";

}

using namespace std;

/** Printing a Exception with "Exception:\n message \n" */
void inline printException(const XMLException& toCatch) {
	char* message = XMLString::transcode(toCatch.getMessage());
	cerr << "Exception:" << endl << message << endl;
	XMLString::release(&message);
}

/** Reading in a File, try to parse and validate against sheme */
int main(int argn, char *argv[]) {

	if (argn <= 1) {
		cerr << "ERROR : There was no filename" << endl;
		return 1;
	}

	string filename = argv[1];
	cout << "Going to parse the file " << filename << endl;

	try {
	    XMLPlatformUtils::Initialize();
	}catch (const XMLException& toCatch) {
		cerr << "ERROR : Couldn't initialize XML-Parser"<<endl;
		printException(toCatch);
		return 0;
	}

	XMLParser* parser = new XMLParser();

	cout << "Successfull initialized" << endl;

	try {

		string shemaLoc = URL_MEASURED_XSD;
		shemaLoc = shemaLoc + " " + FILE_MEASURED_XSD;
		parser->setExternalSchemaLocation(shemaLoc.c_str());
		cout << "Validationfile: "<< FILE_MEASURED_XSD << endl;

		parser->parse(argv[1]);
		cout << "File validated and parsed to DOM" << endl;

		if(parser->getErrorCount() != 0){
		  cerr << "WARNING : File doesn't match sheme" << endl;
		  cerr << "There were " << parser->getErrorCount() << " errors." << endl;
		}
		cerr << parser->getErrors();

		MeasurePointFromDocumentReader* measurePointsReader = new MeasurePointFromDocumentReader(parser->getDocument());
		measurePointsReader->readMeasurepoints();
		vector<MeasurePoint*> measurePoints = measurePointsReader->getMeasurePoints();
		cout << measurePoints.size() <<" measurepoints read" << endl;

		ofstream outputStream;
		string output=filename.replace(filename.end()-3, filename.end(),"csv");
		outputStream.open(output.c_str(), ios::out);

		cout << "Writing data to " << output << endl;
		for(MeasurePoint* mp : measurePoints){
			outputStream << mp->getDate() << SEPERATOR << setw(2) << mp->getHour() << SEPERATOR << mp->getPower() << endl;
		}

		cout << "Writing was successfull" << endl;

		for(MeasurePoint* mp : measurePoints){
			delete mp;
		}

		delete measurePointsReader;

	}

	catch (const XMLException& toCatch) {
		cerr << "ERROR" <<endl;
		printException(toCatch);
		return 0;
	}

	catch (const SAXParseException& toCatch) {
		cerr << "ERROR : Exception while Parsing."<<endl;
		char* message = XMLString::transcode(toCatch.getMessage());
		cerr << "Exception:" << endl << message << endl;
		XMLString::release(&message);
	    return 0;
	}

	delete parser;

	XMLPlatformUtils::Terminate();

	return 1;
}
<commit_msg>return 0 if successfull<commit_after>/**
 * Exercise 2 : Read in a xml-file, validate via sheme and generate a csv with the values.
 *
 * @author FirstSanny
 */

#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <vector>

#include "MeasurePointFromDocumentReader.h"
#include "XMLParser.h"
#include "MeasurePoint.h"

namespace {

	const char* SEPERATOR = "; ";

	const char* URL_MEASURED_XSD = "http://gaslab.zib.de/kwpt/measured";
	const char* FILE_MEASURED_XSD = "measured-1-1-0.xsd";
//	const char* FILE_FRAMEWORK_XSD = "Framework-1-1-0.xsd";
//	const char* FILE_PHYSICS_XSD = "PhysicalValues-1-1-0.xsd";
//	const char* FILE_TOPO_XSD = "Topology-1-1-0.xsd";
//	const char* FILE_PROG_XSD = "prognosis-1-1-0.xsd";

}

using namespace std;

/** Printing a Exception with "Exception:\n message \n" */
void inline printException(const XMLException& toCatch) {
	char* message = XMLString::transcode(toCatch.getMessage());
	cerr << "Exception:" << endl << message << endl;
	XMLString::release(&message);
}

/** Reading in a File, try to parse and validate against sheme */
int main(int argn, char *argv[]) {

	if (argn <= 1) {
		cerr << "ERROR : There was no filename" << endl;
		return 1;
	}

	string filename = argv[1];
	cout << "Going to parse the file " << filename << endl;

	try {
	    XMLPlatformUtils::Initialize();
	}catch (const XMLException& toCatch) {
		cerr << "ERROR : Couldn't initialize XML-Parser"<<endl;
		printException(toCatch);
		return 0;
	}

	XMLParser* parser = new XMLParser();

	cout << "Successfull initialized" << endl;

	try {

		string shemaLoc = URL_MEASURED_XSD;
		shemaLoc = shemaLoc + " " + FILE_MEASURED_XSD;
		parser->setExternalSchemaLocation(shemaLoc.c_str());
		cout << "Validationfile: "<< FILE_MEASURED_XSD << endl;

		parser->parse(argv[1]);
		cout << "File validated and parsed to DOM" << endl;

		if(parser->getErrorCount() != 0){
		  cerr << "WARNING : File doesn't match sheme" << endl;
		  cerr << "There were " << parser->getErrorCount() << " errors." << endl;
		}
		cerr << parser->getErrors();

		MeasurePointFromDocumentReader* measurePointsReader = new MeasurePointFromDocumentReader(parser->getDocument());
		measurePointsReader->readMeasurepoints();
		vector<MeasurePoint*> measurePoints = measurePointsReader->getMeasurePoints();
		cout << measurePoints.size() <<" measurepoints read" << endl;

		ofstream outputStream;
		string output=filename.replace(filename.end()-3, filename.end(),"csv");
		outputStream.open(output.c_str(), ios::out);

		cout << "Writing data to " << output << endl;
		for(MeasurePoint* mp : measurePoints){
			outputStream << mp->getDate() << SEPERATOR << setw(2) << mp->getHour() << SEPERATOR << mp->getPower() << endl;
		}

		cout << "Writing was successfull" << endl;

		for(MeasurePoint* mp : measurePoints){
			delete mp;
		}

		delete measurePointsReader;

	}

	catch (const XMLException& toCatch) {
		cerr << "ERROR" <<endl;
		printException(toCatch);
		return 0;
	}

	catch (const SAXParseException& toCatch) {
		cerr << "ERROR : Exception while Parsing."<<endl;
		char* message = XMLString::transcode(toCatch.getMessage());
		cerr << "Exception:" << endl << message << endl;
		XMLString::release(&message);
	    return 0;
	}

	delete parser;

	XMLPlatformUtils::Terminate();

	return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2019 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#define CAF_SUITE string_application

#include "caf/net/endpoint_manager.hpp"
#include <caf/policy/scribe.hpp>

#include "caf/test/dsl.hpp"

#include "host_fixture.hpp"

#include "caf/binary_deserializer.hpp"
#include "caf/binary_serializer.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/make_actor.hpp"
#include "caf/net/actor_proxy_impl.hpp"
#include "caf/net/make_endpoint_manager.hpp"
#include "caf/net/multiplexer.hpp"
#include "caf/net/stream_socket.hpp"

using namespace caf;
using namespace caf::net;
using namespace caf::policy;

namespace {

string_view hello_manager{"hello manager!"};

string_view hello_test{"hello test!"};

struct fixture : test_coordinator_fixture<>, host_fixture {
  fixture() {
    mpx = std::make_shared<multiplexer>();
    if (auto err = mpx->init())
      CAF_FAIL("mpx->init failed: " << sys.render(err));
  }

  bool handle_io_event() override {
    mpx->handle_updates();
    return mpx->poll_once(false);
  }

  multiplexer_ptr mpx;
};

struct string_application_header {
  uint32_t payload;
};

/// @relates header
template <class Inspector>
typename Inspector::result_type inspect(Inspector& f,
                                        string_application_header& hdr) {
  return f(meta::type_name("sa_header"), hdr.payload);
}

class string_application {
public:
  using header_type = string_application_header;

  string_application(actor_system& sys, std::shared_ptr<std::vector<char>> buf)
    : sys_(sys), buf_(std::move(buf)) {
    // nop
  }

  template <class Parent>
  error init(Parent&) {
    return none;
  }

  template <class Parent>
  void handle_packet(Parent&, header_type&, span<char> payload) {
    binary_deserializer source{sys_, payload.data(), payload.size()};
    message msg;
    if (auto err = msg.load(source))
      CAF_FAIL("unable to deserialize message: " << err);
    if (!msg.match_elements<std::string>())
      CAF_FAIL("unexpected message: " << msg);
    auto& str = msg.get_as<std::string>(0);
    buf_->insert(buf_->end(), str.begin(), str.end());
  }

  template <class Parent>
  void write_message(Parent& parent,
                     std::unique_ptr<net::endpoint_manager::message> msg) {
    std::vector<char> buf;
    header_type header{static_cast<uint32_t>(msg->payload.size())};
    buf.resize(sizeof(header_type));
    memcpy(buf.data(), &header, buf.size());
    buf.insert(buf.end(), msg->payload.begin(), msg->payload.end());
    parent.write_packet(buf);
  }

  static expected<std::vector<char>> serialize(actor_system& sys,
                                               const type_erased_tuple& x) {
    std::vector<char> result;
    binary_serializer sink{sys, result};
    if (auto err = message::save(sink, x))
      return err;
    return result;
  }

private:
  actor_system& sys_;
  std::shared_ptr<std::vector<char>> buf_;
};

template <class Base, class Subtype>
class stream_string_application : public Base {
public:
  using header_type = typename Base::header_type;

  stream_string_application(actor_system& sys,
                            std::shared_ptr<std::vector<char>> buf)
    : Base(sys, std::move(buf)), await_payload_(false) {
    // nop
  }

  template <class Parent>
  error init(Parent& parent) {
    parent.transport().configure_read(
      net::receive_policy::exactly(sizeof(header_type)));
    return Base::init(parent);
  }

  template <class Parent>
  void handle_data(Parent& parent, span<char> data) {
    if (await_payload_) {
      Base::handle_packet(parent, header_, data);
      await_payload_ = false;
    } else {
      if (data.size() != sizeof(header_type))
        CAF_FAIL("");
      memcpy(&header_, data.data(), sizeof(header_type));
      if (header_.payload == 0)
        Base::handle_packet(parent, header_, span<char>{});
      else
        parent.configure_read(net::receive_policy::exactly(header_.payload));
      await_payload_ = true;
    }
  }

  template <class Manager>
  void resolve(Manager& manager, const std::string& path, actor listener) {
    actor_id aid = 42;
    auto hid = "0011223344556677889900112233445566778899";
    auto nid = unbox(make_node_id(aid, hid));
    actor_config cfg;
    auto p = make_actor<net::actor_proxy_impl, strong_actor_ptr>(aid, nid,
                                                                 &manager
                                                                    .system(),
                                                                 cfg, &manager);
    anon_send(listener, resolve_atom::value, std::move(path), p);
  }

  template <class Transport>
  void timeout(Transport&, atom_value, uint64_t) {
    // nop
  }

  void handle_error(sec) {
    // nop
  }

private:
  header_type header_;
  bool await_payload_;
};

} // namespace

CAF_TEST_FIXTURE_SCOPE(endpoint_manager_tests, fixture)

CAF_TEST(receive) {
  std::vector<char> read_buf(1024);
  CAF_CHECK_EQUAL(mpx->num_socket_managers(), 1u);
  auto buf = std::make_shared<std::vector<char>>();
  auto sockets = unbox(make_stream_socket_pair());
  nonblocking(sockets.second, true);
  CAF_CHECK_EQUAL(read(sockets.second, read_buf.data(), read_buf.size()),
                  sec::unavailable_or_would_block);
  CAF_MESSAGE("adding both endpoint managers");
  auto mgr1 = make_endpoint_manager(mpx, sys, policy::scribe{sockets.first},
                                    extend<string_application>::with<
                                      stream_string_application>{sys, buf});
  CAF_CHECK_EQUAL(mgr1->init(), none);
  mpx->handle_updates();
  CAF_CHECK_EQUAL(mpx->num_socket_managers(), 2u);
  auto mgr2 = make_endpoint_manager(mpx, sys, policy::scribe{sockets.second},
                                    extend<string_application>::with<
                                      stream_string_application>{sys, buf});
  CAF_CHECK_EQUAL(mgr2->init(), none);
  mpx->handle_updates();
  CAF_CHECK_EQUAL(mpx->num_socket_managers(), 3u);
  CAF_MESSAGE("resolve actor-proxy");
  mgr1->resolve("/id/42", self);
  run();
  self->receive(
    [&](resolve_atom, const std::string&, const strong_actor_ptr& p) {
      CAF_MESSAGE("got a proxy, send a message to it");
      self->send(actor_cast<actor>(p), "hello proxy!");
    },
    after(std::chrono::seconds(0)) >>
      [&] { CAF_FAIL("manager did not respond with a proxy."); });
  run();
  CAF_CHECK_EQUAL(string_view(buf->data(), buf->size()), "hello proxy!");
}

CAF_TEST_FIXTURE_SCOPE_END()
<commit_msg>Add application_type<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright 2011-2019 Dominik Charousset                                     *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#define CAF_SUITE string_application

#include "caf/net/endpoint_manager.hpp"
#include <caf/policy/scribe.hpp>

#include "caf/test/dsl.hpp"

#include "host_fixture.hpp"

#include "caf/binary_deserializer.hpp"
#include "caf/binary_serializer.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/make_actor.hpp"
#include "caf/net/actor_proxy_impl.hpp"
#include "caf/net/make_endpoint_manager.hpp"
#include "caf/net/multiplexer.hpp"
#include "caf/net/stream_socket.hpp"

using namespace caf;
using namespace caf::net;
using namespace caf::policy;

namespace {

string_view hello_manager{"hello manager!"};

string_view hello_test{"hello test!"};

struct fixture : test_coordinator_fixture<>, host_fixture {
  fixture() {
    mpx = std::make_shared<multiplexer>();
    if (auto err = mpx->init())
      CAF_FAIL("mpx->init failed: " << sys.render(err));
  }

  bool handle_io_event() override {
    mpx->handle_updates();
    return mpx->poll_once(false);
  }

  multiplexer_ptr mpx;
};

struct string_application_header {
  uint32_t payload;
};

/// @relates header
template <class Inspector>
typename Inspector::result_type inspect(Inspector& f,
                                        string_application_header& hdr) {
  return f(meta::type_name("sa_header"), hdr.payload);
}

class string_application {
public:
  using header_type = string_application_header;

  string_application(actor_system& sys, std::shared_ptr<std::vector<char>> buf)
    : sys_(sys), buf_(std::move(buf)) {
    // nop
  }

  template <class Parent>
  error init(Parent&) {
    return none;
  }

  template <class Parent>
  void handle_packet(Parent&, header_type&, span<char> payload) {
    binary_deserializer source{sys_, payload.data(), payload.size()};
    message msg;
    if (auto err = msg.load(source))
      CAF_FAIL("unable to deserialize message: " << err);
    if (!msg.match_elements<std::string>())
      CAF_FAIL("unexpected message: " << msg);
    auto& str = msg.get_as<std::string>(0);
    buf_->insert(buf_->end(), str.begin(), str.end());
  }

  template <class Parent>
  void write_message(Parent& parent,
                     std::unique_ptr<net::endpoint_manager::message> msg) {
    std::vector<char> buf;
    header_type header{static_cast<uint32_t>(msg->payload.size())};
    buf.resize(sizeof(header_type));
    memcpy(buf.data(), &header, buf.size());
    buf.insert(buf.end(), msg->payload.begin(), msg->payload.end());
    parent.write_packet(buf);
  }

  static expected<std::vector<char>> serialize(actor_system& sys,
                                               const type_erased_tuple& x) {
    std::vector<char> result;
    binary_serializer sink{sys, result};
    if (auto err = message::save(sink, x))
      return err;
    return result;
  }

private:
  actor_system& sys_;
  std::shared_ptr<std::vector<char>> buf_;
};

template <class Base, class Subtype>
class stream_string_application : public Base {
public:
  using header_type = typename Base::header_type;

  stream_string_application(actor_system& sys,
                            std::shared_ptr<std::vector<char>> buf)
    : Base(sys, std::move(buf)), await_payload_(false) {
    // nop
  }

  template <class Parent>
  error init(Parent& parent) {
    parent.transport().configure_read(
      net::receive_policy::exactly(sizeof(header_type)));
    return Base::init(parent);
  }

  template <class Parent>
  void handle_data(Parent& parent, span<char> data) {
    if (await_payload_) {
      Base::handle_packet(parent, header_, data);
      await_payload_ = false;
    } else {
      if (data.size() != sizeof(header_type))
        CAF_FAIL("");
      memcpy(&header_, data.data(), sizeof(header_type));
      if (header_.payload == 0)
        Base::handle_packet(parent, header_, span<char>{});
      else
        parent.configure_read(net::receive_policy::exactly(header_.payload));
      await_payload_ = true;
    }
  }

  template <class Manager>
  void resolve(Manager& manager, const std::string& path, actor listener) {
    actor_id aid = 42;
    auto hid = "0011223344556677889900112233445566778899";
    auto nid = unbox(make_node_id(aid, hid));
    actor_config cfg;
    auto p = make_actor<net::actor_proxy_impl, strong_actor_ptr>(aid, nid,
                                                                 &manager
                                                                    .system(),
                                                                 cfg, &manager);
    anon_send(listener, resolve_atom::value, std::move(path), p);
  }

  template <class Transport>
  void timeout(Transport&, atom_value, uint64_t) {
    // nop
  }

  void handle_error(sec) {
    // nop
  }

private:
  header_type header_;
  bool await_payload_;
};

} // namespace

CAF_TEST_FIXTURE_SCOPE(endpoint_manager_tests, fixture)

CAF_TEST(receive) {
  using application_type = extend<string_application>::with<
    stream_string_application>;
  std::vector<char> read_buf(1024);
  CAF_CHECK_EQUAL(mpx->num_socket_managers(), 1u);
  auto buf = std::make_shared<std::vector<char>>();
  auto sockets = unbox(make_stream_socket_pair());
  nonblocking(sockets.second, true);
  CAF_CHECK_EQUAL(read(sockets.second, read_buf.data(), read_buf.size()),
                  sec::unavailable_or_would_block);
  CAF_MESSAGE("adding both endpoint managers");
  auto mgr1 = make_endpoint_manager(mpx, sys, policy::scribe{sockets.first},
                                    application_type{sys, buf});
  CAF_CHECK_EQUAL(mgr1->init(), none);
  mpx->handle_updates();
  CAF_CHECK_EQUAL(mpx->num_socket_managers(), 2u);
  auto mgr2 = make_endpoint_manager(mpx, sys, policy::scribe{sockets.second},
                                    application_type{sys, buf});
  CAF_CHECK_EQUAL(mgr2->init(), none);
  mpx->handle_updates();
  CAF_CHECK_EQUAL(mpx->num_socket_managers(), 3u);
  CAF_MESSAGE("resolve actor-proxy");
  mgr1->resolve("/id/42", self);
  run();
  self->receive(
    [&](resolve_atom, const std::string&, const strong_actor_ptr& p) {
      CAF_MESSAGE("got a proxy, send a message to it");
      self->send(actor_cast<actor>(p), "hello proxy!");
    },
    after(std::chrono::seconds(0)) >>
      [&] { CAF_FAIL("manager did not respond with a proxy."); });
  run();
  CAF_CHECK_EQUAL(string_view(buf->data(), buf->size()), "hello proxy!");
}

CAF_TEST_FIXTURE_SCOPE_END()
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkCurvatures.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

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

#include "vtkObjectFactory.h"
#include "vtkPolyDataNormals.h"
#include "vtkPolyData.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkPolygon.h"
#include "vtkTensor.h"

vtkCxxRevisionMacro(vtkCurvatures, "1.2");
vtkStandardNewMacro(vtkCurvatures);

//------------------------------------------------------------------------------
#if VTK3
vtkCurvatures* vtkCurvatures::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCurvatures");
  if(ret)
    {
    return (vtkCurvatures*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkCurvatures;
}
#endif
//-------------------------------------------------------//
vtkCurvatures::vtkCurvatures()
{
  this->CurvatureType = VTK_CURVATURE_GAUSS;
  this->InvertMeanCurvature = false;
}
//-------------------------------------------------------//
void vtkCurvatures::GetMeanCurvature()
{
    vtkDebugMacro("Start vtkCurvatures::GetMeanCurvature");
    vtkPolyData* mesh = this->GetOutput();

    // Empty array check
    if (mesh->GetNumberOfPolys()==0 || mesh->GetNumberOfPoints()==0)
      {
      vtkErrorMacro("No points/cells to operate on");
      return;
      }

    int numPts = mesh->GetNumberOfPoints();

    // vtkData
    vtkIdList* vertices, *vertices_n, *neighbours;

    vtkTriangle* facet;
    vtkTriangle* neighbour;
    //     create-allocate
    vertices   = vtkIdList::New();
    vertices_n = vtkIdList::New();
    neighbours = vtkIdList::New();
    facet      = vtkTriangle::New();
    neighbour  = vtkTriangle::New();
    vtkDoubleArray* meanCurvature = vtkDoubleArray::New();
    meanCurvature->SetName("Mean_Curvature");
    meanCurvature->SetNumberOfComponents(1);
    meanCurvature->SetNumberOfTuples(numPts);
    // Get the array so we can write to it directly
    double *meanCurvatureData = meanCurvature->GetPointer(0);
    //     data
    int v, v_l, v_r, v_o,  f, F, V, n, nv;// n short for neighbor

    //     create-allocate
    float n_f[3]; // normal of facet (could be stored for later?)
    float n_n[3]; // normal of edge
    float t[3];   // to store the cross product of n_f n_n
    float ore[3]; // origin of e
    float end[3]; // end of e
    float oth[3]; //     third vertex necessary for comp of n
    float vn0[3];
    float vn1[3]; // vertices for computation of neighbour's n
    float vn2[3];
    float e[3];   // edge (oriented)

    double cs, sn;    // cs: cos; sn sin
    double angle, length, Af, Hf;  // temporary store

    mesh->BuildLinks();
    //data init
    f = 0;
    F = mesh->GetNumberOfCells();
    V = mesh->GetNumberOfPoints();
    Hf = 0.0;
    // init, preallocate the mean curvature
    int* num_neighb = new int[V];
    for (v = 0; v < V; v++)
      {
      meanCurvatureData[v] = 0.0;
      num_neighb[v] = 0;
      }

    //     main loop
    vtkDebugMacro(<<"Main loop: loop over facets such that id > id of neighb");
    vtkDebugMacro(<<"so that every edge comes only once");
    //
    for (f = 0; f < F; f++)
      {
      mesh->GetCellPoints(f,vertices);
      nv = vertices->GetNumberOfIds();

      for (v = 0; v < nv; v++)
        {
        // get neighbour
        v_l = vertices->GetId(v);
        v_r = vertices->GetId((v+1) % nv);
        v_o = vertices->GetId((v+2) % nv);
        mesh->GetCellEdgeNeighbors(f,v_l,v_r,neighbours);

        // compute only if there is really ONE neighbour
        // AND meanCurvature has not been computed yet!
        // (ensured by n > f)
        if (neighbours->GetNumberOfIds() == 1 && (n = neighbours->GetId(0)) > f)
          {
          // find 3 corners of f: in order!
          mesh->GetPoint(v_l,ore);
          mesh->GetPoint(v_r,end);
          mesh->GetPoint(v_o,oth);
          // compute normal of f
          facet->ComputeNormal(ore,end,oth,n_f);
          // compute common edge
          e[0] = end[0]; e[1] = end[1]; e[2] = end[2];
          e[0] -= ore[0]; e[1] -= ore[1]; e[2] -= ore[2];
          length = double(vtkMath::Normalize(e));
          Af = double(facet->TriangleArea(ore,end,oth));
          // find 3 corners of n: in order!
          mesh->GetCellPoints(n,vertices_n);
          mesh->GetPoint(vertices_n->GetId(0),vn0);
          mesh->GetPoint(vertices_n->GetId(1),vn1);
          mesh->GetPoint(vertices_n->GetId(2),vn2);
          Af += double(facet->TriangleArea(vn0,vn1,vn2));
          // compute normal of n
          neighbour->ComputeNormal(vn0,vn1,vn2,n_n);
          // the cosine is n_f * n_n
          cs = double(vtkMath::Dot(n_f,n_n));
          // the sin is (n_f x n_n) * e
          vtkMath::Cross(n_f,n_n,t);
          sn = double(vtkMath::Dot(t,e));
          // signed angle in [-pi,pi]
          if (sn!=0.0 || cs!=0.0)
            {
            angle = atan2(sn,cs);
            Hf    = length*angle;
            }
          else
            {
            Hf = 0.0;
            }
          // add weighted Hf to scalar at v_l and v_r
          if (Af!=0.0)
            {
            (Hf /= Af) *=3.0;
            }
          meanCurvatureData[v_l] += Hf;
          meanCurvatureData[v_r] += Hf;
          num_neighb[v_l] += 1;
          num_neighb[v_r] += 1;
          }
        }
      }

    // put curvature in vtkArray
    for (v = 0; v < V; v++)
      {
        if (num_neighb[v]>0)
          {
          Hf = 0.5*meanCurvatureData[v]/(double)num_neighb[v];
          if (this->InvertMeanCurvature)
            {
            meanCurvatureData[v] = -Hf;
            }
          else
            {
            meanCurvatureData[v] = Hf;
            }
          }
        else
          {
          meanCurvatureData[v] = 0.0;
          }
      }

    mesh->GetPointData()->AddArray(meanCurvature);
    mesh->GetPointData()->SetActiveScalars("Mean_Curvature");

    vtkDebugMacro("Set Values of Mean Curvature: Done");
    // clean
    vertices  ->Delete();
    vertices_n->Delete();
    neighbours->Delete();
    facet     ->Delete();
    neighbour ->Delete();

    if (meanCurvature) meanCurvature->Delete();
    if (num_neighb) delete [] num_neighb;
};
//--------------------------------------------
#define CLAMP_MACRO(v)    ((v)<(-1) ? (-1) : (v) > (1) ? (1) : v)
void vtkCurvatures::GetGaussCurvature()
{
    vtkDebugMacro("Start vtkCurvatures::GetGaussCurvature()");
    // vtk data
    vtkPolyData* output = this->GetOutput();
    vtkCellArray* facets = output->GetPolys();

    // Empty array check
    if (output->GetNumberOfPolys()==0 || output->GetNumberOfPoints()==0)
      {
      vtkErrorMacro("No points/cells to operate on");
      return;
      }

    vtkTriangle* facet = vtkTriangle::New();

    // other data
    int Nf   = output->GetNumberOfCells ();
    int Nv   = output->GetNumberOfPoints();

    double* K = new double[Nv];
    double* dA = new double[Nv];
    double pi2 = 2.0*vtkMath::Pi();
    for (int k = 0; k < Nv; k++)
      {
      K[k]  = pi2;
      dA[k] = 0.0;
      }

    float v0[3], v1[3], v2[3], e0[3], e1[3], e2[3];

    double A, alpha0, alpha1, alpha2;

    int f, *vert;
    facets->InitTraversal();
    while (facets->GetNextCell(f,vert))
      {
      output->GetPoint(vert[0],v0);
      output->GetPoint(vert[1],v1);
      output->GetPoint(vert[2],v2);
      // edges
      e0[0] = v1[0] ; e0[1] = v1[1] ; e0[2] = v1[2] ;
      e0[0] -= v0[0]; e0[1] -= v0[1]; e0[2] -= v0[2];

      e1[0] = v2[0] ; e1[1] = v2[1] ; e1[2] = v2[2] ;
      e1[0] -= v1[0]; e1[1] -= v1[1]; e1[2] -= v1[2];

      e2[0] = v0[0] ; e2[1] = v0[1] ; e2[2] = v0[2] ;
      e2[0] -= v2[0]; e2[1] -= v2[1]; e2[2] -= v2[2];

      // normalise
      vtkMath::Normalize(e0); vtkMath::Normalize(e1); vtkMath::Normalize(e2);
      // angles
      // I get lots of acos domain errors so clamp the value to +/-1 as the
      // normalize function can return 1.000000001 etc (I think)
      double ac1 = vtkMath::Dot(e1,e2);
      double ac2 = vtkMath::Dot(e2,e0);
      double ac3 = vtkMath::Dot(e0,e1);
      alpha0 = acos(-CLAMP_MACRO(ac1));
      alpha1 = acos(-CLAMP_MACRO(ac2));
      alpha2 = acos(-CLAMP_MACRO(ac3));

      // surf. area
      A = double(facet->TriangleArea(v0,v1,v2));
      // UPDATE
      dA[vert[0]] += A;
      dA[vert[1]] += A;
      dA[vert[2]] += A;
      K[vert[0]] -= alpha1;
      K[vert[1]] -= alpha2;
      K[vert[2]] -= alpha0;
      }

    int numPts = output->GetNumberOfPoints();
    // put curvature in vtkArray
    vtkDoubleArray* gaussCurvature = vtkDoubleArray::New();
    gaussCurvature->SetName("Gauss_Curvature");
    gaussCurvature->SetNumberOfComponents(1);
    gaussCurvature->SetNumberOfTuples(numPts);
    double *gaussCurvatureData = gaussCurvature->GetPointer(0);

    for (int v = 0; v < Nv; v++)
      {
      if (dA[v]>0.0)
        {
        gaussCurvatureData[v] = 3.0*K[v]/dA[v];
        }
      else
        {
        gaussCurvatureData[v] = 0.0;
        }
      }

    output->GetPointData()->AddArray(gaussCurvature);
    output->GetPointData()->SetActiveScalars("Gauss_Curvature");

    vtkDebugMacro("Set Values of Gauss Curvature: Done");
    /*******************************************************/
    if (facet) facet->Delete();
    if (K)              delete [] K;
    if (dA)             delete [] dA;
    if (gaussCurvature) gaussCurvature->Delete();
    /*******************************************************/
};

//-------------------------------------------------------
void vtkCurvatures::Execute()
{
  vtkPolyData *input  = this->GetInput();
  vtkPolyData *output = this->GetOutput();
  // Null input check
  if (!input)
    {
    return;
    }

  output->CopyStructure(input);
  output->GetPointData()->PassData(input->GetPointData());
  output->GetFieldData()->PassData(input->GetFieldData());

  //-------------------------------------------------------//
  //    Set Curvatures as PointData  Scalars               //
  //-------------------------------------------------------//

  if ( this->CurvatureType == VTK_CURVATURE_GAUSS )
      {
      this->GetGaussCurvature();
      }
  else if ( this->CurvatureType == VTK_CURVATURE_MEAN )
      {
      this->GetMeanCurvature();
      }
  else
      {
      vtkErrorMacro("Only Gauss and Mean Curvature type available");
      }
}
/*-------------------------------------------------------*/
void vtkCurvatures::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataToPolyDataFilter::PrintSelf(os,indent);
  os << indent << "CurvatureType: " << this->CurvatureType << "\n";
  os << indent << "InvertMeanCurvature: " << this->InvertMeanCurvature << "\n";
}

<commit_msg>Fix build problem on 64 bit id<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCurvatures.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

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

#include "vtkObjectFactory.h"
#include "vtkPolyDataNormals.h"
#include "vtkPolyData.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkPolygon.h"
#include "vtkTensor.h"

vtkCxxRevisionMacro(vtkCurvatures, "1.3");
vtkStandardNewMacro(vtkCurvatures);

//------------------------------------------------------------------------------
#if VTK3
vtkCurvatures* vtkCurvatures::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCurvatures");
  if(ret)
    {
    return (vtkCurvatures*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkCurvatures;
}
#endif
//-------------------------------------------------------//
vtkCurvatures::vtkCurvatures()
{
  this->CurvatureType = VTK_CURVATURE_GAUSS;
  this->InvertMeanCurvature = false;
}
//-------------------------------------------------------//
void vtkCurvatures::GetMeanCurvature()
{
    vtkDebugMacro("Start vtkCurvatures::GetMeanCurvature");
    vtkPolyData* mesh = this->GetOutput();

    // Empty array check
    if (mesh->GetNumberOfPolys()==0 || mesh->GetNumberOfPoints()==0)
      {
      vtkErrorMacro("No points/cells to operate on");
      return;
      }

    int numPts = mesh->GetNumberOfPoints();

    // vtkData
    vtkIdList* vertices, *vertices_n, *neighbours;

    vtkTriangle* facet;
    vtkTriangle* neighbour;
    //     create-allocate
    vertices   = vtkIdList::New();
    vertices_n = vtkIdList::New();
    neighbours = vtkIdList::New();
    facet      = vtkTriangle::New();
    neighbour  = vtkTriangle::New();
    vtkDoubleArray* meanCurvature = vtkDoubleArray::New();
    meanCurvature->SetName("Mean_Curvature");
    meanCurvature->SetNumberOfComponents(1);
    meanCurvature->SetNumberOfTuples(numPts);
    // Get the array so we can write to it directly
    double *meanCurvatureData = meanCurvature->GetPointer(0);
    //     data
    int v, v_l, v_r, v_o,  f, F, V, n, nv;// n short for neighbor

    //     create-allocate
    float n_f[3]; // normal of facet (could be stored for later?)
    float n_n[3]; // normal of edge
    float t[3];   // to store the cross product of n_f n_n
    float ore[3]; // origin of e
    float end[3]; // end of e
    float oth[3]; //     third vertex necessary for comp of n
    float vn0[3];
    float vn1[3]; // vertices for computation of neighbour's n
    float vn2[3];
    float e[3];   // edge (oriented)

    double cs, sn;    // cs: cos; sn sin
    double angle, length, Af, Hf;  // temporary store

    mesh->BuildLinks();
    //data init
    f = 0;
    F = mesh->GetNumberOfCells();
    V = mesh->GetNumberOfPoints();
    Hf = 0.0;
    // init, preallocate the mean curvature
    int* num_neighb = new int[V];
    for (v = 0; v < V; v++)
      {
      meanCurvatureData[v] = 0.0;
      num_neighb[v] = 0;
      }

    //     main loop
    vtkDebugMacro(<<"Main loop: loop over facets such that id > id of neighb");
    vtkDebugMacro(<<"so that every edge comes only once");
    //
    for (f = 0; f < F; f++)
      {
      mesh->GetCellPoints(f,vertices);
      nv = vertices->GetNumberOfIds();

      for (v = 0; v < nv; v++)
        {
        // get neighbour
        v_l = vertices->GetId(v);
        v_r = vertices->GetId((v+1) % nv);
        v_o = vertices->GetId((v+2) % nv);
        mesh->GetCellEdgeNeighbors(f,v_l,v_r,neighbours);

        // compute only if there is really ONE neighbour
        // AND meanCurvature has not been computed yet!
        // (ensured by n > f)
        if (neighbours->GetNumberOfIds() == 1 && (n = neighbours->GetId(0)) > f)
          {
          // find 3 corners of f: in order!
          mesh->GetPoint(v_l,ore);
          mesh->GetPoint(v_r,end);
          mesh->GetPoint(v_o,oth);
          // compute normal of f
          facet->ComputeNormal(ore,end,oth,n_f);
          // compute common edge
          e[0] = end[0]; e[1] = end[1]; e[2] = end[2];
          e[0] -= ore[0]; e[1] -= ore[1]; e[2] -= ore[2];
          length = double(vtkMath::Normalize(e));
          Af = double(facet->TriangleArea(ore,end,oth));
          // find 3 corners of n: in order!
          mesh->GetCellPoints(n,vertices_n);
          mesh->GetPoint(vertices_n->GetId(0),vn0);
          mesh->GetPoint(vertices_n->GetId(1),vn1);
          mesh->GetPoint(vertices_n->GetId(2),vn2);
          Af += double(facet->TriangleArea(vn0,vn1,vn2));
          // compute normal of n
          neighbour->ComputeNormal(vn0,vn1,vn2,n_n);
          // the cosine is n_f * n_n
          cs = double(vtkMath::Dot(n_f,n_n));
          // the sin is (n_f x n_n) * e
          vtkMath::Cross(n_f,n_n,t);
          sn = double(vtkMath::Dot(t,e));
          // signed angle in [-pi,pi]
          if (sn!=0.0 || cs!=0.0)
            {
            angle = atan2(sn,cs);
            Hf    = length*angle;
            }
          else
            {
            Hf = 0.0;
            }
          // add weighted Hf to scalar at v_l and v_r
          if (Af!=0.0)
            {
            (Hf /= Af) *=3.0;
            }
          meanCurvatureData[v_l] += Hf;
          meanCurvatureData[v_r] += Hf;
          num_neighb[v_l] += 1;
          num_neighb[v_r] += 1;
          }
        }
      }

    // put curvature in vtkArray
    for (v = 0; v < V; v++)
      {
        if (num_neighb[v]>0)
          {
          Hf = 0.5*meanCurvatureData[v]/(double)num_neighb[v];
          if (this->InvertMeanCurvature)
            {
            meanCurvatureData[v] = -Hf;
            }
          else
            {
            meanCurvatureData[v] = Hf;
            }
          }
        else
          {
          meanCurvatureData[v] = 0.0;
          }
      }

    mesh->GetPointData()->AddArray(meanCurvature);
    mesh->GetPointData()->SetActiveScalars("Mean_Curvature");

    vtkDebugMacro("Set Values of Mean Curvature: Done");
    // clean
    vertices  ->Delete();
    vertices_n->Delete();
    neighbours->Delete();
    facet     ->Delete();
    neighbour ->Delete();

    if (meanCurvature) meanCurvature->Delete();
    if (num_neighb) delete [] num_neighb;
};
//--------------------------------------------
#define CLAMP_MACRO(v)    ((v)<(-1) ? (-1) : (v) > (1) ? (1) : v)
void vtkCurvatures::GetGaussCurvature()
{
    vtkDebugMacro("Start vtkCurvatures::GetGaussCurvature()");
    // vtk data
    vtkPolyData* output = this->GetOutput();
    vtkCellArray* facets = output->GetPolys();

    // Empty array check
    if (output->GetNumberOfPolys()==0 || output->GetNumberOfPoints()==0)
      {
      vtkErrorMacro("No points/cells to operate on");
      return;
      }

    vtkTriangle* facet = vtkTriangle::New();

    // other data
    vtkIdType Nf   = output->GetNumberOfCells ();
    vtkIdType Nv   = output->GetNumberOfPoints();

    double* K = new double[Nv];
    double* dA = new double[Nv];
    double pi2 = 2.0*vtkMath::Pi();
    for (int k = 0; k < Nv; k++)
      {
      K[k]  = pi2;
      dA[k] = 0.0;
      }

    float v0[3], v1[3], v2[3], e0[3], e1[3], e2[3];

    double A, alpha0, alpha1, alpha2;

    vtkIdType f, *vert;
    facets->InitTraversal();
    while (facets->GetNextCell(f,vert))
      {
      output->GetPoint(vert[0],v0);
      output->GetPoint(vert[1],v1);
      output->GetPoint(vert[2],v2);
      // edges
      e0[0] = v1[0] ; e0[1] = v1[1] ; e0[2] = v1[2] ;
      e0[0] -= v0[0]; e0[1] -= v0[1]; e0[2] -= v0[2];

      e1[0] = v2[0] ; e1[1] = v2[1] ; e1[2] = v2[2] ;
      e1[0] -= v1[0]; e1[1] -= v1[1]; e1[2] -= v1[2];

      e2[0] = v0[0] ; e2[1] = v0[1] ; e2[2] = v0[2] ;
      e2[0] -= v2[0]; e2[1] -= v2[1]; e2[2] -= v2[2];

      // normalise
      vtkMath::Normalize(e0); vtkMath::Normalize(e1); vtkMath::Normalize(e2);
      // angles
      // I get lots of acos domain errors so clamp the value to +/-1 as the
      // normalize function can return 1.000000001 etc (I think)
      double ac1 = vtkMath::Dot(e1,e2);
      double ac2 = vtkMath::Dot(e2,e0);
      double ac3 = vtkMath::Dot(e0,e1);
      alpha0 = acos(-CLAMP_MACRO(ac1));
      alpha1 = acos(-CLAMP_MACRO(ac2));
      alpha2 = acos(-CLAMP_MACRO(ac3));

      // surf. area
      A = double(facet->TriangleArea(v0,v1,v2));
      // UPDATE
      dA[vert[0]] += A;
      dA[vert[1]] += A;
      dA[vert[2]] += A;
      K[vert[0]] -= alpha1;
      K[vert[1]] -= alpha2;
      K[vert[2]] -= alpha0;
      }

    int numPts = output->GetNumberOfPoints();
    // put curvature in vtkArray
    vtkDoubleArray* gaussCurvature = vtkDoubleArray::New();
    gaussCurvature->SetName("Gauss_Curvature");
    gaussCurvature->SetNumberOfComponents(1);
    gaussCurvature->SetNumberOfTuples(numPts);
    double *gaussCurvatureData = gaussCurvature->GetPointer(0);

    for (int v = 0; v < Nv; v++)
      {
      if (dA[v]>0.0)
        {
        gaussCurvatureData[v] = 3.0*K[v]/dA[v];
        }
      else
        {
        gaussCurvatureData[v] = 0.0;
        }
      }

    output->GetPointData()->AddArray(gaussCurvature);
    output->GetPointData()->SetActiveScalars("Gauss_Curvature");

    vtkDebugMacro("Set Values of Gauss Curvature: Done");
    /*******************************************************/
    if (facet) facet->Delete();
    if (K)              delete [] K;
    if (dA)             delete [] dA;
    if (gaussCurvature) gaussCurvature->Delete();
    /*******************************************************/
};

//-------------------------------------------------------
void vtkCurvatures::Execute()
{
  vtkPolyData *input  = this->GetInput();
  vtkPolyData *output = this->GetOutput();
  // Null input check
  if (!input)
    {
    return;
    }

  output->CopyStructure(input);
  output->GetPointData()->PassData(input->GetPointData());
  output->GetFieldData()->PassData(input->GetFieldData());

  //-------------------------------------------------------//
  //    Set Curvatures as PointData  Scalars               //
  //-------------------------------------------------------//

  if ( this->CurvatureType == VTK_CURVATURE_GAUSS )
      {
      this->GetGaussCurvature();
      }
  else if ( this->CurvatureType == VTK_CURVATURE_MEAN )
      {
      this->GetMeanCurvature();
      }
  else
      {
      vtkErrorMacro("Only Gauss and Mean Curvature type available");
      }
}
/*-------------------------------------------------------*/
void vtkCurvatures::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataToPolyDataFilter::PrintSelf(os,indent);
  os << indent << "CurvatureType: " << this->CurvatureType << "\n";
  os << indent << "InvertMeanCurvature: " << this->InvertMeanCurvature << "\n";
}

<|endoftext|>


<commit_before>/*
  Huffman Coding (encoder)
  lossless data compression algorithm, entropy encoding

  The main function takes as argument:
  arg1: input file name, this should be a ASCII-only textfile.

  It then writes the following files:
  fout1: output file name: fname1,
         contains the Huffman code words.
  fout2: file name: fname2,
         contains the C code for an array containing the
         Huffman code words.
  fout3: file name: fname3,
         input text after every character was substituted
         with the corresponding Huffman code word (binary).
  fout4: file name: fname4,
         contains the mapping of Huffman code words.
	 Essentially, this comprises the alphabet.
	 Characters are saved as integers (according to
	 the ASCII table).
  fout5: file name: fname5,
         contains a null-terminated string, containing
	 all chars of the alphabet.

*/

#include <cstdio>
#include <utility>
#include <vector>
#include <stack>
#include <queue>
#define INPUT_BUFFER_SIZE 10000000
#define ALPHABET_BUFFER_SIZE 1000
const char fname1[] = "HUFFMAN_code_words.txt";
const char fname2[] = "HUFFMAN_code_words_C.txt";
const char fname3[] = "HUFFMAN_encoded.txt";
const char fname4[] = "HUFFMAN_code_words_mapping.txt";
const char fname5[] = "HUFFMAN_alphabet.txt";
using std::vector;
using std::stack;
using std::priority_queue;
using std::pair;
using std::make_pair;
using std::greater;

typedef pair<double, int> PDI;
typedef pair<int, bool> PIB;

// A = {a_1, ..., a_n} alphabet, as an array of chars
//   it is assumed that 0 <= a_i <= n-1 and all a_i are
//   distinct, A is terminated with a '0' (C string)
// alen: length of A
// W = {w_1, ..., w_n} set of positive symbol weights,
//   usually proportional to probabilities
// C = {c_1, ..., c_n} the set of binary codeword
//   where c_i is the codeword for a_i, 1 <= i <= n
void HuffmanCoding_encoder(char const * const A, const int alen, double const * const W, vector<vector<bool> >& C) {
  int id = alen;
  // format of nodes inserted in priority queue:
  // (weight, node index)
  priority_queue<PDI, vector<PDI>, greater<PDI> > P;
  // add all leaf nodes to the priority queue
  for (int i = 0; i < alen; i++)
    P.push(make_pair(W[i], i));

  // generate the Huffman tree

  // parent[i] = (j, b): the parent of node i is node j
  // and the edge is marked with the binary digit b
  PIB* parent = new PIB[alen + alen - 1];
  while (P.size() > 1) {
    // remove the two nodes of highest priority from the queue
    PDI n1 = P.top();
    P.pop();
    PDI n2 = P.top();
    P.pop();
    // create a new internal node with these two nodes as children
    parent[n1.second] = make_pair(id, 0);
    parent[n2.second] = make_pair(id, 1);
    P.push(make_pair(n1.first + n2.first, id++));
  }
  parent[id-1] = make_pair(-1, 0);

  // construct the code words from the Huffman tree
  stack<bool> tempstack;
  C.resize(alen);
  for (int i = 0; i < alen; i++) {
    int v = i;
    while (parent[v].first != -1) {
      tempstack.push(parent[v].second);
      v = parent[v].first;
    }
    while (!tempstack.empty()) {
      C[i].push_back(tempstack.top());
      tempstack.pop();
    }
  }
}

int main(int argc, char** argv) {
  if (argc != 2) {
    fprintf(stderr, "Wrong number of arguments specified.\n");
    return 1;
  }

  FILE *fin = fopen(argv[1], "r");
  if (fin == NULL) {
    fprintf(stderr, "Input file %s could not be opened.\n", argv[1]);
    return 1;
  }

  FILE *fout1 = fopen(fname1, "w");
  FILE *fout2 = fopen(fname2, "w");
  FILE *fout3 = fopen(fname3, "w");
  FILE *fout4 = fopen(fname4, "w");
  FILE *fout5 = fopen(fname5, "w");

  // read input
  char* S = new char[INPUT_BUFFER_SIZE];
  int slen = fread(S, sizeof(char), INPUT_BUFFER_SIZE, fin);
  // specify the alphabet
  // the alphabet is determined by the chars appearing in the
  // input, thus, every symbol should appear once in the input
  char* A = new char[ALPHABET_BUFFER_SIZE];
  int alen = 0;
  int F[256] = { 0 }; // F[i] counts the frequency of char i
  for (int i = 0; i < slen; i++) {
    if (F[(unsigned char) S[i]] == 0)
      alen++;
    F[(unsigned char) S[i]]++;
  }

  for (int i = 0, j = 0; i < 256; i++)
    if (F[i] > 0)
      A[j++] = i;

  printf("The alphabet: ");
  for (int i = 0; i < alen; i++) {
    printf("%c", A[i]); // TODO: some chars are unprintable
    if (i != alen-1)
      printf(", ");
    else
      printf("\n");
  }

  // specify the weights
  double* W = new double[alen];
  for (int i = 0; i < alen; i++) {
    W[i] = (double) F[(unsigned char) A[i]] / (double) slen;
  }

  vector<vector<bool> > C;
  printf("Huffman Coding...\n");
  HuffmanCoding_encoder(A, alen, W, C);

  // print code words
  printf("The code words are:\n");
  for (int i = 0; i < alen; i++) {
    printf("'%c' (%04.1lf) [%d] ", A[i], W[i]*100.0, F[(unsigned char) A[i]]);
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      printf("%d", (int) *it);
    }
    printf("\n");
  }

  // fout2
  fprintf(fout2, "char C[%d][]={", alen);
  for (int i = 0; i < alen; i++) {
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      fprintf(fout2, "%d", (int) *it);
    }
    if (i != alen-1) {
      fprintf(fout2, ",");
    }
  }
  fprintf(fout2, "};\n");

  // fout1
  fprintf(fout1, "%d ",alen);
  for (int i = 0; i < alen; i++) {
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      fprintf(fout1, "%d", (int) *it);
    }
    if (i != alen-1) {
      fprintf(fout1, " ");
    }
  }
  fprintf(fout1, "\n");

  // reverse mapping, A[i] to index
  int R[256];
  memset(R, -1, sizeof R);
  for (int i = 0; i < alen; i++)
    R[(unsigned char) A[i]] = i;
  // fout3
  for (int i = 0; i < slen; i++) {
    for (vector<bool>::iterator it = C[R[(unsigned char) S[i]]].begin();
	 it != C[R[(unsigned char) S[i]]].end(); it++) {
      fprintf(fout3, "%d", (int) *it);
    }
  }
  fprintf(fout3, "\n");

  // fout4
  fprintf(fout4, "%d\n",alen);
  for (int i = 0; i < alen; i++) {
    fprintf(fout4, "%d ", (unsigned char) A[i]);
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      fprintf(fout4, "%d", (int) *it);
    }
    fprintf(fout4, "\n");
  }

  // fout5
  fwrite(A, sizeof(char), alen, fout5);
}
<commit_msg>HUFFMAN: Fixed bug, now also works for files with alphabet of length one.<commit_after>/*
  Huffman Coding (encoder)
  lossless data compression algorithm, entropy encoding

  The main function takes as argument:
  arg1: input file name, this should be a ASCII-only textfile.

  It then writes the following files:
  fout1: output file name: fname1,
         contains the Huffman code words.
  fout2: file name: fname2,
         contains the C code for an array containing the
         Huffman code words.
  fout3: file name: fname3,
         input text after every character was substituted
         with the corresponding Huffman code word (binary).
  fout4: file name: fname4,
         contains the mapping of Huffman code words.
	 Essentially, this comprises the alphabet.
	 Characters are saved as integers (according to
	 the ASCII table).
  fout5: file name: fname5,
         contains a null-terminated string, containing
	 all chars of the alphabet.

*/

#include <cstdio>
#include <utility>
#include <vector>
#include <stack>
#include <queue>
#define INPUT_BUFFER_SIZE 10000000
#define ALPHABET_BUFFER_SIZE 1000
const char fname1[] = "HUFFMAN_code_words.txt";
const char fname2[] = "HUFFMAN_code_words_C.txt";
const char fname3[] = "HUFFMAN_encoded.txt";
const char fname4[] = "HUFFMAN_code_words_mapping.txt";
const char fname5[] = "HUFFMAN_alphabet.txt";
using std::vector;
using std::stack;
using std::priority_queue;
using std::pair;
using std::make_pair;
using std::greater;

typedef pair<double, int> PDI;
typedef pair<int, bool> PIB;

// A = {a_1, ..., a_n} alphabet, as an array of chars
//   it is assumed that 0 <= a_i <= n-1 and all a_i are
//   distinct, A is terminated with a '0' (C string)
// alen: length of A
// W = {w_1, ..., w_n} set of positive symbol weights,
//   usually proportional to probabilities
// C = {c_1, ..., c_n} the set of binary codeword
//   where c_i is the codeword for a_i, 1 <= i <= n
void HuffmanCoding_encoder(char const * const A, const int alen, double const * const W, vector<vector<bool> >& C) {
  if (alen == 1) {
    C.resize(1);
    C[0].push_back(false);
  }

  int id = alen;
  // format of nodes inserted in priority queue:
  // (weight, node index)
  priority_queue<PDI, vector<PDI>, greater<PDI> > P;
  // add all leaf nodes to the priority queue
  for (int i = 0; i < alen; i++)
    P.push(make_pair(W[i], i));

  // generate the Huffman tree

  // parent[i] = (j, b): the parent of node i is node j
  // and the edge is marked with the binary digit b
  PIB* parent = new PIB[alen + alen - 1];
  while (P.size() > 1) {
    // remove the two nodes of highest priority from the queue
    PDI n1 = P.top();
    P.pop();
    PDI n2 = P.top();
    P.pop();
    // create a new internal node with these two nodes as children
    parent[n1.second] = make_pair(id, 0);
    parent[n2.second] = make_pair(id, 1);
    P.push(make_pair(n1.first + n2.first, id++));
  }
  parent[id-1] = make_pair(-1, 0);

  // construct the code words from the Huffman tree
  stack<bool> tempstack;
  C.resize(alen);
  for (int i = 0; i < alen; i++) {
    int v = i;
    while (parent[v].first != -1) {
      tempstack.push(parent[v].second);
      v = parent[v].first;
    }
    while (!tempstack.empty()) {
      C[i].push_back(tempstack.top());
      tempstack.pop();
    }
  }
}

int main(int argc, char** argv) {
  if (argc != 2) {
    fprintf(stderr, "Wrong number of arguments specified.\n");
    return 1;
  }

  FILE *fin = fopen(argv[1], "r");
  if (fin == NULL) {
    fprintf(stderr, "Input file %s could not be opened.\n", argv[1]);
    return 1;
  }

  FILE *fout1 = fopen(fname1, "w");
  FILE *fout2 = fopen(fname2, "w");
  FILE *fout3 = fopen(fname3, "w");
  FILE *fout4 = fopen(fname4, "w");
  FILE *fout5 = fopen(fname5, "w");

  // read input
  char* S = new char[INPUT_BUFFER_SIZE];
  int slen = fread(S, sizeof(char), INPUT_BUFFER_SIZE, fin);
  // specify the alphabet
  // the alphabet is determined by the chars appearing in the
  // input, thus, every symbol should appear once in the input
  char* A = new char[ALPHABET_BUFFER_SIZE];
  int alen = 0;
  int F[256] = { 0 }; // F[i] counts the frequency of char i
  for (int i = 0; i < slen; i++) {
    if (F[(unsigned char) S[i]] == 0)
      alen++;
    F[(unsigned char) S[i]]++;
  }

  for (int i = 0, j = 0; i < 256; i++)
    if (F[i] > 0)
      A[j++] = i;

  printf("The alphabet: ");
  for (int i = 0; i < alen; i++) {
    printf("%c", A[i]); // TODO: some chars are unprintable
    if (i != alen-1)
      printf(", ");
    else
      printf("\n");
  }

  // specify the weights
  double* W = new double[alen];
  for (int i = 0; i < alen; i++) {
    W[i] = (double) F[(unsigned char) A[i]] / (double) slen;
  }

  vector<vector<bool> > C;
  printf("Huffman Coding...\n");
  HuffmanCoding_encoder(A, alen, W, C);

  // print code words
  printf("The code words are:\n");
  for (int i = 0; i < alen; i++) {
    printf("'%c' (%04.1lf) [%d] ", A[i], W[i]*100.0, F[(unsigned char) A[i]]);
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      printf("%d", (int) *it);
    }
    printf("\n");
  }

  // fout2
  fprintf(fout2, "char C[%d][]={", alen);
  for (int i = 0; i < alen; i++) {
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      fprintf(fout2, "%d", (int) *it);
    }
    if (i != alen-1) {
      fprintf(fout2, ",");
    }
  }
  fprintf(fout2, "};\n");

  // fout1
  fprintf(fout1, "%d ",alen);
  for (int i = 0; i < alen; i++) {
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      fprintf(fout1, "%d", (int) *it);
    }
    if (i != alen-1) {
      fprintf(fout1, " ");
    }
  }
  fprintf(fout1, "\n");

  // reverse mapping, A[i] to index
  int R[256];
  memset(R, -1, sizeof R);
  for (int i = 0; i < alen; i++)
    R[(unsigned char) A[i]] = i;
  // fout3
  for (int i = 0; i < slen; i++) {
    for (vector<bool>::iterator it = C[R[(unsigned char) S[i]]].begin();
	 it != C[R[(unsigned char) S[i]]].end(); it++) {
      fprintf(fout3, "%d", (int) *it);
    }
  }
  fprintf(fout3, "\n");

  // fout4
  fprintf(fout4, "%d\n",alen);
  for (int i = 0; i < alen; i++) {
    fprintf(fout4, "%d ", (unsigned char) A[i]);
    for (vector<bool>::iterator it = C[i].begin(); it != C[i].end(); it++) {
      fprintf(fout4, "%d", (int) *it);
    }
    fprintf(fout4, "\n");
  }

  // fout5
  fwrite(A, sizeof(char), alen, fout5);
}
<|endoftext|>