<commit_before>#include "bamliquidator.h"

#include <cmath>
#include <fstream>
#include <future>
#include <iostream>
#include <map>
#include <stdexcept>
#include <sstream>

#include <boost/atomic.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include <hdf5.h>
#include <hdf5_hl.h>

/* todo:

   - don't store strings in table records, e.g. have seperate tables for chromosomes, file names,
     and cell types.  in the count table records, just store integers representing the strings.
     this should speed up the writing and cut the file sizes
 */

namespace
{
  const bool logging_enabled = false;
}

class ChromosomeLengths
{
public:
  ChromosomeLengths(const std::string &chrom_size_file)
  {
    const size_t chromosome_column = 0;
    const size_t type_column = 2;
    const size_t length_column = 4;

    std::ifstream size_file(chrom_size_file);
    if (!size_file.is_open())
    {
      throw std::runtime_error("failed to open chrom_size_file " + chrom_size_file);
    }

    for(std::string line; std::getline(size_file, line); )
    {
      std::vector<std::string> columns;
      boost::split(columns, line, boost::is_any_of("\t"));
      if (columns.size() < length_column + 1)
      {
        throw std::runtime_error("error parsing chrom_size_file");
      }
      m_type_to_chromosome_to_count[columns[type_column]][columns[chromosome_column]] =
        boost::lexical_cast<size_t>(columns[length_column]);
    }
  }

  size_t operator()(const std::string &bam_file, const std::string& chromosome) const
  {
    for (const auto type : m_type_to_chromosome_to_count)
    {
      if (bam_file.find(type.first) != std::string::npos)
      {
        const auto count = type.second.find(chromosome);
        if (count == type.second.end())
        {
          throw std::runtime_error("failed to find chromosome " + chromosome
                                   + " for " + type.first);
        }
        return count->second;
      }
    }
    throw std::runtime_error("failed to determine type of " + bam_file);
  }

private:
  typedef std::map<std::string, std::map<std::string, size_t>> TypeToChromosomeToCount;
  TypeToChromosomeToCount m_type_to_chromosome_to_count;
};

struct CountH5Record
{
  uint32_t bin_number;
  char cell_type[16];
  char chromosome[16];
  uint64_t count;
  char file_name[64];
};

std::vector<CountH5Record> count(const std::string& chr,
                                 const std::string& cell_type,
                                 const unsigned int bin_size,
                                 const ChromosomeLengths& lengths,
                                 const std::string& bam_file)
{
  const size_t last_slash_position = bam_file.find_last_of("/");
  const std::string bam_file_name = last_slash_position == std::string::npos
                                  ? bam_file
                                  : bam_file.substr(last_slash_position + 1);

  int base_pairs = lengths(bam_file, chr);
  int bins = std::ceil(base_pairs / (double) bin_size);
  int max_base_pair = bins * bin_size;

  const std::vector<double> bin_counts = liquidate(bam_file, chr, 0, max_base_pair, '.', bins, 0);

  CountH5Record record;
  record.bin_number = 0;
  strncpy(record.cell_type,  cell_type.c_str(),     sizeof(CountH5Record::cell_type));
  strncpy(record.chromosome, chr.c_str(),           sizeof(CountH5Record::chromosome));
  strncpy(record.file_name,  bam_file_name.c_str(), sizeof(CountH5Record::file_name));

  std::vector<CountH5Record> records(bin_counts.size(), record);
  for (size_t bin=0; bin <= bin_counts.size(); ++bin)
  {
    records[bin].bin_number = bin;
    records[bin].count = bin_counts[bin];
  }

  return records;
}

void batch(hid_t& file,
           const std::string& cell_type,
           const unsigned int bin_size,
           const ChromosomeLengths& lengths,
           const std::string& bam_file)
{
  std::deque<std::future<std::vector<CountH5Record>>> future_counts;

  const std::vector<std::string> chromosomes {"chr1", "chr2", "chr3", "chr4", "chr5",
    "chr6", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16",
    "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX"};

  for (auto& chr : chromosomes)
  {
    future_counts.push_back(std::async(count,
                                       std::ref(chr),
                                       std::ref(cell_type),
                                       bin_size,
                                       std::ref(lengths),
                                       std::ref(bam_file)));
  }

  const size_t record_size = sizeof(CountH5Record);

  size_t record_offset[] = { HOFFSET(CountH5Record, bin_number),
                             HOFFSET(CountH5Record, cell_type),
                             HOFFSET(CountH5Record, chromosome),
                             HOFFSET(CountH5Record, count),
                             HOFFSET(CountH5Record, file_name) };

  size_t field_sizes[] = { sizeof(CountH5Record::bin_number),
                           sizeof(CountH5Record::cell_type),
                           sizeof(CountH5Record::chromosome),
                           sizeof(CountH5Record::count),
                           sizeof(CountH5Record::file_name) };

  for (auto& future_count : future_counts)
  {
    std::vector<CountH5Record> records = future_count.get();

    herr_t status = H5TBappend_records(file, "counts", records.size(), record_size, record_offset,
                                       field_sizes, records.data());
    if (status != 0)
    {
      std::cerr << "Error appending record, status = " << status << std::endl;
    }
  }
}

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 6)
    {
      std::cerr << "usage: " << argv[0] << " cell_type bin_size ucsc_chrom_size_path bam_file_path hdf5_file\n"
        << "\ne.g. " << argv[0] << " mm1s 100000 /grail/annotations/ucsc_chromSize.txt"
        << "\n      /ifs/labs/bradner/bam/hg18/mm1s/04032013_D1L57ACXX_4.TTAGGC.hg18.bwt.sorted.bam\n"
        << "\nnote that this application is intended to be run from bamliquidator_batch.py -- see"
        << "\nhttps://github.com/BradnerLab/pipeline/wiki for more information"
        << std::endl;
      return 1;
    }

    const std::string cell_type = argv[1];
    const unsigned int bin_size = boost::lexical_cast<unsigned int>(argv[2]);
    const std::string ucsc_chrom_size_path = argv[3];
    const std::string bam_file_path = argv[4];
    const std::string hdf5_file_path = argv[5];

    if (bin_size == 0)
    {
      std::cerr << "bin size cannot be zero" << std::endl;
      return 2;
    }

    const ChromosomeLengths lengths(ucsc_chrom_size_path);

    hid_t h5file = H5Fopen(hdf5_file_path.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
    if (h5file < 0)
    {
      std::cerr << "Failed to open H5 file " << hdf5_file_path << std::endl;
      return 3;
    }

    batch(h5file, cell_type, bin_size, lengths, bam_file_path);

    H5Fclose(h5file);

    return 0;
  }
  catch(const std::exception& e)
  {
    std::cerr << "Unhandled exception: " << e.what() << std::endl;

    return 4;
  }
}

/* The MIT License (MIT)

   Copyright (c) 2013 John DiMatteo

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
 */
<commit_msg>Removed unused variable<commit_after>#include "bamliquidator.h"

#include <cmath>
#include <fstream>
#include <future>
#include <iostream>
#include <map>
#include <stdexcept>
#include <sstream>

#include <boost/atomic.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include <hdf5.h>
#include <hdf5_hl.h>

/* todo:

   - don't store strings in table records, e.g. have seperate tables for chromosomes, file names,
     and cell types.  in the count table records, just store integers representing the strings.
     this should speed up the writing and cut the file sizes
 */

class ChromosomeLengths
{
public:
  ChromosomeLengths(const std::string &chrom_size_file)
  {
    const size_t chromosome_column = 0;
    const size_t type_column = 2;
    const size_t length_column = 4;

    std::ifstream size_file(chrom_size_file);
    if (!size_file.is_open())
    {
      throw std::runtime_error("failed to open chrom_size_file " + chrom_size_file);
    }

    for(std::string line; std::getline(size_file, line); )
    {
      std::vector<std::string> columns;
      boost::split(columns, line, boost::is_any_of("\t"));
      if (columns.size() < length_column + 1)
      {
        throw std::runtime_error("error parsing chrom_size_file");
      }
      m_type_to_chromosome_to_count[columns[type_column]][columns[chromosome_column]] =
        boost::lexical_cast<size_t>(columns[length_column]);
    }
  }

  size_t operator()(const std::string &bam_file, const std::string& chromosome) const
  {
    for (const auto type : m_type_to_chromosome_to_count)
    {
      if (bam_file.find(type.first) != std::string::npos)
      {
        const auto count = type.second.find(chromosome);
        if (count == type.second.end())
        {
          throw std::runtime_error("failed to find chromosome " + chromosome
                                   + " for " + type.first);
        }
        return count->second;
      }
    }
    throw std::runtime_error("failed to determine type of " + bam_file);
  }

private:
  typedef std::map<std::string, std::map<std::string, size_t>> TypeToChromosomeToCount;
  TypeToChromosomeToCount m_type_to_chromosome_to_count;
};

struct CountH5Record
{
  uint32_t bin_number;
  char cell_type[16];
  char chromosome[16];
  uint64_t count;
  char file_name[64];
};

std::vector<CountH5Record> count(const std::string& chr,
                                 const std::string& cell_type,
                                 const unsigned int bin_size,
                                 const ChromosomeLengths& lengths,
                                 const std::string& bam_file)
{
  const size_t last_slash_position = bam_file.find_last_of("/");
  const std::string bam_file_name = last_slash_position == std::string::npos
                                  ? bam_file
                                  : bam_file.substr(last_slash_position + 1);

  int base_pairs = lengths(bam_file, chr);
  int bins = std::ceil(base_pairs / (double) bin_size);
  int max_base_pair = bins * bin_size;

  const std::vector<double> bin_counts = liquidate(bam_file, chr, 0, max_base_pair, '.', bins, 0);

  CountH5Record record;
  record.bin_number = 0;
  strncpy(record.cell_type,  cell_type.c_str(),     sizeof(CountH5Record::cell_type));
  strncpy(record.chromosome, chr.c_str(),           sizeof(CountH5Record::chromosome));
  strncpy(record.file_name,  bam_file_name.c_str(), sizeof(CountH5Record::file_name));

  std::vector<CountH5Record> records(bin_counts.size(), record);
  for (size_t bin=0; bin <= bin_counts.size(); ++bin)
  {
    records[bin].bin_number = bin;
    records[bin].count = bin_counts[bin];
  }

  return records;
}

void batch(hid_t& file,
           const std::string& cell_type,
           const unsigned int bin_size,
           const ChromosomeLengths& lengths,
           const std::string& bam_file)
{
  std::deque<std::future<std::vector<CountH5Record>>> future_counts;

  const std::vector<std::string> chromosomes {"chr1", "chr2", "chr3", "chr4", "chr5",
    "chr6", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16",
    "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX"};

  for (auto& chr : chromosomes)
  {
    future_counts.push_back(std::async(count,
                                       std::ref(chr),
                                       std::ref(cell_type),
                                       bin_size,
                                       std::ref(lengths),
                                       std::ref(bam_file)));
  }

  const size_t record_size = sizeof(CountH5Record);

  size_t record_offset[] = { HOFFSET(CountH5Record, bin_number),
                             HOFFSET(CountH5Record, cell_type),
                             HOFFSET(CountH5Record, chromosome),
                             HOFFSET(CountH5Record, count),
                             HOFFSET(CountH5Record, file_name) };

  size_t field_sizes[] = { sizeof(CountH5Record::bin_number),
                           sizeof(CountH5Record::cell_type),
                           sizeof(CountH5Record::chromosome),
                           sizeof(CountH5Record::count),
                           sizeof(CountH5Record::file_name) };

  for (auto& future_count : future_counts)
  {
    std::vector<CountH5Record> records = future_count.get();

    herr_t status = H5TBappend_records(file, "counts", records.size(), record_size, record_offset,
                                       field_sizes, records.data());
    if (status != 0)
    {
      std::cerr << "Error appending record, status = " << status << std::endl;
    }
  }
}

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 6)
    {
      std::cerr << "usage: " << argv[0] << " cell_type bin_size ucsc_chrom_size_path bam_file_path hdf5_file\n"
        << "\ne.g. " << argv[0] << " mm1s 100000 /grail/annotations/ucsc_chromSize.txt"
        << "\n      /ifs/labs/bradner/bam/hg18/mm1s/04032013_D1L57ACXX_4.TTAGGC.hg18.bwt.sorted.bam\n"
        << "\nnote that this application is intended to be run from bamliquidator_batch.py -- see"
        << "\nhttps://github.com/BradnerLab/pipeline/wiki for more information"
        << std::endl;
      return 1;
    }

    const std::string cell_type = argv[1];
    const unsigned int bin_size = boost::lexical_cast<unsigned int>(argv[2]);
    const std::string ucsc_chrom_size_path = argv[3];
    const std::string bam_file_path = argv[4];
    const std::string hdf5_file_path = argv[5];

    if (bin_size == 0)
    {
      std::cerr << "bin size cannot be zero" << std::endl;
      return 2;
    }

    const ChromosomeLengths lengths(ucsc_chrom_size_path);

    hid_t h5file = H5Fopen(hdf5_file_path.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
    if (h5file < 0)
    {
      std::cerr << "Failed to open H5 file " << hdf5_file_path << std::endl;
      return 3;
    }

    batch(h5file, cell_type, bin_size, lengths, bam_file_path);

    H5Fclose(h5file);

    return 0;
  }
  catch(const std::exception& e)
  {
    std::cerr << "Unhandled exception: " << e.what() << std::endl;

    return 4;
  }
}

/* The MIT License (MIT)

   Copyright (c) 2013 John DiMatteo

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
 */
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/PointCloud.h>
#include <math.h>

#define PI 3.14159265
#define DEG_TO_RAD(x) (x * PI / 180.0)
#define MAX_RANGE 3.0 // meters
#define MIN_ANGLE -144 // degrees
#define MAX_ANGLE 144 // degrees
#define DEG_INCREMENT 2 // degrees
#define NUM_READINGS ((MAX_ANGLE-MIN_ANGLE) / DEG_INCREMENT + 1)

#define NUMBER_OF_SONAR_SENSORS 8
#define magnitude(x,y) sqrt((x)*(x) + (y)*(y))

// Amigobot sonar directions in degrees
// TODO : Move to cfg file
static int sonar_directions[] = {90, 44, 12, -12, -44, -90, -144, 144};

// Initialize sonar data with default values
double sonar_data[NUMBER_OF_SONAR_SENSORS] = {1, 1, 1, 1, 1, 1, 1, 1};
ros::Time sonar_timestamp;

// -144 to 144 degrees in 2 deg increments, plus 1 to include angle max in array

// 25 Hz for sonar
double sonar_frequency = 25;

double ranges[NUM_READINGS];
double intensities[NUM_READINGS];

ros::Publisher scan_pub;

// Uses global sonar_data to generate laserscan data and publish
// Uses global sonar_timestamp to generate timestamp
void publishLaserFromSonar() {
  // Generate empty data outside of the range for our laser scan
  for(unsigned int i = 0; i < NUM_READINGS; ++i){
    ranges[i] = MAX_RANGE + 1.0;
    intensities[i] = 0;
  }

  // Generate actual sonar data in correct positions
  for (unsigned int i = 0; i < NUMBER_OF_SONAR_SENSORS; ++i)
  {
    // Place sonar data into correct position in ranges array
    int index = (sonar_directions[i] - MIN_ANGLE)/DEG_INCREMENT;
    ranges[index] = sonar_data[i];
    intensities[index] = 1.0;
  }

  // Populate the LaserScan message
  sensor_msgs::LaserScan scan;
  scan.header.stamp = sonar_timestamp;
  scan.header.frame_id = "base_link";
  scan.angle_min = DEG_TO_RAD(MIN_ANGLE);
  scan.angle_max = DEG_TO_RAD(MAX_ANGLE);
  scan.angle_increment = DEG_TO_RAD(DEG_INCREMENT);
  scan.time_increment = (1.0 / sonar_frequency) / (NUM_READINGS);
  scan.range_min = 0.0;
  scan.range_max = MAX_RANGE;

  scan.ranges.resize(NUM_READINGS);
  scan.intensities.resize(NUM_READINGS);
  for(unsigned int i = 0; i < NUM_READINGS; ++i){
    scan.ranges[i] = ranges[i];
    scan.intensities[i] = intensities[i];
  }
  scan_pub.publish(scan);
}

// Store most recent sonar data
void sonarCallback(const sensor_msgs::PointCloud::ConstPtr& msg){
  // Extract distances from depth cloud
  for (unsigned int i = 0; i < NUMBER_OF_SONAR_SENSORS; ++i) {
    sonar_data[i] = magnitude(msg->points[i].x, msg->points[i].y);
  }
  // Get time of scan
  sonar_timestamp = msg->header.stamp;

  publishLaserFromSonar();
}

int main(int argc, char** argv){
  // Make sure that the number of values in sonar_direction matches number of sensors
  assert(sizeof(sonar_directions)/sizeof(int) == NUMBER_OF_SONAR_SENSORS);

  ros::init(argc, argv, "laser_scan_publisher");
  ros::NodeHandle n;

  // Publish generated laserscan data with a queue size of 50
  scan_pub = n.advertise<sensor_msgs::LaserScan>("scan", 50);

  // Subscribe to sonar data with queue size of 100
  ros::Subscriber goal_sub = n.subscribe("amigobot_node/sonar", 100, sonarCallback);

  ros::spin();
}<commit_msg>p3 fix with tf_prefix<commit_after>#include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <sensor_msgs/PointCloud.h>
#include <math.h>

#define PI 3.14159265
#define DEG_TO_RAD(x) (x * PI / 180.0)
#define MAX_RANGE 3.0 // meters
#define MIN_ANGLE -144 // degrees
#define MAX_ANGLE 144 // degrees
#define DEG_INCREMENT 2 // degrees
#define NUM_READINGS ((MAX_ANGLE-MIN_ANGLE) / DEG_INCREMENT + 1)

#define NUMBER_OF_SONAR_SENSORS 8
#define magnitude(x,y) sqrt((x)*(x) + (y)*(y))

// Amigobot sonar directions in degrees
// TODO : Move to cfg file
// static int sonar_directions[] = {90, 44, 12, -12, -44, -90, -144, 144};

// p3dx sonar directions in degrees
static int sonar_directions[] = {90, 67.5, 45, 22.5, -22.5, -45, -67.5, -90};

// Initialize sonar data with default values
double sonar_data[NUMBER_OF_SONAR_SENSORS] = {1, 1, 1, 1, 1, 1, 1, 1};
ros::Time sonar_timestamp;

// -144 to 144 degrees in 2 deg increments, plus 1 to include angle max in array

// 25 Hz for sonar
double sonar_frequency = 25;

double ranges[NUM_READINGS];
double intensities[NUM_READINGS];

ros::Publisher scan_pub;

// Transform prefix, set as param
std::string tf_prefix;

// Uses global sonar_data to generate laserscan data and publish
// Uses global sonar_timestamp to generate timestamp
void publishLaserFromSonar() {
  // Generate empty data outside of the range for our laser scan
  for(unsigned int i = 0; i < NUM_READINGS; ++i){
    ranges[i] = MAX_RANGE + 1.0;
    intensities[i] = 0;
  }

  // Generate actual sonar data in correct positions
  for (unsigned int i = 0; i < NUMBER_OF_SONAR_SENSORS; ++i)
  {
    // Place sonar data into correct position in ranges array
    int index = (sonar_directions[i] - MIN_ANGLE)/DEG_INCREMENT;
    ranges[index] = sonar_data[i];
    intensities[index] = 0.5;
  }

  // Populate the LaserScan message
  sensor_msgs::LaserScan scan;
  scan.header.stamp = sonar_timestamp;
  scan.header.frame_id = tf_prefix + "/base_link";
  scan.angle_min = DEG_TO_RAD(MIN_ANGLE);
  scan.angle_max = DEG_TO_RAD(MAX_ANGLE);
  scan.angle_increment = DEG_TO_RAD(DEG_INCREMENT);
  scan.time_increment = (1.0 / sonar_frequency) / (NUM_READINGS);
  scan.range_min = 0.0;
  scan.range_max = MAX_RANGE;

  scan.ranges.resize(NUM_READINGS);
  scan.intensities.resize(NUM_READINGS);
  for(unsigned int i = 0; i < NUM_READINGS; ++i){
    scan.ranges[i] = ranges[i];
    scan.intensities[i] = intensities[i];
  }
  scan_pub.publish(scan);
}

// Store most recent sonar data
void sonarCallback(const sensor_msgs::PointCloud::ConstPtr& msg){
  // Extract distances from depth cloud
  for (unsigned int i = 0; i < NUMBER_OF_SONAR_SENSORS; ++i) {
    sonar_data[i] = magnitude(msg->points[i].x, msg->points[i].y);
  }
  // Get time of scan
  sonar_timestamp = msg->header.stamp;

  publishLaserFromSonar();
}

int main(int argc, char** argv){
  // Make sure that the number of values in sonar_direction matches number of sensors
  assert(sizeof(sonar_directions)/sizeof(int) == NUMBER_OF_SONAR_SENSORS);

  ros::init(argc, argv, "laser_scan_publisher");
  ros::NodeHandle n;

  // Get TF prefix
  tf_prefix = "";
  if (n.getParam("tf_prefix", tf_prefix))
      ROS_INFO_STREAM("Read tf prefix: " << tf_prefix);
  else
      ROS_ERROR_STREAM("Did not read tf_prefix: default = " << tf_prefix);

  // Publish generated laserscan data with a queue size of 50
  scan_pub = n.advertise<sensor_msgs::LaserScan>("scan", 50);

  // Subscribe to sonar data with queue size of 100
  ros::Subscriber goal_sub = n.subscribe("p3_node/sonar", 100, sonarCallback);

  ros::spin();
}<|endoftext|>


<commit_before><commit_msg>do not use INFINITY (or NAN while at it..) macro<commit_after><|endoftext|>


<commit_before>#include "../set_stream_precision.hxx"

#include <El.hpp>

#include <boost/filesystem.hpp>

void write_spectrum(const boost::filesystem::path &output_path,
                    const std::vector<std::vector<El::BigFloat>> &zeros)
{
  boost::filesystem::ofstream outfile(output_path);
  if(!outfile.good())
    {
      throw std::runtime_error("Problem when opening output file: '"
                               + output_path.string() + "'");
    }
  set_stream_precision(outfile);
  outfile << "[";
  for(auto block(zeros.begin()); block != zeros.end(); ++block)
    {
      if(block != zeros.begin())
        {
          outfile << ",";
        }
      outfile << "\n  [";
      for(auto zero(block->begin()); zero != block->end(); ++zero)
        {
          if(zero != block->begin())
            {
              outfile << ",";
            }
          outfile << "\n    \"" << *zero << "\"";
        }
      outfile << "\n  ]";
    }
  outfile << "\n]\n";
  if(!outfile.good())
    {
      throw std::runtime_error("Problem when writing to output file: '"
                               + output_path.string() + "'");
    }
}
<commit_msg>Make write_spectrum work in MPI<commit_after>#include "../set_stream_precision.hxx"

#include <El.hpp>

#include <boost/filesystem.hpp>

void write_spectrum(const boost::filesystem::path &output_path,
                    const std::vector<std::vector<El::BigFloat>> &zeros)
{
  // Synchronize zeros
  // This is waaaay more work than it should be.
  std::vector<int32_t> sizes(zeros.size(), 0);
  for(size_t index(0); index != zeros.size(); ++index)
    {
      sizes.at(index) = zeros.at(index).size();
    }
  El::mpi::AllReduce(sizes.data(), sizes.size(), El::mpi::MAX,
                     El::mpi::COMM_WORLD);
  const int64_t num_elements(std::accumulate(sizes.begin(), sizes.end(), 0));
  std::vector<El::BigFloat> zero_flattened;
  zero_flattened.reserve(num_elements);
  for(size_t block_index(0); block_index != zeros.size(); ++block_index)
    {
      for(int32_t zero_index(0); zero_index != sizes[block_index];
          ++zero_index)
        {
          if(zeros.at(block_index).empty())
            {
              zero_flattened.emplace_back(0);
            }
          else
            {
              zero_flattened.emplace_back(
                zeros.at(block_index).at(zero_index));
            }
        }
    }
  El::mpi::Reduce(zero_flattened.data(), zero_flattened.size(), 0,
                  El::mpi::COMM_WORLD);

  // Write the file
  if(El::mpi::Rank() == 0)
    {
      boost::filesystem::ofstream outfile(output_path);
      if(!outfile.good())
        {
          throw std::runtime_error("Problem when opening output file: '"
                                   + output_path.string() + "'");
        }
      set_stream_precision(outfile);
      outfile << "[";
      auto iterator(zero_flattened.begin());
      for(size_t block_index(0); block_index != sizes.size(); ++block_index)
        {
          if(block_index != 0)
            {
              outfile << ",";
            }
          outfile << "\n  [";
          for(int64_t zero_index(0); zero_index != sizes.at(block_index);
              ++zero_index)
            {
              if(zero_index != 0)
                {
                  outfile << ",";
                }
              outfile << "\n    \"" << *iterator << "\"";
              ++iterator;
            }
          outfile << "\n  ]";
        }
      outfile << "\n]\n";
      if(!outfile.good())
        {
          throw std::runtime_error("Problem when writing to output file: '"
                                   + output_path.string() + "'");
        }
    }
}
<|endoftext|>


<commit_before>#ifndef __STAN__PROB__INTERNAL_MATH_HPP__
#define __STAN__PROB__INTERNAL_MATH_HPP__

#include <math.h>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/beta.hpp>

namespace stan {

  namespace math {

      // Gradient of the hypergeometric function 2F1(a, b | c | z) with respect to a and c
      void grad2F1(double& gradA, double& gradC, double a, double b, double c, double z, double precision = 1e-6)
      {

          gradA = 0;
          gradC = 0;

          double gradAold = 0;
          double gradCold = 0;

          int k = 0;
          double tOld = 1.0;
          double tNew = (a * b) / c;

          while(fabs(tNew) > precision)
          {

              gradAold = tNew * (gradAold / tOld + 1.0 / (a + k) );
              gradCold = tNew * (gradCold / tOld - 1.0 / (c + k) );

              gradA += gradAold;
              gradC += gradCold;

              ++k;

              tNew = ( (a + k) / (c + k) ) * ( (b + k) / (k + 1) ) * z * tOld;

              if(tNew == 0) break;

          }

      }

      // Gradient of the incomplete beta function beta(a, b, z)
      // with respect to the first two arguments, using the
      // equivalence to a hypergeometric function.
      // See http://dlmf.nist.gov/8.17#ii
      void gradIncBeta(double& g1, double& g2, double a, double b, double z)
      {

          double c1 = std::log(z);
          double c2 = std::log(1 - z);
          double c3 = boost::math::beta(a, b, z);

          double C = std::exp( a * c1 + b * c2 ) / a;

          double dF1 = 0;
          double dF2 = 0;

          grad2F1(dF1, dF2, a + b, 1, a + 1, z);

          g1 = (c1 - 1.0 / a) * c3 + C * (dF1 + dF2);
          g2 = c2 * c3 + C * dF1;

      }

      // Gradient of the regularized incomplete beta function ibeta(a, b, z)
      void gradRegIncBeta(double& g1, double& g2, double a, double b, double z,
                          double digammaA, double digammaB, double digammaSum, double betaAB)
      {

          double dBda = 0;
          double dBdb = 0;

          gradIncBeta(dBda, dBdb, a, b, z);

          double b1 = boost::math::beta(a, b, z);

          g1 = ( dBda - b1 * (digammaA - digammaSum) ) / betaAB;
          g2 = ( dBdb - b1 * (digammaB - digammaSum) ) / betaAB;

      }

      // Gradient of the regularized incomplete gamma functions igamma(a, g)
      double gradRegIncGamma(double a, double z, double g, double dig, double precision = 1e-6)
      {

          using boost::math::gamma_p;

          double S = 0;
          double s = 1;
          double l = std::log(z);

          int k = 0;
          double delta = s / (a * a);

          while (fabs(delta) > precision)
          {
              S += delta;
              ++k;
              s *= - z / k;
              delta = s / ((k + a) * (k + a));
          }

          // Precomputed values
          // dig -> digamma(a)
          // g   -> g(a)
          return gamma_p(a, z) * ( dig - l ) + std::exp( a * l ) * S / g;

      }

  }

}

#endif<commit_msg>Added 3F2 and its gradient.<commit_after>#ifndef __STAN__PROB__INTERNAL_MATH_HPP__
#define __STAN__PROB__INTERNAL_MATH_HPP__

#include <math.h>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/beta.hpp>

namespace stan {

  namespace math {

      double F32(double a, double b, double c, double d, double e, double z)
      {

          double F = 1;

          double tOld = 1;
          double tNew = 0;

          double logT = 0;

          double logZ = std::log(z);

          for(int k = 0; k < 500; ++k)
          {

              double p = (a + k) * (b + k) * (c + k) / ( (d + k) * (e + k) * (k + 1) );

              // If a, b, or c is a negative integer then the series terminates
              // after a finite number of interations
              if(p == 0) break;

              logT += (p > 0 ? 1 : -1) * std::log(fabs(p)) + logZ;

              tNew = std::exp(logT);

              F += tNew;

              tOld = tNew;

          }

          return F;

      }

      void gradF32(double* g, double a, double b, double c, double d, double e, double z)
      {

          double gOld[6];

          for(double *p = g; p != g + 6; ++p) *p = 0;
          for(double *p = gOld; p != gOld + 6; ++p) *p = 0;

          double tOld = 1;
          double tNew = 0;

          double logT = 0;

          double logZ = std::log(z);

          for(int k = 0; k < 500; ++k)
          {

              double C = (a + k) / (d + k);
              C *= (b + k) / (e + k);
              C *= (c + k) / (1 + k);

              // If a, b, or c is a negative integer then the series terminates
              // after a finite number of interations
              if(C == 0) break;

              logT += (C > 0 ? 1 : -1) * std::log(fabs(C)) + logZ;

              tNew = std::exp(logT);

              gOld[0] = tNew * (gOld[0] / tOld + 1.0 / (a + k) );
              gOld[1] = tNew * (gOld[1] / tOld + 1.0 / (b + k) );
              gOld[2] = tNew * (gOld[2] / tOld + 1.0 / (c + k) );

              gOld[3] = tNew * (gOld[3] / tOld - 1.0 / (d + k) );
              gOld[4] = tNew * (gOld[4] / tOld - 1.0 / (e + k) );

              gOld[5] = tNew * ( gOld[5] / tOld + 1.0 / z );

              for(int i = 0; i < 6; ++i) g[i] += gOld[i];

              tOld = tNew;

          }

      }

      // Gradient of the hypergeometric function 2F1(a, b | c | z) with respect to a and c
      void grad2F1(double& gradA, double& gradC, double a, double b, double c, double z, double precision = 1e-6)
      {

          gradA = 0;
          gradC = 0;

          double gradAold = 0;
          double gradCold = 0;

          int k = 0;
          double tOld = 1.0;
          double tNew = (a * b) / c;

          while(fabs(tNew) > precision)
          {

              gradAold = tNew * (gradAold / tOld + 1.0 / (a + k) );
              gradCold = tNew * (gradCold / tOld - 1.0 / (c + k) );

              gradA += gradAold;
              gradC += gradCold;

              ++k;

              tNew = ( (a + k) / (c + k) ) * ( (b + k) / (k + 1) ) * z * tOld;

              if(tNew == 0) break;

          }

      }

      // Gradient of the incomplete beta function beta(a, b, z)
      // with respect to the first two arguments, using the
      // equivalence to a hypergeometric function.
      // See http://dlmf.nist.gov/8.17#ii
      void gradIncBeta(double& g1, double& g2, double a, double b, double z)
      {

          double c1 = std::log(z);
          double c2 = std::log(1 - z);
          double c3 = boost::math::beta(a, b, z);

          double C = std::exp( a * c1 + b * c2 ) / a;

          double dF1 = 0;
          double dF2 = 0;

          grad2F1(dF1, dF2, a + b, 1, a + 1, z);

          g1 = (c1 - 1.0 / a) * c3 + C * (dF1 + dF2);
          g2 = c2 * c3 + C * dF1;

      }

      // Gradient of the regularized incomplete beta function ibeta(a, b, z)
      void gradRegIncBeta(double& g1, double& g2, double a, double b, double z,
                          double digammaA, double digammaB, double digammaSum, double betaAB)
      {

          double dBda = 0;
          double dBdb = 0;

          gradIncBeta(dBda, dBdb, a, b, z);

          double b1 = boost::math::beta(a, b, z);

          g1 = ( dBda - b1 * (digammaA - digammaSum) ) / betaAB;
          g2 = ( dBdb - b1 * (digammaB - digammaSum) ) / betaAB;

      }

      // Gradient of the regularized incomplete gamma functions igamma(a, g)
      double gradRegIncGamma(double a, double z, double g, double dig, double precision = 1e-6)
      {

          using boost::math::gamma_p;

          double S = 0;
          double s = 1;
          double l = std::log(z);

          int k = 0;
          double delta = s / (a * a);

          while (fabs(delta) > precision)
          {
              S += delta;
              ++k;
              s *= - z / k;
              delta = s / ((k + a) * (k + a));
          }

          // Precomputed values
          // dig -> digamma(a)
          // g   -> g(a)
          return gamma_p(a, z) * ( dig - l ) + std::exp( a * l ) * S / g;

      }

  }

}

#endif<|endoftext|>


<commit_before>#include <algorithm> // random_shuffle, transform
#include <cassert>
#include <chrono>
#include <random>
#include <utility>  // pair

#include <sdd/order/order.hh>
#include <sdd/order/strategies/force.hh>

#include "mc/make_order.hh"
#include "mc/dump.hh"

namespace pnmc { namespace mc {

using sdd_conf = sdd::conf1;

/*------------------------------------------------------------------------------------------------*/

struct mk_order_visitor
  : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>>
{
  using order_identifier = sdd::order_identifier<sdd_conf>;
  using result_type = std::pair<order_identifier, sdd::order_builder<sdd_conf>>;
  using order_builder = sdd::order_builder<sdd_conf>;

  const conf::pnmc_configuration& conf;
  mutable unsigned int artificial_id_counter;

  mk_order_visitor(const conf::pnmc_configuration& c)
    : conf(c), artificial_id_counter(0)
  {}

  // Place: base case of the recursion, there's no more possible nested hierarchies.
  result_type
  operator()(const pn::place* p)
  const noexcept
  {
    return std::make_pair(order_identifier(p->id), order_builder());
  }

  // Hierarchy.
  result_type
  operator()(const pn::module_node& m)
  const noexcept
  {
    assert(not m.nested.empty());

    std::deque<result_type> tmp;

    for (const auto& h : m.nested)
    {
      const auto res = boost::apply_visitor(*this, *h);
      tmp.push_back(res);
    }

    std::size_t height = 0;
    for (const auto& p : tmp)
    {
      if (not p.second.empty())
      {
        height += p.second.height();
      }
      else
      {
        height += 1; // place
      }
    }

    order_builder ob;
    if (height <= conf.order_min_height)
    {
      order_identifier id;
      for (const auto& p : tmp)
      {
        if (not p.second.empty())
        {
          ob = p.second << ob;
        }
        else // place
        {
          ob.push(p.first, p.second);
        }
      }
      return result_type(id, ob);
    }
    else
    {
      for (const auto& p : tmp)
      {
        ob.push(p.first, p.second);
      }
    }

    return std::make_pair(order_identifier(m.id) , ob);
  }
};

/*------------------------------------------------------------------------------------------------*/

sdd::order<sdd_conf>
make_order(const conf::pnmc_configuration& conf, statistics& stats, const pn::net& net)
{
  if (conf.order_ordering_force)
  {
    std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();
    using identifier_type = sdd_conf::Identifier;
    using vertex = sdd::force::vertex<identifier_type>;
    using hyperedge = sdd::force::hyperedge<identifier_type>;

    sdd::force::hypergraph<sdd_conf> graph;
    std::vector<identifier_type> identifiers;
    for (const auto& transition : net.transitions())
    {
      for (const auto& arc : transition.pre)
      {
        identifiers.emplace_back(arc.first);
      }

      for (const auto& arc : transition.post)
      {
        identifiers.emplace_back(arc.first);
      }
      graph.add_hyperedge(identifiers.cbegin(), identifiers.cend());
      identifiers.clear();
    }
    const auto o = force_ordering(graph);
    stats.force_duration = std::chrono::system_clock::now() - start;
    dump_hypergraph_dot(conf, graph);
    return sdd::order<sdd_conf>(o);
  }
  else if (not conf.order_force_flat and net.modules)
  {
    return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(conf), *net.modules).second);
  }
  else
  {
    sdd::order_builder<sdd_conf> ob;
    if (conf.order_random)
    {
      std::vector<std::string> tmp;
      tmp.reserve(net.places().size());
      std::transform( net.places().cbegin(), net.places().cend(), std::back_inserter(tmp)
                    , [](const pn::place& p){return p.id;});
      std::random_device rd;
      std::mt19937 g(rd());
      std::shuffle(tmp.begin(), tmp.end(), g);
      for (const auto& id : tmp)
      {
        ob.push(id);
      }
    }
    else
    {
      for (const auto& place : net.places())
      {
        ob.push(place.id);
      }
    }
    return sdd::order<sdd_conf>(ob);
  }
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace pnmc::mc
<commit_msg>Comments.<commit_after>#include <algorithm> // random_shuffle, transform
#include <cassert>
#include <chrono>
#include <random>
#include <utility>  // pair

#include <sdd/order/order.hh>
#include <sdd/order/strategies/force.hh>

#include "mc/make_order.hh"
#include "mc/dump.hh"

namespace pnmc { namespace mc {

using sdd_conf = sdd::conf1;

/*------------------------------------------------------------------------------------------------*/

struct mk_order_visitor
  : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>>
{
  using order_identifier = sdd::order_identifier<sdd_conf>;
  using result_type = std::pair<order_identifier, sdd::order_builder<sdd_conf>>;
  using order_builder = sdd::order_builder<sdd_conf>;

  const conf::pnmc_configuration& conf;
  mutable unsigned int artificial_id_counter;

  mk_order_visitor(const conf::pnmc_configuration& c)
    : conf(c), artificial_id_counter(0)
  {}

  // Place: base case of the recursion, there's no more possible nested hierarchies.
  result_type
  operator()(const pn::place* p)
  const noexcept
  {
    return std::make_pair(order_identifier(p->id), order_builder());
  }

  // Hierarchy.
  result_type
  operator()(const pn::module_node& m)
  const noexcept
  {
    assert(not m.nested.empty());

    std::deque<result_type> tmp;

    for (const auto& h : m.nested)
    {
      const auto res = boost::apply_visitor(*this, *h);
      tmp.push_back(res);
    }

    std::size_t height = 0;
    for (const auto& p : tmp)
    {
      if (not p.second.empty())
      {
        height += p.second.height();
      }
      else
      {
        height += 1; // place
      }
    }

    order_builder ob;
    if (height <= conf.order_min_height)
    {
      order_identifier id;
      for (const auto& p : tmp)
      {
        if (not p.second.empty())
        {
          ob = p.second << ob;
        }
        else // place
        {
          ob.push(p.first, p.second);
        }
      }
      return result_type(id, ob);
    }
    else
    {
      for (const auto& p : tmp)
      {
        ob.push(p.first, p.second);
      }
    }

    return std::make_pair(order_identifier(m.id) , ob);
  }
};

/*------------------------------------------------------------------------------------------------*/

sdd::order<sdd_conf>
make_order(const conf::pnmc_configuration& conf, statistics& stats, const pn::net& net)
{
  if (conf.order_ordering_force)
  {
    std::chrono::time_point<std::chrono::system_clock> start = std::chrono::system_clock::now();
    using identifier_type = sdd_conf::Identifier;
    using vertex = sdd::force::vertex<identifier_type>;
    using hyperedge = sdd::force::hyperedge<identifier_type>;

    // The hypergraph that stores connections between the places of the Petri net.
    sdd::force::hypergraph<sdd_conf> graph;

    // Temporary placeholder for identifiers of an hyperedge.
    std::vector<identifier_type> identifiers;

    // A new connection is created for each transition of the Petri net.
    for (const auto& transition : net.transitions())
    {
      for (const auto& arc : transition.pre)
      {
        identifiers.emplace_back(arc.first);
      }

      for (const auto& arc : transition.post)
      {
        identifiers.emplace_back(arc.first);
      }
      graph.add_hyperedge(identifiers.cbegin(), identifiers.cend());

      // We use this container again in the next loop.
      identifiers.clear();
    }
    // Apply the FORCE ordering strategy.
    const auto o = force_ordering(graph);
    stats.force_duration = std::chrono::system_clock::now() - start;

    // Dump the hypergraph to a DOT file if required by the configuration.
    dump_hypergraph_dot(conf, graph);
    return sdd::order<sdd_conf>(o);
  }
  else if (not conf.order_force_flat and net.modules)
  {
    return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(conf), *net.modules).second);
  }
  else
  {
    sdd::order_builder<sdd_conf> ob;
    if (conf.order_random)
    {
      std::vector<std::string> tmp;
      tmp.reserve(net.places().size());
      std::transform( net.places().cbegin(), net.places().cend(), std::back_inserter(tmp)
                    , [](const pn::place& p){return p.id;});
      std::random_device rd;
      std::mt19937 g(rd());
      std::shuffle(tmp.begin(), tmp.end(), g);
      for (const auto& id : tmp)
      {
        ob.push(id);
      }
    }
    else
    {
      for (const auto& place : net.places())
      {
        ob.push(place.id);
      }
    }
    return sdd::order<sdd_conf>(ob);
  }
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace pnmc::mc
<|endoftext|>


<commit_before>#include <X86/CpuRegisters.hh>
#include <PageFrameAllocator.hh>
#include <Parameters.hh>

class PageDirectory
{
   void init()
   {
      uint32_t* pageDirectory = (uint32_t* )PageFrameAllocator::getFreePage();
      KASSERT(pageDirectory != 0);

      memset(pageDirectory, 0, PageSize);
   }
};
<commit_msg>fix build<commit_after>#include <X86/CpuRegisters.hh>
#include <PageFrameAllocator.hh>
#include <Parameters.hh>
#include <Debug.hh>

#include <stdint.h>
#include <string.h>

class PageDirectory
{
   void init()
   {
      uint32_t* pageDirectory = (uint32_t* )PageFrameAllocator::getFreePage();
      KASSERT(pageDirectory != 0);

      memset(pageDirectory, 0, PageSize);
   }
};
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkCommand.cxx

  Copyright (c) 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 "vtkCommand.h"
#include "vtkDebugLeaks.h"

// This list should only contain the initial, contiguous
// set of events and should not include UserEvent
static const char *vtkCommandEventStrings[] = {
  "NoEvent",
  "AnyEvent",
  "DeleteEvent",
  "StartEvent",
  "EndEvent",
  "RenderEvent",
  "ProgressEvent",
  "PickEvent",
  "StartPickEvent",
  "EndPickEvent",
  "AbortCheckEvent",
  "ExitEvent",
  "LeftButtonPressEvent",
  "LeftButtonReleaseEvent",
  "MiddleButtonPressEvent",
  "MiddleButtonReleaseEvent",
  "RightButtonPressEvent",
  "RightButtonReleaseEvent",
  "EnterEvent",
  "LeaveEvent",
  "KeyPressEvent",
  "KeyReleaseEvent",
  "CharEvent",
  "ExposeEvent",
  "ConfigureEvent",
  "TimerEvent",
  "MouseMoveEvent",
  "MouseWheelForwardEvent",
  "MouseWheelBackwardEvent",
  "ActiveCameraEvent",
  "CreateCameraEvent",
  "ResetCameraEvent",
  "ResetCameraClippingRangeEvent",
  "ModifiedEvent",
  "WindowLevelEvent",
  "StartWindowLevelEvent",
  "EndWindowLevelEvent",
  "ResetWindowLevelEvent",
  "SetOutputEvent",
  "ErrorEvent",
  "WarningEvent",
  "StartInteractionEvent",
  "InteractionEvent",
  "EndInteractionEvent",
  "EnableEvent",
  "DisableEvent",
  "CreateTimerEvent",
  "DestroyTimerEvent",
  "PlacePointEvent",
  "PlaceWidgetEvent",
  "CursorChangedEvent",
  "ExecuteInformationEvent",
  "RenderWindowMessageEvent",
  "WrongTagEvent",
  "StartAnimationCueEvent",
  "AnimationCueTickEvent",
  "EndAnimationCueEvent",
  "VolumeMapperRenderEndEvent",
  "VolumeMapperRenderProgressEvent",
  "VolumeMapperRenderStartEvent",
  "VolumeMapperComputeGradientsEndEvent",
  "VolumeMapperComputeGradientsProgressEvent",
  "VolumeMapperComputeGradientsStartEvent",
  "WidgetModifiedEvent",
  "WidgetValueChangedEvent",
  "WidgetActivateEvent",
  "ConnectionCreatedEvent",
  "ConnectionClosedEvent",
  "DomainModifiedEvent",
  "PropertyModifiedEvent",
  "UpdateEvent",
  "RegisterEvent",
  "UnRegisterEvent",
  "UpdateInformationEvent",
  "AnnotationChangedEvent",
  "SelectionChangedEvent",
  "UpdatePropertyEvent",
  "ViewProgressEvent",
  "UpdateDataEvent",
  "CurrentChangedEvent",
  "ComputeVisiblePropBoundsEvent",
  "TDxMotionEvent", // 3D Connexion device event
  "TDxButtonPressEvent", // 3D Connexion device event
  "TDxButtonReleaseEvent", // 3D Connexion device event
  "HoverEvent",
  "LoadStateEvent",
  "SaveStateEvent",
  "StateChangedEvent",
  "WindowMakeCurrentEvent",
  "WindowIsCurrentEvent",
  "WindowFrameEvent",
  NULL
};

//----------------------------------------------------------------
vtkCommand::vtkCommand():AbortFlag(0),PassiveObserver(0)
{
#ifdef VTK_DEBUG_LEAKS
  vtkDebugLeaks::ConstructClass("vtkCommand or subclass");
#endif
}

//----------------------------------------------------------------
void vtkCommand::UnRegister()
{
  int refcount = this->GetReferenceCount()-1;
  this->SetReferenceCount(refcount);
  if (refcount <= 0)
    {
#ifdef VTK_DEBUG_LEAKS
    vtkDebugLeaks::DestructClass("vtkCommand or subclass");
#endif
    delete this;
    }
}

//----------------------------------------------------------------
const char *vtkCommand::GetStringFromEventId(unsigned long event)
{
  static unsigned long numevents = 0;

  // find length of table
  if (!numevents)
    {
    while (vtkCommandEventStrings[numevents] != NULL)
      {
      numevents++;
      }
    }

  if (event < numevents)
    {
    return vtkCommandEventStrings[event];
    }
  else if (event == vtkCommand::UserEvent)
    {
    return "UserEvent";
    }
  else
    {
    return "NoEvent";
    }
}

//----------------------------------------------------------------
unsigned long vtkCommand::GetEventIdFromString(const char *event)
{
  unsigned long i;

  for (i = 0; vtkCommandEventStrings[i] != NULL; i++)
    {
    if (!strcmp(vtkCommandEventStrings[i],event))
      {
      return i;
      }
    }
  if (!strcmp("UserEvent",event))
    {
    return vtkCommand::UserEvent;
    }
  return vtkCommand::NoEvent;
}

<commit_msg>Replace runtime counting with compile time counting.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCommand.cxx

  Copyright (c) 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 "vtkCommand.h"
#include "vtkDebugLeaks.h"

// This list should only contain the initial, contiguous
// set of events and should not include UserEvent
static const char *vtkCommandEventStrings[] = {
  "NoEvent",
  "AnyEvent",
  "DeleteEvent",
  "StartEvent",
  "EndEvent",
  "RenderEvent",
  "ProgressEvent",
  "PickEvent",
  "StartPickEvent",
  "EndPickEvent",
  "AbortCheckEvent",
  "ExitEvent",
  "LeftButtonPressEvent",
  "LeftButtonReleaseEvent",
  "MiddleButtonPressEvent",
  "MiddleButtonReleaseEvent",
  "RightButtonPressEvent",
  "RightButtonReleaseEvent",
  "EnterEvent",
  "LeaveEvent",
  "KeyPressEvent",
  "KeyReleaseEvent",
  "CharEvent",
  "ExposeEvent",
  "ConfigureEvent",
  "TimerEvent",
  "MouseMoveEvent",
  "MouseWheelForwardEvent",
  "MouseWheelBackwardEvent",
  "ActiveCameraEvent",
  "CreateCameraEvent",
  "ResetCameraEvent",
  "ResetCameraClippingRangeEvent",
  "ModifiedEvent",
  "WindowLevelEvent",
  "StartWindowLevelEvent",
  "EndWindowLevelEvent",
  "ResetWindowLevelEvent",
  "SetOutputEvent",
  "ErrorEvent",
  "WarningEvent",
  "StartInteractionEvent",
  "InteractionEvent",
  "EndInteractionEvent",
  "EnableEvent",
  "DisableEvent",
  "CreateTimerEvent",
  "DestroyTimerEvent",
  "PlacePointEvent",
  "PlaceWidgetEvent",
  "CursorChangedEvent",
  "ExecuteInformationEvent",
  "RenderWindowMessageEvent",
  "WrongTagEvent",
  "StartAnimationCueEvent",
  "AnimationCueTickEvent",
  "EndAnimationCueEvent",
  "VolumeMapperRenderEndEvent",
  "VolumeMapperRenderProgressEvent",
  "VolumeMapperRenderStartEvent",
  "VolumeMapperComputeGradientsEndEvent",
  "VolumeMapperComputeGradientsProgressEvent",
  "VolumeMapperComputeGradientsStartEvent",
  "WidgetModifiedEvent",
  "WidgetValueChangedEvent",
  "WidgetActivateEvent",
  "ConnectionCreatedEvent",
  "ConnectionClosedEvent",
  "DomainModifiedEvent",
  "PropertyModifiedEvent",
  "UpdateEvent",
  "RegisterEvent",
  "UnRegisterEvent",
  "UpdateInformationEvent",
  "AnnotationChangedEvent",
  "SelectionChangedEvent",
  "UpdatePropertyEvent",
  "ViewProgressEvent",
  "UpdateDataEvent",
  "CurrentChangedEvent",
  "ComputeVisiblePropBoundsEvent",
  "TDxMotionEvent", // 3D Connexion device event
  "TDxButtonPressEvent", // 3D Connexion device event
  "TDxButtonReleaseEvent", // 3D Connexion device event
  "HoverEvent",
  "LoadStateEvent",
  "SaveStateEvent",
  "StateChangedEvent",
  "WindowMakeCurrentEvent",
  "WindowIsCurrentEvent",
  "WindowFrameEvent",
  NULL
};

//----------------------------------------------------------------
vtkCommand::vtkCommand():AbortFlag(0),PassiveObserver(0)
{
#ifdef VTK_DEBUG_LEAKS
  vtkDebugLeaks::ConstructClass("vtkCommand or subclass");
#endif
}

//----------------------------------------------------------------
void vtkCommand::UnRegister()
{
  int refcount = this->GetReferenceCount()-1;
  this->SetReferenceCount(refcount);
  if (refcount <= 0)
    {
#ifdef VTK_DEBUG_LEAKS
    vtkDebugLeaks::DestructClass("vtkCommand or subclass");
#endif
    delete this;
    }
}

//----------------------------------------------------------------
const char *vtkCommand::GetStringFromEventId(unsigned long event)
{
  // find length of table
  static unsigned long numevents = sizeof( vtkCommandEventStrings )
    / sizeof( *vtkCommandEventStrings ) - 1; // do not count NULL sentinel

  if (event < numevents)
    {
    return vtkCommandEventStrings[event];
    }
  if (event == vtkCommand::UserEvent)
    {
    return "UserEvent";
    }
  return "NoEvent";
}

//----------------------------------------------------------------
unsigned long vtkCommand::GetEventIdFromString(const char *event)
{
  if (event)
    {
    for (unsigned long i = 0; vtkCommandEventStrings[i] != NULL; i++)
      {
      if (!strcmp(vtkCommandEventStrings[i],event))
        {
        return i;
        }
      }
    if (!strcmp("UserEvent",event))
      {
      return vtkCommand::UserEvent;
      }
    }
  return vtkCommand::NoEvent;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MPreparedStatement.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:19:23 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CONNECTIVITY_SPREPAREDSTATEMENT_HXX
#define CONNECTIVITY_SPREPAREDSTATEMENT_HXX

#ifndef CONNECTIVITY_SRESULTSET_HXX
#include "MResultSet.hxx"
#endif
#ifndef CONNECTIVITY_SSTATEMENT_HXX
#include "MStatement.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XPREPAREDSTATEMENT_HPP_
#include <com/sun/star/sdbc/XPreparedStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_
#include <com/sun/star/sdbc/XParameters.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XMULTIPLERESULTS_HPP_
#include <com/sun/star/sdbc/XMultipleResults.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#include <cppuhelper/compbase5.hxx>
#endif

namespace connectivity
{
    namespace mozab
    {

        class OBoundParam;
        typedef ::cppu::ImplHelper5<    ::com::sun::star::sdbc::XPreparedStatement,
                                        ::com::sun::star::sdbc::XParameters,
                                        ::com::sun::star::sdbc::XResultSetMetaDataSupplier,
                                        ::com::sun::star::sdbc::XMultipleResults,
                                        ::com::sun::star::lang::XServiceInfo> OPreparedStatement_BASE;

        class OPreparedStatement :  public  OStatement_BASE2,
                                    public  OPreparedStatement_BASE
        {
        protected:
            struct Parameter
            {
                ::com::sun::star::uno::Any  aValue;
                sal_Int32                   nDataType;

                Parameter(const ::com::sun::star::uno::Any& rValue,
                          sal_Int32                         rDataType) : aValue(rValue),nDataType(rDataType)
                {
                }

            };

            ::std::vector< Parameter>       m_aParameters;
            //====================================================================
            // Data attributes
            //====================================================================
            sal_Int32                       m_nNumParams;       // Number of parameter markers
                                                                //  for the prepared statement

            ::rtl::OUString                             m_sSqlStatement;
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData >  m_xMetaData;
            sal_Bool                                    m_bPrepared;
            OResultSet*                                 m_pResultSet;
            ::vos::ORef<connectivity::OSQLColumns>      m_xParamColumns;    // the parameter columns
            OValueRow                                   m_aParameterRow;

            void checkParameterIndex(sal_Int32 _parameterIndex);

        protected:
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,
                                                                   const ::com::sun::star::uno::Any& rValue)
                                                                        throw (::com::sun::star::uno::Exception);
            virtual ~OPreparedStatement();

            virtual void SAL_CALL disposing();
            virtual sal_Bool parseSql( const ::rtl::OUString& sql , sal_Bool bAdjusted = sal_False) throw (
                           ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );

            virtual OResultSet* createResultSet();
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> initResultSet();

            void checkAndResizeParameters(sal_Int32 parameterIndex);
            void setParameter(sal_Int32 parameterIndex, const ORowSetValue& x);

            sal_uInt32 AddParameter(connectivity::OSQLParseNode * pParameter,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xCol);
            void scanParameter(OSQLParseNode* pParseNode,::std::vector< OSQLParseNode*>& _rParaNodes);
            void describeColumn(OSQLParseNode* _pParameter,OSQLParseNode* _pNode,const OSQLTable& _xTable);
            void describeParameter();

            virtual void initializeResultSet( OResultSet* _pResult );

        public:
            DECLARE_SERVICE_INFO();
            // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
            OPreparedStatement( OConnection* _pConnection,const ::rtl::OUString& sql);

            //XInterface
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);

            // XPreparedStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL executeUpdate(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL execute(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XParameters
            virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearParameters(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XResultSetMetaDataSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XMultipleResults
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getResultSet(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getUpdateCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL getMoreResults(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}
#endif // CONNECTIVITY_SPREPAREDSTATEMENT_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.6.30); FILE MERGED 2005/11/21 10:07:51 fs 1.6.30.1: #i57457# warning-free code on unx*<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MPreparedStatement.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:44:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CONNECTIVITY_SPREPAREDSTATEMENT_HXX
#define CONNECTIVITY_SPREPAREDSTATEMENT_HXX

#ifndef CONNECTIVITY_SRESULTSET_HXX
#include "MResultSet.hxx"
#endif
#ifndef CONNECTIVITY_SSTATEMENT_HXX
#include "MStatement.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XPREPAREDSTATEMENT_HPP_
#include <com/sun/star/sdbc/XPreparedStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_
#include <com/sun/star/sdbc/XParameters.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XMULTIPLERESULTS_HPP_
#include <com/sun/star/sdbc/XMultipleResults.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#include <cppuhelper/compbase5.hxx>
#endif

namespace connectivity
{
    namespace mozab
    {

        class OBoundParam;
        typedef ::cppu::ImplHelper5<    ::com::sun::star::sdbc::XPreparedStatement,
                                        ::com::sun::star::sdbc::XParameters,
                                        ::com::sun::star::sdbc::XResultSetMetaDataSupplier,
                                        ::com::sun::star::sdbc::XMultipleResults,
                                        ::com::sun::star::lang::XServiceInfo> OPreparedStatement_BASE;

        class OPreparedStatement :  public  OStatement_BASE2,
                                    public  OPreparedStatement_BASE
        {
        protected:
            struct Parameter
            {
                ::com::sun::star::uno::Any  aValue;
                sal_Int32                   nDataType;

                Parameter(const ::com::sun::star::uno::Any& rValue,
                          sal_Int32                         rDataType) : aValue(rValue),nDataType(rDataType)
                {
                }

            };

            ::std::vector< Parameter>       m_aParameters;
            //====================================================================
            // Data attributes
            //====================================================================
            sal_Int32                       m_nNumParams;       // Number of parameter markers
                                                                //  for the prepared statement

            ::rtl::OUString                             m_sSqlStatement;
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData >  m_xMetaData;
            sal_Bool                                    m_bPrepared;
            OResultSet*                                 m_pResultSet;
            ::vos::ORef<connectivity::OSQLColumns>      m_xParamColumns;    // the parameter columns
            OValueRow                                   m_aParameterRow;

            void checkParameterIndex(sal_Int32 _parameterIndex);

        protected:
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,
                                                                   const ::com::sun::star::uno::Any& rValue)
                                                                        throw (::com::sun::star::uno::Exception);
            virtual ~OPreparedStatement();

            virtual void SAL_CALL disposing();
            virtual sal_Bool parseSql( const ::rtl::OUString& sql , sal_Bool bAdjusted = sal_False) throw (
                           ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException );

            virtual OResultSet* createResultSet();
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet> initResultSet();

            void checkAndResizeParameters(sal_Int32 parameterIndex);
            void setParameter(sal_Int32 parameterIndex, const ORowSetValue& x);

            sal_uInt32 AddParameter(connectivity::OSQLParseNode * pParameter,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xCol);
            void scanParameter(OSQLParseNode* pParseNode,::std::vector< OSQLParseNode*>& _rParaNodes);
            void describeColumn(OSQLParseNode* _pParameter,OSQLParseNode* _pNode,const OSQLTable& _xTable);
            void describeParameter();

            virtual void initializeResultSet( OResultSet* _pResult );

        public:
            DECLARE_SERVICE_INFO();
            // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
            OPreparedStatement( OConnection* _pConnection,const ::rtl::OUString& sql);

            //XInterface
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);

            // XPreparedStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL executeUpdate(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL execute(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XParameters
            virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearParameters(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XResultSetMetaDataSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XMultipleResults
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getResultSet(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getUpdateCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL getMoreResults(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        public:
            using OStatement_Base::executeQuery;
            using OStatement_Base::executeUpdate;
            using OStatement_Base::execute;
        protected:
            using OPropertySetHelper::getFastPropertyValue;
        };
    }
}
#endif // CONNECTIVITY_SPREPAREDSTATEMENT_HXX
<|endoftext|>


<commit_before>//
// Created by dc on 15/12/17.
//

#ifndef SUIL_CMDL_HPP
#define SUIL_CMDL_HPP

#include <suil/sys.hpp>

namespace suil {

    namespace cmdl {

        static const char NOSF = '\0';
        struct Arg {
            zcstring        lf{nullptr};
            zcstring        help;
            char            sf{NOSF};
            bool            option{true};
            bool            required{false};
            bool            global{false};
        private:
            friend struct Cmd;

            inline bool check(const zcstring& arg) const {
                return lf == arg;
            }

            inline bool check(char c) const {
                return c == sf;
            }

            inline bool check(char s, const zcstring& l) {
                return ((s != NOSF) && Ego.check(s)) || Ego.check(l);
            }
        };

        struct Cmd {
            Cmd(zcstring&& name, const char *descript = nullptr, bool help =  true);
            Cmd&operator()(zcstring&& lf, zcstring&& help, char sf, bool opt, bool req);
            Cmd&operator<<(Arg&&arg);
            Cmd&operator()(std::function<void(Cmd&)> handler) {
                if (Ego.handler != nullptr) {
                    throw SuilError::create("command '", name,
                                             "' already assigned a handler");
                }
                Ego.handler = handler;
                return Ego;
            }
            void showhelp(const char *app, zbuffer &help, bool ishelp = false) const;
            bool parse(int argc, char *argv[], bool debug = false);

            template <typename... O>
            bool parse(iod::sio<O...>& obj, int argc, char *argv[]) {
                // parse arguments as usual
                bool ishelp = parse(argc, argv, true);
                if (ishelp) {
                    return ishelp;
                }

                // parse arguments based on object
                iod::foreach2(obj) |
                [&](auto& m) {
                    auto& n = m.symbol().name();
                    zcstring name{n.data(), n.size(), false};
                    getvalue(name, m.value());
                };
            }

            inline bool interactive(bool showhelp=false) {
                Ego.inter = true;
                Ego.interhelp = showhelp;
            }

            zcstring operator[](char sf) {
                Arg& arg = Ego.check(nullptr, sf);
                return Ego[arg.lf].peek();
            }
            zcstring operator[](const char *lf) {
                Arg& arg = Ego.check(lf, NOSF);
                return Ego[arg.lf].peek();
            }

            zcstring operator[](const zcstring& lf);

            template <typename V>
            V getvalue(const char*lf, const V def) {
                zcstring zlf{lf};
                return std::move(getvalue(zlf, def));
            }

            zcstring getvalue(const char*lf, const char* def) {
                zcstring zlf{lf};
                zcstring zdef{def};
                return std::move(getvalue(zlf, zdef));
            }

            template <typename V>
            V getvalue(const zcstring& name, const V def) {
                Arg *_;
                if (!check(_, name, NOSF)) {
                    throw SuilError::create("passed parameter '",
                            name, "' is not an argument");
                }
                V tmp = def;
                zcstring zstr = Ego[name];
                if (!zstr.empty()) {
                    setvalue(tmp, zstr);
                }
                return std::move(tmp);
            }

        private:
            friend struct Parser;

            template <typename V>
            inline void setvalue(V& out, zcstring& from) {
                utils::cast(from, out);
            }

            template <typename V>
            inline void setvalue(std::vector<V>& out, zcstring& from) {
                auto& parts = utils::strsplit(from, ",");
                for (auto& part: parts) {
                    V val;
                    zcstring tmp{part};
                    zcstring trimd = utils::strtrim(tmp, ' ');
                    setvalue(val, trimd);
                    out.emplace_back(std::move(val));
                }
            }

            static int isvalid(const char *flag) {
                if (flag[0] == '-') {
                    if (flag[1] == '-') {
                        return (flag[2] != '\0' && flag[2] != '-' && isalpha(flag[2]))?
                               2 : 0;
                    }
                    return (flag[1] != '\0' && isalpha(flag[1]))? 1: 0;
                }
                return 0;
            }

            void requestvalue(Arg& arg);

            Arg& check(const zcstring& lf, char sf);
            bool check(Arg*& found, const zcstring& lf, char sf);
            zcstring    name;
            zcstring    descript;
            std::vector<Arg> args;
            size_t      longest{0};
            bool        required{false};
            bool        internal{false};
            bool        inter{false};
            bool        interhelp{false};
            zmap<zcstring> passed;
            std::function<void(Cmd&)> handler;
        };

        struct Parser {
            Parser(const char* app, const char *version, const char *descript = nullptr);
            template <typename... Commands>
            void add(Cmd&& cmd, Commands&&... cmds) {
                add(std::forward<Cmd>(cmd));
                add(std::forward<Commands>(cmds)...);
            }

            void add(Cmd&& cmd);

            Parser&operator<<(Arg&& arg);

            void  parse(int argc, char *argv[]);
            void  handle();
            void  showcmdhelp(zbuffer& out, Cmd& cmd, bool ishelp);
            const Cmd* getcmd() const {
                return parsed;
            }

            template <typename __T>
            zcstring operator[](char sf) {
                zcstring _{nullptr};
                Arg *arg = findarg(_, sf);
                if (arg) {
                    return Ego.getvalue(arg->lf, arg);
                }
                return zcstring{};
            }
            zcstring operator[](const char* lf) {
                zcstring zlf{lf};
                return getvalue(zlf, nullptr);
            }

            zcstring operator[](const zcstring& lf) {
                return getvalue(lf, nullptr);
            }

        private:
            zcstring  getvalue(const zcstring&, Arg* arg);
            void      showhelp(const char *prefix = nullptr);
            Cmd*  find(const zcstring& name);
            Arg* findarg(const zcstring& name, char sf=NOSF);
            Arg  shallowcopy(const Arg& arg);
            void add(){}
            std::vector<Cmd>  commands;
            std::vector<Arg> globals;
            // this is the command that successfully passed
            Cmd               *parsed{nullptr};
            zcstring              appname;
            zcstring              descript;
            zcstring              appversion;
            size_t                longestcmd{0};
            size_t                longestflag{0};
            bool                  required{false};
            bool                  inter{false};
        };

        zcstring readparam(const zcstring& display, const char *def);
        zcstring readpasswd(const zcstring& display);
    }

}
#endif //SUIL_CMDL_HPP
<commit_msg>- Updating for C++17 compiler<commit_after>//
// Created by dc on 15/12/17.
//

#ifndef SUIL_CMDL_HPP
#define SUIL_CMDL_HPP

#include <suil/sys.hpp>

namespace suil {

    namespace cmdl {

        static const char NOSF = '\0';
        struct Arg {
            zcstring        lf{nullptr};
            zcstring        help;
            char            sf{NOSF};
            bool            option{true};
            bool            required{false};
            bool            global{false};
        private:
            friend struct Cmd;

            inline bool check(const zcstring& arg) const {
                return lf == arg;
            }

            inline bool check(char c) const {
                return c == sf;
            }

            inline bool check(char s, const zcstring& l) {
                return ((s != NOSF) && Ego.check(s)) || Ego.check(l);
            }
        };

        struct Cmd {
            Cmd(zcstring&& name, const char *descript = nullptr, bool help =  true);
            Cmd&operator()(zcstring&& lf, zcstring&& help, char sf, bool opt, bool req);
            Cmd&operator<<(Arg&&arg);
            Cmd&operator()(std::function<void(Cmd&)> handler) {
                if (Ego.handler != nullptr) {
                    throw SuilError::create("command '", name,
                                             "' already assigned a handler");
                }
                Ego.handler = handler;
                return Ego;
            }
            void showhelp(const char *app, zbuffer &help, bool ishelp = false) const;
            bool parse(int argc, char *argv[], bool debug = false);

            template <typename... O>
            bool parse(iod::sio<O...>& obj, int argc, char *argv[]) {
                // parse arguments as usual
                bool ishelp = parse(argc, argv, true);
                if (ishelp) {
                    return ishelp;
                }

                // parse arguments based on object
                iod::foreach2(obj) |
                [&](auto& m) {
                    auto& n = m.symbol().name();
                    zcstring name{n.data(), n.size(), false};
                    getvalue(name, m.value());
                };
            }

            inline bool interactive(bool showhelp=false) {
                Ego.inter = true;
                Ego.interhelp = showhelp;
                return true;
            }

            zcstring operator[](char sf) {
                Arg& arg = Ego.check(nullptr, sf);
                return Ego[arg.lf].peek();
            }
            zcstring operator[](const char *lf) {
                Arg& arg = Ego.check(lf, NOSF);
                return Ego[arg.lf].peek();
            }

            zcstring operator[](const zcstring& lf);

            template <typename V>
            V getvalue(const char*lf, const V def) {
                zcstring zlf{lf};
                return std::move(getvalue(zlf, def));
            }

            zcstring getvalue(const char*lf, const char* def) {
                zcstring zlf{lf};
                zcstring zdef{def};
                return std::move(getvalue(zlf, zdef));
            }

            template <typename V>
            V getvalue(const zcstring& name, const V def) {
                Arg *_;
                if (!check(_, name, NOSF)) {
                    throw SuilError::create("passed parameter '",
                            name, "' is not an argument");
                }
                V tmp = def;
                zcstring zstr = Ego[name];
                if (!zstr.empty()) {
                    setvalue(tmp, zstr);
                }
                return std::move(tmp);
            }

        private:
            friend struct Parser;

            template <typename V>
            inline void setvalue(V& out, zcstring& from) {
                utils::cast(from, out);
            }

            template <typename V>
            inline void setvalue(std::vector<V>& out, zcstring& from) {
                auto& parts = utils::strsplit(from, ",");
                for (auto& part: parts) {
                    V val;
                    zcstring tmp{part};
                    zcstring trimd = utils::strtrim(tmp, ' ');
                    setvalue(val, trimd);
                    out.emplace_back(std::move(val));
                }
            }

            static int isvalid(const char *flag) {
                if (flag[0] == '-') {
                    if (flag[1] == '-') {
                        return (flag[2] != '\0' && flag[2] != '-' && isalpha(flag[2]))?
                               2 : 0;
                    }
                    return (flag[1] != '\0' && isalpha(flag[1]))? 1: 0;
                }
                return 0;
            }

            void requestvalue(Arg& arg);

            Arg& check(const zcstring& lf, char sf);
            bool check(Arg*& found, const zcstring& lf, char sf);
            zcstring    name;
            zcstring    descript;
            std::vector<Arg> args;
            size_t      longest{0};
            bool        required{false};
            bool        internal{false};
            bool        inter{false};
            bool        interhelp{false};
            zmap<zcstring> passed;
            std::function<void(Cmd&)> handler;
        };

        struct Parser {
            Parser(const char* app, const char *version, const char *descript = nullptr);
            template <typename... Commands>
            void add(Cmd&& cmd, Commands&&... cmds) {
                add(std::forward<Cmd>(cmd));
                add(std::forward<Commands>(cmds)...);
            }

            void add(Cmd&& cmd);

            Parser&operator<<(Arg&& arg);

            void  parse(int argc, char *argv[]);
            void  handle();
            void  showcmdhelp(zbuffer& out, Cmd& cmd, bool ishelp);
            const Cmd* getcmd() const {
                return parsed;
            }

            template <typename __T>
            zcstring operator[](char sf) {
                zcstring _{nullptr};
                Arg *arg = findarg(_, sf);
                if (arg) {
                    return Ego.getvalue(arg->lf, arg);
                }
                return zcstring{};
            }
            zcstring operator[](const char* lf) {
                zcstring zlf{lf};
                return getvalue(zlf, nullptr);
            }

            zcstring operator[](const zcstring& lf) {
                return getvalue(lf, nullptr);
            }

        private:
            zcstring  getvalue(const zcstring&, Arg* arg);
            void      showhelp(const char *prefix = nullptr);
            Cmd*  find(const zcstring& name);
            Arg* findarg(const zcstring& name, char sf=NOSF);
            Arg  shallowcopy(const Arg& arg);
            void add(){}
            std::vector<Cmd>  commands;
            std::vector<Arg> globals;
            // this is the command that successfully passed
            Cmd               *parsed{nullptr};
            zcstring              appname;
            zcstring              descript;
            zcstring              appversion;
            size_t                longestcmd{0};
            size_t                longestflag{0};
            bool                  required{false};
            bool                  inter{false};
        };

        zcstring readparam(const zcstring& display, const char *def);
        zcstring readpasswd(const zcstring& display);
    }

}
#endif //SUIL_CMDL_HPP
<|endoftext|>