<commit_before>#ifndef __STAN__COMMON__PRINT_PROGRESS_HPP__
#define __STAN__COMMON__PRINT_PROGRESS_HPP__

#include <cmath>
#include <iomanip>
#include <stan/common/do_print.hpp>

// FIXME: this calls std::cout directly.
#include <iostream>

namespace stan {
  namespace common {

    void print_progress(const int m,
                        const int start,
                        const int finish,
                        const int refresh,
                        const bool warmup,
                        std::ostream& o) {
      int it_print_width = std::ceil(std::log10(finish));
      if (do_print(m, (start + m + 1 == finish), refresh)) {
        o << "Iteration: ";
        o << std::setw(it_print_width) << m + 1 + start
          << " / " << finish;
        o << " [" << std::setw(3)
          << static_cast<int>( (100.0 * (start + m + 1)) / finish )
          << "%] ";
        o << (warmup ? " (Warmup)" : " (Sampling)");
        o << std::endl;
      }
    }

    void print_progress(const int m,
                        const int start,
                        const int finish,
                        const int refresh,
                        const bool warmup) {
      print_progress(m, start, finish, refresh, warmup,
                     std::cout);
    }

  } // namespace common

} // namespace stan

#endif
<commit_msg>refactor: abstracted prefix and suffix out of print_progress<commit_after>#ifndef __STAN__COMMON__PRINT_PROGRESS_HPP__
#define __STAN__COMMON__PRINT_PROGRESS_HPP__

#include <cmath>
#include <iomanip>
#include <stan/common/do_print.hpp>

// FIXME: this calls std::cout directly.
#include <iostream>

namespace stan {
  namespace common {

    void print_progress(const int m,
                        const int start,
                        const int finish,
                        const int refresh,
                        const bool warmup,
                        const std::string prefix,
                        const std::string suffix,
                        std::ostream& o) {
      int it_print_width = std::ceil(std::log10(finish));
      if (do_print(m, (start + m + 1 == finish), refresh)) {
        o << prefix;
        o << "Iteration: ";
        o << std::setw(it_print_width) << m + 1 + start
          << " / " << finish;
        o << " [" << std::setw(3)
          << static_cast<int>( (100.0 * (start + m + 1)) / finish )
          << "%] ";
        o << (warmup ? " (Warmup)" : " (Sampling)");
        o << suffix;
        o << std::endl;
      }
    }

    void print_progress(const int m,
                        const int start,
                        const int finish,
                        const int refresh,
                        const bool warmup) {
      print_progress(m, start, finish, refresh, warmup,
                     "", "\n",
                     std::cout);
    }

  } // namespace common

} // namespace stan

#endif
<|endoftext|>


<commit_before>#include "ImfCFile.h"

#include <stdlib.h>
#include <assert.h>

#define XRES 1024
#define YRES 512

int main()
{
	const char *software = "microexr";
	const char *comment = "a simple test case for the microexr library";

	ImfHeader *header = ImfNewHeader();

	ImfHeaderSetCompression(header, IMF_ZIP_COMPRESSION );
	ImfHeaderSetStringAttribute( header, "software", software );
	ImfHeaderSetStringAttribute( header, "comment", comment );
	ImfHeaderSetDataWindow( header, 0, 0, XRES-1, YRES-1 );
	ImfHeaderSetDisplayWindow( header, 0, 0, XRES-1, YRES-1 );
	ImfHeaderSetPixelAspectRatio( header, 1.0f );
	ImfHeaderSetScreenWindowCenter(header, 0.0, 0.0);
	ImfHeaderSetScreenWindowWidth(header, 1.0);

	ImfHeaderSetLineOrder( header, IMF_INCREASING_Y );

	ImfHeaderInsertChannel(header, "R", IMF_PIXEL_HALF);
	ImfHeaderInsertChannel(header, "G", IMF_PIXEL_HALF);
	ImfHeaderInsertChannel(header, "B", IMF_PIXEL_HALF);
	ImfHeaderInsertChannel(header, "A", IMF_PIXEL_HALF);

	ImfOutputFile *exr = ImfOpenOutputFile( "gradient.exr", header );

	if( !exr )
	{
		perror( "gradient: unable to open 'gradient.exr' for writing" );
		exit( 1 );
	}

	/* Write a simple gradient in the framebuffer. */
	ImfHalf *fb = new ImfHalf[XRES*4];

	for( unsigned j=0; j<YRES; j++ )
	{
		float g = float(j) / float(YRES-1);
		assert( g<=1.0f );

		ImfHalf *current_pixel = fb;

		for( unsigned i=0; i<XRES; i++ )
		{
			float r = float(i) / float(XRES-1);

			assert( r<=1.0f );

			ImfFloatToHalf( r, current_pixel + 0 );
			ImfFloatToHalf( g, current_pixel + 1 );
			ImfFloatToHalf( 0.5f, current_pixel + 2 );
			ImfFloatToHalf( 1.0f, current_pixel + 3 );

			current_pixel += 4;
		}

		ImfOutputSetFrameBuffer( exr, (const char *)fb, 4*sizeof(ImfHalf), 0 );
		ImfOutputWritePixels( exr, 1 );
	}

	ImfCloseOutputFile( exr );
	ImfDeleteHeader( header );

	delete [] fb;

	exit( 0 );
}
<commit_msg>Use the standard open nomencalture for compatibility.<commit_after>#include "ImfCFile.h"

#include <stdlib.h>
#include <assert.h>

#define XRES 1024
#define YRES 512

int main()
{
	const char *software = "microexr";
	const char *comment = "a simple test case for the microexr library";

	ImfHeader *header = ImfNewHeader();

	ImfHeaderSetCompression(header, IMF_ZIP_COMPRESSION );
	ImfHeaderSetStringAttribute( header, "software", software );
	ImfHeaderSetStringAttribute( header, "comment", comment );
	ImfHeaderSetDataWindow( header, 0, 0, XRES-1, YRES-1 );
	ImfHeaderSetDisplayWindow( header, 0, 0, XRES-1, YRES-1 );
	ImfHeaderSetPixelAspectRatio( header, 1.0f );
	ImfHeaderSetScreenWindowCenter(header, 0.0, 0.0);
	ImfHeaderSetScreenWindowWidth(header, 1.0);

	ImfHeaderSetLineOrder( header, IMF_INCREASING_Y );

	ImfOutputFile *exr = ImfOpenOutputFile( "gradient.exr", header, IMF_WRITE_RGBA );

	if( !exr )
	{
		perror( "gradient: unable to open 'gradient.exr' for writing" );
		exit( 1 );
	}

	/* Write a simple gradient in the framebuffer. */
	ImfHalf *fb = new ImfHalf[XRES*4];

	for( unsigned j=0; j<YRES; j++ )
	{
		float g = float(j) / float(YRES-1);
		assert( g<=1.0f );

		ImfHalf *current_pixel = fb;

		for( unsigned i=0; i<XRES; i++ )
		{
			float r = float(i) / float(XRES-1);

			assert( r<=1.0f );

			ImfFloatToHalf( r, current_pixel + 0 );
			ImfFloatToHalf( g, current_pixel + 1 );
			ImfFloatToHalf( 0.5f, current_pixel + 2 );
			ImfFloatToHalf( 1.0f, current_pixel + 3 );

			current_pixel += 4;
		}

		ImfOutputSetFrameBuffer( exr, (const char *)fb, 4*sizeof(ImfHalf), 0 );
		ImfOutputWritePixels( exr, 1 );
	}

	ImfCloseOutputFile( exr );
	ImfDeleteHeader( header );

	delete [] fb;

	exit( 0 );
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 Patrick Huck
#include "src/cmdline/cmdline.h"
#include <boost/filesystem/fstream.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>
#include "src/clean/clean.h"
#include "src/aux/utils.h"

using std::cout;
using std::endl;
using std::ostream;
namespace io = boost::iostreams;
namespace fs = boost::filesystem;

typedef io::tee_device<ostream, fs::ofstream> Tee;
typedef io::stream<Tee> TeeStream;

cmdline::cmdline()
: ckon_cmd(""), nCpu("1"), ckon_config_file("ckon.cfg"), ckon_src_dir("StRoot"),
  ckon_obsolete_dir("Obsolete"), ckon_exclSuffix("Gnuplot Options"),
  ckon_DontScan("dat-files database"), ckon_NoRootCint("YamlCpp"),
  ckon_prog_subdir("programs"), ckon_macro_subdir("macros"),
  ckon_build_dir("build"), ckon_install_dir("build")
{ }

void cmdline::purge() {
  clean clcont(ckon_src_dir);
  printf("%d files removed.\n", clcont.purge());
}

void cmdline::runSetup() {
  if ( fs::exists(ckon_config_file) || fs::exists("configure.ac") ) {
    cout << ckon_config_file << " or configure.ac already exist(s)!" << endl;
    if ( utils::askYesOrNo("remove and start over") == 'n' ) return;
    fs::remove(ckon_config_file);
    fs::remove("configure.ac");
    fs::remove(".autom4te.cfg");
  }

  cout << "write cfgfile" << endl;

  fs::ofstream cfgfile(ckon_config_file);
  Tee tee(cout, cfgfile);
  TeeStream both(tee);
  both << "pythia=" << bPythia << endl;
  both << "roofit=" << bRooFit << endl;
  both << "boost=" << bBoost << endl;
  both << "suffix=" << bSuffix << endl;
  both << "[ckon]" << endl;
  both << "src_dir=" << ckon_src_dir << endl;
  both << "obsolete_dir=" << ckon_obsolete_dir << endl;
  both << "prog_subdir=" << ckon_prog_subdir << endl;
  both << "macro_subdir=" << ckon_macro_subdir << endl;
  both << "build_dir=" << ckon_build_dir << endl;
  both << "install_dir=" << ckon_install_dir << endl;
  both << "exclSuffix=\"" << ckon_exclSuffix << "\"" << endl;
  both << "DontScan=\"" << ckon_DontScan << "\"" << endl;
  both << "NoRootCint=" << ckon_NoRootCint << endl;
  both.close();

  writeConfigureAc();
  writeAutom4teCfg();

  cout << endl << "setup done. check " << ckon_config_file << endl;
}

bool cmdline::parse(int argc, char *argv[]) {
  po::options_description generic("Generic Options");
  generic.add_options()
    ("help,h", po::bool_switch(&bHelp), "show this help")
    ("verbose,v", po::bool_switch(&bVerbose), "verbose output")
    (",j", po::value<string>(&nCpu), "call make with option -j <#cores>")
    ("ckon_cmd", po::value<string>(&ckon_cmd), "setup | clean | install");

  po::options_description config("Configuration");
  config.add_options()
    ("pythia,p", po::value<bool>(&bPythia), "link with pythia library (bool)")
    ("roofit,r", po::value<bool>(&bRooFit), "link with roofit library (bool)")
    ("suffix,s", po::value<bool>(&bSuffix), "Add suffix + in LinkDef file (bool)")
    ("boost,b", po::value<bool>(&bBoost), "include BOOST_INC and BOOST_LIB (bool)")
    ("ckon.config_file", po::value<string>(&ckon_config_file), "config file")
    ("ckon.src_dir", po::value<string>(&ckon_src_dir), "source dir")
    ("ckon.obsolete_dir", po::value<string>(&ckon_obsolete_dir), "obsolete dir")
    ("ckon.exclSuffix", po::value<string>(&ckon_exclSuffix), "no + suffix")
    ("ckon.DontScan", po::value<string>(&ckon_DontScan), "no source scan")
    ("ckon.NoRootCint", po::value<string>(&ckon_NoRootCint), "no dictionary")
    ("ckon.prog_subdir", po::value<string>(&ckon_prog_subdir), "progs subdir")
    ("ckon.macro_subdir", po::value<string>(&ckon_macro_subdir), "macro subdir")
    ("ckon.build_dir", po::value<string>(&ckon_build_dir), "build dir")
    ("ckon.install_dir", po::value<string>(&ckon_install_dir), "install dir");

  po::options_description allopts;
  allopts.add(generic).add(config);

  po::positional_options_description posOpts;
  posOpts.add("ckon_cmd", 1);

  po::variables_map vm;

  try {
    po::store(
        po::command_line_parser(argc, argv)
        .options(allopts).positional(posOpts).run(), vm);
    if ( fs::exists(ckon_config_file) ) {
      po::store(
          po::parse_config_file<char>(ckon_config_file.c_str(), config), vm);
    }

    po::notify(vm);  // throws on error

    if ( bHelp ) {  // --help option
      cout << "ckon -- automatic ROOT analyses compiler & linker" << endl;
      cout << allopts << endl;
      return false;
    }

    bSetup = !ckon_cmd.compare("setup");
    bClean = !ckon_cmd.compare("clean");
    bInstall = !ckon_cmd.compare("install");

    if ( bSetup ) { cout << "run setup" << endl; runSetup(); return false; }
    if ( bClean ) { purge(); return false; }

    return true;
  }
  catch(const po::error& e) {
    std::cerr << "ERROR: " << e.what() << endl << endl << generic << endl;
    return false;
  }
}

void cmdline::writeConfigureAc() {
  string cfg_ac_str = "AC_INIT([ana], [0.0])\n";
  cfg_ac_str += "m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])\n";
  cfg_ac_str += "AC_CONFIG_AUX_DIR(config)\n";
  cfg_ac_str += "m4_pattern_allow([AM_PROG_AR])\n";
  cfg_ac_str += "m4_ifdef([AM_PROG_AR], [AM_PROG_AR])\n";
  cfg_ac_str += "AM_INIT_AUTOMAKE([-Wall no-define])\n";
  cfg_ac_str += "AC_PROG_CXX\n";
  cfg_ac_str += "AM_PROG_LIBTOOL\n";
  cfg_ac_str += "ROOTLIBS=`$ROOTSYS/bin/root-config --libs`\n";
  cfg_ac_str += "ROOTINCLUDES=`$ROOTSYS/bin/root-config --incdir`\n";
  cfg_ac_str += "ROOTLIBDIR=`$ROOTSYS/bin/root-config --libdir`\n";
  cfg_ac_str += "ROOTGLIBS=`$ROOTSYS/bin/root-config --glibs`\n";
  cfg_ac_str += "AC_SUBST(ROOTLIBS)\n";
  cfg_ac_str += "AC_SUBST(ROOTINCLUDES)\n";
  cfg_ac_str += "AC_SUBST(ROOTGLIBS)\n";
  cfg_ac_str += "AC_SUBST(ROOTLIBDIR)\n";
  cfg_ac_str += "AC_CONFIG_FILES([Makefile])\n";
  cfg_ac_str += "AC_OUTPUT\n";
  fs::ofstream cfg_ac;
  cfg_ac.open("configure.ac");
  cfg_ac << cfg_ac_str;
  cfg_ac.close();
}

void cmdline::writeAutom4teCfg() {
  string atmte_str = "begin-language: \"Autoconf-without-aclocal-m4\"\n";
  atmte_str += "args: --no-cache\n";
  atmte_str += "end-language: \"Autoconf-without-aclocal-m4\"\n";
  fs::ofstream atmte;
  atmte.open(".autom4te.cfg");
  atmte << atmte_str;
  atmte.close();
}

<commit_msg>remove ckon.config_file as option<commit_after>// Copyright (c) 2013 Patrick Huck
#include "src/cmdline/cmdline.h"
#include <boost/filesystem/fstream.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>
#include "src/clean/clean.h"
#include "src/aux/utils.h"

using std::cout;
using std::endl;
using std::ostream;
namespace io = boost::iostreams;
namespace fs = boost::filesystem;

typedef io::tee_device<ostream, fs::ofstream> Tee;
typedef io::stream<Tee> TeeStream;

cmdline::cmdline()
: ckon_cmd(""), nCpu("1"), ckon_config_file("ckon.cfg"), ckon_src_dir("StRoot"),
  ckon_obsolete_dir("Obsolete"), ckon_exclSuffix("Gnuplot Options"),
  ckon_DontScan("dat-files database"), ckon_NoRootCint("YamlCpp"),
  ckon_prog_subdir("programs"), ckon_macro_subdir("macros"),
  ckon_build_dir("build"), ckon_install_dir("build")
{ }

void cmdline::purge() {
  clean clcont(ckon_src_dir);
  printf("%d files removed.\n", clcont.purge());
}

void cmdline::runSetup() {
  if ( fs::exists(ckon_config_file) || fs::exists("configure.ac") ) {
    cout << ckon_config_file << " or configure.ac already exist(s)!" << endl;
    if ( utils::askYesOrNo("remove and start over") == 'n' ) return;
    fs::remove(ckon_config_file);
    fs::remove("configure.ac");
    fs::remove(".autom4te.cfg");
  }

  cout << "write cfgfile" << endl;

  fs::ofstream cfgfile(ckon_config_file);
  Tee tee(cout, cfgfile);
  TeeStream both(tee);
  both << "pythia=" << bPythia << endl;
  both << "roofit=" << bRooFit << endl;
  both << "boost=" << bBoost << endl;
  both << "suffix=" << bSuffix << endl;
  both << "[ckon]" << endl;
  both << "src_dir=" << ckon_src_dir << endl;
  both << "obsolete_dir=" << ckon_obsolete_dir << endl;
  both << "prog_subdir=" << ckon_prog_subdir << endl;
  both << "macro_subdir=" << ckon_macro_subdir << endl;
  both << "build_dir=" << ckon_build_dir << endl;
  both << "install_dir=" << ckon_install_dir << endl;
  both << "exclSuffix=\"" << ckon_exclSuffix << "\"" << endl;
  both << "DontScan=\"" << ckon_DontScan << "\"" << endl;
  both << "NoRootCint=" << ckon_NoRootCint << endl;
  both.close();

  writeConfigureAc();
  writeAutom4teCfg();

  cout << endl << "setup done. check " << ckon_config_file << endl;
}

bool cmdline::parse(int argc, char *argv[]) {
  po::options_description generic("Generic Options");
  generic.add_options()
    ("help,h", po::bool_switch(&bHelp), "show this help")
    ("verbose,v", po::bool_switch(&bVerbose), "verbose output")
    (",j", po::value<string>(&nCpu), "call make with option -j <#cores>")
    ("ckon_cmd", po::value<string>(&ckon_cmd), "setup | clean | install");

  po::options_description config("Configuration");
  config.add_options()
    ("pythia,p", po::value<bool>(&bPythia), "link with pythia library (bool)")
    ("roofit,r", po::value<bool>(&bRooFit), "link with roofit library (bool)")
    ("suffix,s", po::value<bool>(&bSuffix), "Add suffix + in LinkDef file (bool)")
    ("boost,b", po::value<bool>(&bBoost), "include BOOST_INC and BOOST_LIB (bool)")
    ("ckon.src_dir", po::value<string>(&ckon_src_dir), "source dir")
    ("ckon.obsolete_dir", po::value<string>(&ckon_obsolete_dir), "obsolete dir")
    ("ckon.exclSuffix", po::value<string>(&ckon_exclSuffix), "no + suffix")
    ("ckon.DontScan", po::value<string>(&ckon_DontScan), "no source scan")
    ("ckon.NoRootCint", po::value<string>(&ckon_NoRootCint), "no dictionary")
    ("ckon.prog_subdir", po::value<string>(&ckon_prog_subdir), "progs subdir")
    ("ckon.macro_subdir", po::value<string>(&ckon_macro_subdir), "macro subdir")
    ("ckon.build_dir", po::value<string>(&ckon_build_dir), "build dir")
    ("ckon.install_dir", po::value<string>(&ckon_install_dir), "install dir");

  po::options_description allopts;
  allopts.add(generic).add(config);

  po::positional_options_description posOpts;
  posOpts.add("ckon_cmd", 1);

  po::variables_map vm;

  try {
    po::store(
        po::command_line_parser(argc, argv)
        .options(allopts).positional(posOpts).run(), vm);
    if ( fs::exists(ckon_config_file) ) {
      po::store(
          po::parse_config_file<char>(ckon_config_file.c_str(), config), vm);
    }

    po::notify(vm);  // throws on error

    if ( bHelp ) {  // --help option
      cout << "ckon -- automatic ROOT analyses compiler & linker" << endl;
      cout << allopts << endl;
      return false;
    }

    bSetup = !ckon_cmd.compare("setup");
    bClean = !ckon_cmd.compare("clean");
    bInstall = !ckon_cmd.compare("install");

    if ( bSetup ) { cout << "run setup" << endl; runSetup(); return false; }
    if ( bClean ) { purge(); return false; }

    return true;
  }
  catch(const po::error& e) {
    std::cerr << "ERROR: " << e.what() << endl << endl << generic << endl;
    return false;
  }
}

void cmdline::writeConfigureAc() {
  string cfg_ac_str = "AC_INIT([ana], [0.0])\n";
  cfg_ac_str += "m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])\n";
  cfg_ac_str += "AC_CONFIG_AUX_DIR(config)\n";
  cfg_ac_str += "m4_pattern_allow([AM_PROG_AR])\n";
  cfg_ac_str += "m4_ifdef([AM_PROG_AR], [AM_PROG_AR])\n";
  cfg_ac_str += "AM_INIT_AUTOMAKE([-Wall no-define])\n";
  cfg_ac_str += "AC_PROG_CXX\n";
  cfg_ac_str += "AM_PROG_LIBTOOL\n";
  cfg_ac_str += "ROOTLIBS=`$ROOTSYS/bin/root-config --libs`\n";
  cfg_ac_str += "ROOTINCLUDES=`$ROOTSYS/bin/root-config --incdir`\n";
  cfg_ac_str += "ROOTLIBDIR=`$ROOTSYS/bin/root-config --libdir`\n";
  cfg_ac_str += "ROOTGLIBS=`$ROOTSYS/bin/root-config --glibs`\n";
  cfg_ac_str += "AC_SUBST(ROOTLIBS)\n";
  cfg_ac_str += "AC_SUBST(ROOTINCLUDES)\n";
  cfg_ac_str += "AC_SUBST(ROOTGLIBS)\n";
  cfg_ac_str += "AC_SUBST(ROOTLIBDIR)\n";
  cfg_ac_str += "AC_CONFIG_FILES([Makefile])\n";
  cfg_ac_str += "AC_OUTPUT\n";
  fs::ofstream cfg_ac;
  cfg_ac.open("configure.ac");
  cfg_ac << cfg_ac_str;
  cfg_ac.close();
}

void cmdline::writeAutom4teCfg() {
  string atmte_str = "begin-language: \"Autoconf-without-aclocal-m4\"\n";
  atmte_str += "args: --no-cache\n";
  atmte_str += "end-language: \"Autoconf-without-aclocal-m4\"\n";
  fs::ofstream atmte;
  atmte.open(".autom4te.cfg");
  atmte << atmte_str;
  atmte.close();
}

<|endoftext|>


<commit_before>/*
  Tile.cpp

  tileable image generation

  Li-Yi Wei
  April 25, 2018

*/

#include <iostream>
#include <string>
using namespace std;

#include "Texture.hpp"
#include "VectorRange.hpp"

#include "SequentialCounter.hpp"
#include "FrameBuffer.hpp"
#include "Random.hpp"
#include "Utility.hpp"
#include "Exception.hpp"

string Convert(const vector<int> & output_size, Array<Position> & coord_array)
{
    coord_array = Array<Position>(output_size);

    SequentialCounter counter(output_size.size(), vector<int>(output_size.size(), 0), Utility::Minus1(output_size));

    vector<int> index;
    counter.Reset();

    do
    {
        counter.Get(index);

        if(! coord_array.Put(index, index))
        {
            return "cannot put position";
        }
    }
    while(counter.Next());

    // done
    return "";
}

string Convert(const Array<FrameBuffer::P3> & coord_image, Array<Position> & coord_array)
{
    const vector<int> output_size = coord_image.Size();
    coord_array = Array<Position>(output_size);

    SequentialCounter counter(output_size.size(), vector<int>(output_size.size(), 0), Utility::Minus1(output_size));

    FrameBuffer::P3 pixel;
    Position position(2);
    vector<int> index;
    counter.Reset();

    do
    {
        counter.Get(index);

        if(! coord_image.Get(index, pixel))
        {
            return "cannot get pixel";
        }

        position[0] = pixel.r;
        position[1] = pixel.g;

        if(! coord_array.Put(index, position))
        {
            return "cannot put position";
        }
    }
    while(counter.Next());

    // done
    return "";
}

int Main(int argc, char **argv)
{
    // input arguments
    if(argc < 8)
    {
        cerr << "Usage: " << argv[0] << " input_image_file_path init_coord_spec input_boundary (toroidal or none)  synthesizer_spec sequencer_spec neighborhood_spec (e.g. square1) output_image_file_path" << endl;
        return 1;
    }

    int arg_ctr = 0;

    const string input_image_file_path(argv[++arg_ctr]);
    const string init_coord_spec(argv[++arg_ctr]);
    const string input_boundary(argv[++arg_ctr]);
    const string output_boundary("toroidal");
    const string synthesis_spec(argv[++arg_ctr]);
    const string sequence_spec(argv[++arg_ctr]);
    const string neighborhood_spec(argv[++arg_ctr]);
    const string output_image_file_path(argv[++arg_ctr]);

    // input image
    Array<FrameBuffer::P3> input_image;
    int max_pixel_value = -1;
    if(! FrameBuffer::ReadPPM(input_image_file_path, input_image, max_pixel_value))
    {
        cerr << "cannot read from " << input_image_file_path << endl;
        return 1;
    }

    const Texture input_texture(input_image);

    const int dimension = input_texture.Dimension();

    // init coord
    Array<Position> init_coord;
    {
        Array<FrameBuffer::P3> init_coord_image;
        int max_coord_value = -1;

        string message;
        if(FrameBuffer::ReadPPM(init_coord_spec, init_coord_image, max_coord_value))
        {
            message = Convert(init_coord_image, init_coord);
        }
        else
        {
            message = Convert(input_image.Size(), init_coord);
        }

        if(message != "")
        {
            cerr << "error in converting coord image: " << message << endl;
            return 1;
        }
    }

    // domain and neighborhood
    const shared_ptr<Domain> p_input_domain = Utility::BuildDomain(input_boundary);
    const shared_ptr<Domain> p_output_domain = Utility::BuildDomain(output_boundary);

    if(!p_input_domain || !p_output_domain)
    {
        cerr << "null domain" << endl;
        return 1;
    }

    const Domain & input_domain = *p_input_domain;
    const Domain & output_domain = *p_output_domain;

    const shared_ptr<Templar> p_templar = Utility::BuildTemplar(neighborhood_spec, dimension);
    if(!p_templar)
    {
        cerr << "null templar" << endl;
        return 1;
    }

    const shared_ptr<Neighborhood> p_output_neighborhood = Utility::BuildNeighborhood(*p_templar, output_domain);

    const Neighborhood & output_neighborhood = *p_output_neighborhood;

    // range
    const int range_dimension = 3; // RGB

    const RangePtr penalty_range(new VectorRange<int>(vector<int>(range_dimension, max_pixel_value)));
    const RangePtr zero_range(new VectorRange<int>(vector<int>(range_dimension, 0)));

    // initialization
    Random::InitRandomNumberGenerator();

    // output texture
    Texture output_texture(input_texture, init_coord);

    // synthesis
    const string message = Utility::Synthesize(input_boundary, output_boundary, synthesis_spec, sequence_spec, neighborhood_spec, input_texture, output_texture, penalty_range, zero_range);

    if(message != "")
    {
        cerr << "error in synthesis: " << message << endl;
        return 1;
    }

    // output
    Array<FrameBuffer::P3> output_image;
    if(!output_texture.Convert(output_image))
    {
        cerr << "cannot convert output" << endl;
        return 1;
    }

    if(! FrameBuffer::WritePPM(output_image, max_pixel_value, output_image_file_path))
    {
        cerr << "cannot write to " << output_image_file_path << endl;
        return 1;
    }

    // done
    return 0;
}

int main(int argc, char **argv)
{
    try
    {
        return Main(argc, argv);
    }
    catch(Exception e)
    {
        cout << e.Message() << endl;
        return 1;
    }
}

<commit_msg>r and g channels are x and y<commit_after>/*
  Tile.cpp

  tileable image generation

  Li-Yi Wei
  April 25, 2018

*/

#include <iostream>
#include <string>
using namespace std;

#include "Texture.hpp"
#include "VectorRange.hpp"

#include "SequentialCounter.hpp"
#include "FrameBuffer.hpp"
#include "Random.hpp"
#include "Utility.hpp"
#include "Exception.hpp"

string Convert(const vector<int> & output_size, Array<Position> & coord_array)
{
    coord_array = Array<Position>(output_size);

    SequentialCounter counter(output_size.size(), vector<int>(output_size.size(), 0), Utility::Minus1(output_size));

    vector<int> index;
    counter.Reset();

    do
    {
        counter.Get(index);

        if(! coord_array.Put(index, index))
        {
            return "cannot put position";
        }
    }
    while(counter.Next());

    // done
    return "";
}

string Convert(const Array<FrameBuffer::P3> & coord_image, Array<Position> & coord_array)
{
    const vector<int> output_size = coord_image.Size();
    coord_array = Array<Position>(output_size);

    SequentialCounter counter(output_size.size(), vector<int>(output_size.size(), 0), Utility::Minus1(output_size));

    FrameBuffer::P3 pixel;
    Position position(2);
    vector<int> index;
    counter.Reset();

    do
    {
        counter.Get(index);

        if(! coord_image.Get(index, pixel))
        {
            return "cannot get pixel";
        }

        position[0] = pixel.g;
        position[1] = pixel.r;

        if(! coord_array.Put(index, position))
        {
            return "cannot put position";
        }
    }
    while(counter.Next());

    // done
    return "";
}

int Main(int argc, char **argv)
{
    // input arguments
    if(argc < 8)
    {
        cerr << "Usage: " << argv[0] << " input_image_file_path init_coord_spec input_boundary (toroidal or none)  synthesizer_spec sequencer_spec neighborhood_spec (e.g. square1) output_image_file_path" << endl;
        return 1;
    }

    int arg_ctr = 0;

    const string input_image_file_path(argv[++arg_ctr]);
    const string init_coord_spec(argv[++arg_ctr]);
    const string input_boundary(argv[++arg_ctr]);
    const string output_boundary("toroidal");
    const string synthesis_spec(argv[++arg_ctr]);
    const string sequence_spec(argv[++arg_ctr]);
    const string neighborhood_spec(argv[++arg_ctr]);
    const string output_image_file_path(argv[++arg_ctr]);

    // input image
    Array<FrameBuffer::P3> input_image;
    int max_pixel_value = -1;
    if(! FrameBuffer::ReadPPM(input_image_file_path, input_image, max_pixel_value))
    {
        cerr << "cannot read from " << input_image_file_path << endl;
        return 1;
    }

    const Texture input_texture(input_image);

    const int dimension = input_texture.Dimension();

    // init coord
    Array<Position> init_coord;
    {
        Array<FrameBuffer::P3> init_coord_image;
        int max_coord_value = -1;

        string message;
        if(FrameBuffer::ReadPPM(init_coord_spec, init_coord_image, max_coord_value))
        {
            message = Convert(init_coord_image, init_coord);
        }
        else
        {
            message = Convert(input_image.Size(), init_coord);
        }

        if(message != "")
        {
            cerr << "error in converting coord image: " << message << endl;
            return 1;
        }
    }

    // domain and neighborhood
    const shared_ptr<Domain> p_input_domain = Utility::BuildDomain(input_boundary);
    const shared_ptr<Domain> p_output_domain = Utility::BuildDomain(output_boundary);

    if(!p_input_domain || !p_output_domain)
    {
        cerr << "null domain" << endl;
        return 1;
    }

    const Domain & input_domain = *p_input_domain;
    const Domain & output_domain = *p_output_domain;

    const shared_ptr<Templar> p_templar = Utility::BuildTemplar(neighborhood_spec, dimension);
    if(!p_templar)
    {
        cerr << "null templar" << endl;
        return 1;
    }

    const shared_ptr<Neighborhood> p_output_neighborhood = Utility::BuildNeighborhood(*p_templar, output_domain);

    const Neighborhood & output_neighborhood = *p_output_neighborhood;

    // range
    const int range_dimension = 3; // RGB

    const RangePtr penalty_range(new VectorRange<int>(vector<int>(range_dimension, max_pixel_value)));
    const RangePtr zero_range(new VectorRange<int>(vector<int>(range_dimension, 0)));

    // initialization
    Random::InitRandomNumberGenerator();

    // output texture
    Texture output_texture(input_texture, init_coord);

    // synthesis
    const string message = Utility::Synthesize(input_boundary, output_boundary, synthesis_spec, sequence_spec, neighborhood_spec, input_texture, output_texture, penalty_range, zero_range);

    if(message != "")
    {
        cerr << "error in synthesis: " << message << endl;
        return 1;
    }

    // output
    Array<FrameBuffer::P3> output_image;
    if(!output_texture.Convert(output_image))
    {
        cerr << "cannot convert output" << endl;
        return 1;
    }

    if(! FrameBuffer::WritePPM(output_image, max_pixel_value, output_image_file_path))
    {
        cerr << "cannot write to " << output_image_file_path << endl;
        return 1;
    }

    // done
    return 0;
}

int main(int argc, char **argv)
{
    try
    {
        return Main(argc, argv);
    }
    catch(Exception e)
    {
        cout << e.Message() << endl;
        return 1;
    }
}

<|endoftext|>


<commit_before>#include "command_manager.hh"

#include "utils.hh"
#include "assert.hh"

#include <algorithm>

namespace Kakoune
{

void CommandManager::register_command(const std::string& command_name, Command command,
                                      const CommandCompleter& completer)
{
    m_commands[command_name] = CommandAndCompleter { command, completer };
}

void CommandManager::register_command(const std::vector<std::string>& command_names, Command command,
                                      const CommandCompleter& completer)
{
    for (auto command_name : command_names)
        register_command(command_name, command, completer);
}

typedef std::vector<std::pair<size_t, size_t>> TokenList;
static TokenList split(const std::string& line)
{
    TokenList result;

    size_t pos = 0;
    while (pos != line.length())
    {
        while(line[pos] == ' ' and pos != line.length())
            ++pos;

        size_t token_start = pos;

        while((line[pos] != ' ' or line[pos-1] == '\\') and pos != line.length())
            ++pos;

        result.push_back(std::make_pair(token_start, pos));
    }
    return result;
}

struct command_not_found : runtime_error
{
    command_not_found(const std::string& command)
        : runtime_error(command + " : no such command") {}
};

void CommandManager::execute(const std::string& command_line)
{
    TokenList tokens = split(command_line);
    if (tokens.empty())
        return;

    std::string command_name =
        command_line.substr(tokens[0].first,
                            tokens[0].second - tokens[0].first);

    auto command_it = m_commands.find(command_name);
    if (command_it == m_commands.end())
        throw command_not_found(command_name);

    CommandParameters params;
    for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)
    {
        params.push_back(command_line.substr(it->first,
                                             it->second - it->first));
    }

    command_it->second.command(params);
}

Completions CommandManager::complete(const std::string& command_line, size_t cursor_pos)
{
    TokenList tokens = split(command_line);

    size_t token_to_complete = -1;
    for (size_t i = 0; i < tokens.size(); ++i)
    {
        if (tokens[i].first < cursor_pos and tokens[i].second >= cursor_pos)
        {
            token_to_complete = i;
            break;
        }
    }

    if (token_to_complete == 0) // command name completion
    {
        Completions result(tokens[0].first, cursor_pos);
        std::string prefix = command_line.substr(tokens[0].first,
                                                 cursor_pos - tokens[0].first);

        for (auto& command : m_commands)
        {
            if (command.first.substr(0, prefix.length()) == prefix)
                result.candidates.push_back(command.first);
        }

        return result;
    }

    assert(not tokens.empty());
    std::string command_name =
        command_line.substr(tokens[0].first,
                            tokens[0].second - tokens[0].first);

    auto command_it = m_commands.find(command_name);
    if (command_it == m_commands.end() or not command_it->second.completer)
        return Completions();

    CommandParameters params;
    for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)
    {
        params.push_back(command_line.substr(it->first,
                                             it->second - it->first));
    }
    Completions result(tokens[token_to_complete].first, cursor_pos);
    size_t cursor_pos_in_token = cursor_pos - tokens[token_to_complete].first;

    result.candidates = command_it->second.completer(params,
                                                     token_to_complete - 1,
                                                     cursor_pos_in_token);
    return result;
}

CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params,
                                                      size_t token_to_complete,
                                                      size_t pos_in_token) const
{
    if (token_to_complete >= m_completers.size())
        return CandidateList();

    // it is possible to try to complete a new argument
    assert(token_to_complete <= params.size());

    const std::string& argument = token_to_complete < params.size() ?
                                  params[token_to_complete] : std::string();
    return m_completers[token_to_complete](argument, pos_in_token);
}

}
<commit_msg>CommandManager: fix completion of empty tokens<commit_after>#include "command_manager.hh"

#include "utils.hh"
#include "assert.hh"

#include <algorithm>

namespace Kakoune
{

void CommandManager::register_command(const std::string& command_name, Command command,
                                      const CommandCompleter& completer)
{
    m_commands[command_name] = CommandAndCompleter { command, completer };
}

void CommandManager::register_command(const std::vector<std::string>& command_names, Command command,
                                      const CommandCompleter& completer)
{
    for (auto command_name : command_names)
        register_command(command_name, command, completer);
}

typedef std::vector<std::pair<size_t, size_t>> TokenList;
static TokenList split(const std::string& line)
{
    TokenList result;

    size_t pos = 0;
    while (pos != line.length())
    {
        while(line[pos] == ' ' and pos != line.length())
            ++pos;

        size_t token_start = pos;

        while((line[pos] != ' ' or line[pos-1] == '\\') and pos != line.length())
            ++pos;

        result.push_back(std::make_pair(token_start, pos));
    }
    return result;
}

struct command_not_found : runtime_error
{
    command_not_found(const std::string& command)
        : runtime_error(command + " : no such command") {}
};

void CommandManager::execute(const std::string& command_line)
{
    TokenList tokens = split(command_line);
    if (tokens.empty())
        return;

    std::string command_name =
        command_line.substr(tokens[0].first,
                            tokens[0].second - tokens[0].first);

    auto command_it = m_commands.find(command_name);
    if (command_it == m_commands.end())
        throw command_not_found(command_name);

    CommandParameters params;
    for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)
    {
        params.push_back(command_line.substr(it->first,
                                             it->second - it->first));
    }

    command_it->second.command(params);
}

Completions CommandManager::complete(const std::string& command_line, size_t cursor_pos)
{
    TokenList tokens = split(command_line);

    size_t token_to_complete = -1;
    for (size_t i = 0; i < tokens.size(); ++i)
    {
        if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos)
        {
            token_to_complete = i;
            break;
        }
    }

    if (token_to_complete == 0 or tokens.empty()) // command name completion
    {
        size_t cmd_start = tokens.empty() ? 0 : tokens[0].first;
        Completions result(cmd_start, cursor_pos);
        std::string prefix = command_line.substr(cmd_start,
                                                 cursor_pos - cmd_start);

        for (auto& command : m_commands)
        {
            if (command.first.substr(0, prefix.length()) == prefix)
                result.candidates.push_back(command.first);
        }

        return result;
    }

    assert(not tokens.empty());
    std::string command_name =
        command_line.substr(tokens[0].first,
                            tokens[0].second - tokens[0].first);

    auto command_it = m_commands.find(command_name);
    if (command_it == m_commands.end() or not command_it->second.completer)
        return Completions();

    CommandParameters params;
    for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)
    {
        params.push_back(command_line.substr(it->first,
                                             it->second - it->first));
    }
    Completions result(tokens[token_to_complete].first, cursor_pos);
    size_t cursor_pos_in_token = cursor_pos - tokens[token_to_complete].first;

    result.candidates = command_it->second.completer(params,
                                                     token_to_complete - 1,
                                                     cursor_pos_in_token);
    return result;
}

CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params,
                                                      size_t token_to_complete,
                                                      size_t pos_in_token) const
{
    if (token_to_complete >= m_completers.size())
        return CandidateList();

    // it is possible to try to complete a new argument
    assert(token_to_complete <= params.size());

    const std::string& argument = token_to_complete < params.size() ?
                                  params[token_to_complete] : std::string();
    return m_completers[token_to_complete](argument, pos_in_token);
}

}
<|endoftext|>


<commit_before>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   AuxiliarySimulationFunctions.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2010-06-30
//!
//! @brief Contains a second order integrator utility with provision for some damping
//!
//$Id$

#include "ComponentUtilities/AuxiliarySimulationFunctions.h"
#include <cmath>
#include <limits>

using namespace hopsan;

//! @defgroup ComponentUtilities ComponentUtilities
//! @defgroup AuxiliarySimulationFunctions AuxiliarySimulationFunctions
//! @ingroup ComponentUtilities
//! @defgroup ComponentUtilityClasses ComponentUtilityClasses
//! @ingroup ComponentUtilities

//! @brief Limits a value so it is between min and max
//! @ingroup AuxiliarySimulationFunctions
//! @param &rValue Reference pointer to the value
//! @param min Lower limit of the value
//! @param max Upper limit of the value
void hopsan::limitValue(double &rValue, double min, double max)
{
    if(min>max)
    {
        double temp;
        temp = max;
        max = min;
        min = temp;
    }
    if(rValue > max)
    {
        rValue = max;
    }
    else if(rValue < min)
    {
        rValue = min;
    }
}

//! @brief checks if two double variables are equal with a tolerance
//! @ingroup AuxiliarySimulationFunctions
//! @param [in] x First value
//! @param [in] y Second value
//! @param [in] epsilon Allowed relative error
//! @note Based on http://floating-point-gui.de/errors/comparison (20130429)
bool hopsan::fuzzyEqual(const double x, const double y, const double epsilon)
{
    const double absX = fabs(x);
    const double absY = fabs(y);
    const double diff = fabs(x-y);

    // shortcut, handles infinities
    if (x == y)
    {
        return true;
    }
    // a or b is zero or both are extremely close to it
    // relative error is less meaningful here
    else if (x == 0 || y == 0 || diff < epsilon * std::numeric_limits<double>::epsilon() ) //! @todo Added multiplication with epsilon here, otherwise it may return false without ever reaching the second comparison
    {
        return diff < (epsilon * std::numeric_limits<double>::epsilon() );
    }
    // use relative error
    else
    {
        return diff / (absX + absY) < epsilon;
    }
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::signedSquareL(const double x, const double x0)
{
//    return (-sqrt(x0) + sqrt(x0 + fabs(x))) * sign(x);
    return fabs(x)*pow(1/(pow(x0,2) + pow(fabs(x),2)),0.25)*sign(x);
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSignedSquareL(const double x, const double x0)
{
//    return (1.0 / (sqrt(x0 + fabs(x)) * 2.0));
    return (pow(1/(pow(x0,2) + pow(fabs(x),2)),1.25)*(2*pow(x0,2) + pow(fabs(x),2))*
            dxAbs(x)*sign(x))/2.;
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::squareAbsL(const double x, const double x0)
{
    return (-sqrt(x0) + sqrt(x0 + fabs(x)));
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSquareAbsL(const double x, const double x0)
{
    return 1.0 / (sqrt(x0 + fabs(x)) * 2.0) * sign(x);
}

//! @brief Safe variant of atan2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::Atan2L(const double y, const double x)
{
    if (x!=0 || y!=0)
    {
        return atan2(y,x);
    }
    else
    {
        return 0;
    }
}

//! @brief Returns 1.0 if input variables have same sign, else returns 0.0
//! @ingroup AuxiliarySimulationFunctions
double hopsan::equalSigns(const double x, const double y)
{
//    //! @warning This will NOT work (double != double)
//    if (hopsan::sign(x) != hopsan::sign(y)) {
//        return 0.0;
//    }
//    return 1.0;

    if ( ((x < 0.0) && ( y < 0.0)) || ((x >= 0.0) && (y >= 0.0)) )
    {
        return 1.0;
    }
    else
    {
        return 0.0;
    }
}

//! @brief Safe variant of asin
//! @ingroup AuxiliarySimulationFunctions
double hopsan::ArcSinL(const double x)
{
    return asin(limit(x,-0.9999999999,0.9999999999));
}

//! @brief derivative of AsinL
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxArcSinL(const double x)
{
    return 1.0/sqrt(1 - pow(limit(x,-0.9999999999,0.9999999999),2));
}

//! @brief difference between two angles, fi1-fi2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::diffAngle(const double fi1, const double fi2)
{   double output;
    double output0 = fi1-fi2;
    double output1 = fi1-fi2 + 2.0*pi;
    double output2 = fi1-fi2 - 2.0*pi;
                                      output = output0;
    if (fabs(output0)>= fabs(output1)){output = output1;}
    if (fabs(output0)>= fabs(output2)){output = output2;}

    return output;
}

//! @brief Lift coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CLift(const double alpha, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
    return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*alpha*
            CLalpha + 0.707107*(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) +
              1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*sin(2*alpha);
}

//! @brief Induced drag coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CDragInd(const double alpha, const double AR, const double e, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
    return (0.31831*(1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
             pow(alpha,2)*pow(CLalpha,2))/(AR*e) +
          (1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
           pow(sin(alpha),2);
}

//! @brief Moment coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CMoment(const double alpha, const double Cm0, const double Cmfs, const double /*ap*/, const double /*an*/, const double /*awp*/, const double /*awn*/)
{
    return (1 - 1/(1 + pow(2.71828,-20.*(-0.5 - alpha))) - 1/(1 + pow(2.71828,-20.*(-0.5 + alpha))))*Cm0 +
            (1/(1 + pow(2.71828,-20.*(-0.5 - alpha))) + 1/(1 + pow(2.71828,-20.*(-0.5 + alpha))))*Cmfs*sign(alpha);
}

//! @brief Overloads void hopsan::limitValue() with a return value.
//! @ingroup AuxiliarySimulationFunctions
//! @see void hopsan::limitValue(&value, min, max)
//! @param x Value to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
double hopsan::limit(const double x, const double xmin, const double xmax)
{
    double output = x;
    limitValue(output, xmin, xmax);
    return output;
}

//! @brief Limits a value to a lower limit
//! @ingroup AuxiliarySimulationFunctions
//! @param x Value to be limited
//! @param xmin Minimum value of x
double hopsan::lowLimit(const double x, const double xmin)
{
    if(x < xmin)
    {
        return xmin;
    }
    else
    {
        return x;
    }
}

//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit(const double x, const double xmin, const double xmax)
{
    if (x >= xmax) { return 0.000000001; }
    if (x <= xmin) { return 0.000000001; }
    return 1.0;
}

//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit(const double x,const double xmin)
{
    if (x <= xmin) { return 0.000000001; }
    return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit2(const double x, const double sx, const double xmin)
{
    if (x <= xmin && sx <= 0.0) { return 0.000000001; }
    return 1.0;
}

//! @brief Limits the derivative of x when x is outside of its limits.
//! @ingroup AuxiliarySimulationFunctions
//! Returns 1.0 if x is within borders, or if x is outside borders but derivative has opposite sign (so that x can only move back to the limited range).
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit2(const double x, const double sx, const double xmin, const double xmax)
{
    if (x >= xmax && sx >= 0.0) { return 0.000000001; }
    if (x <= xmin && sx <= 0.0) { return 0.000000001; }
    return 1.0;
}

//! @brief Returns the algebraic quotient x/y with any fractional parts discarded
//! @ingroup AuxiliarySimlationFunctions
//! @ingroup ModelicaWrapperFunctions
//! @param x Numerator
//! @param y Denominator
//! @returns Algebraic quotient with any fractional parts discarded
double hopsan::div(const double x, const double y)
{
    if(x/y > 0)
    {
        return floor(x/y);
    }
    else
    {
        return ceil(x/y);
    }
}
<commit_msg>segare added<commit_after>/*-----------------------------------------------------------------------------
 This source file is part of Hopsan NG

 Copyright (c) 2011
    Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
    Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack

 This file is provided "as is", with no guarantee or warranty for the
 functionality or reliability of the contents. All contents in this file is
 the original work of the copyright holders at the Division of Fluid and
 Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
 redistributing any part of this file is prohibited without explicit
 permission from the copyright holders.
-----------------------------------------------------------------------------*/

//!
//! @file   AuxiliarySimulationFunctions.cc
//! @author Robert Braun <robert.braun@liu.se>
//! @date   2010-06-30
//!
//! @brief Contains a second order integrator utility with provision for some damping
//!
//$Id$

#include "ComponentUtilities/AuxiliarySimulationFunctions.h"
#include <cmath>
#include <limits>

using namespace hopsan;

//! @defgroup ComponentUtilities ComponentUtilities
//! @defgroup AuxiliarySimulationFunctions AuxiliarySimulationFunctions
//! @ingroup ComponentUtilities
//! @defgroup ComponentUtilityClasses ComponentUtilityClasses
//! @ingroup ComponentUtilities

//! @brief Limits a value so it is between min and max
//! @ingroup AuxiliarySimulationFunctions
//! @param &rValue Reference pointer to the value
//! @param min Lower limit of the value
//! @param max Upper limit of the value
void hopsan::limitValue(double &rValue, double min, double max)
{
    if(min>max)
    {
        double temp;
        temp = max;
        max = min;
        min = temp;
    }
    if(rValue > max)
    {
        rValue = max;
    }
    else if(rValue < min)
    {
        rValue = min;
    }
}

//! @brief checks if two double variables are equal with a tolerance
//! @ingroup AuxiliarySimulationFunctions
//! @param [in] x First value
//! @param [in] y Second value
//! @param [in] epsilon Allowed relative error
//! @note Based on http://floating-point-gui.de/errors/comparison (20130429)
bool hopsan::fuzzyEqual(const double x, const double y, const double epsilon)
{
    const double absX = fabs(x);
    const double absY = fabs(y);
    const double diff = fabs(x-y);

    // shortcut, handles infinities
    if (x == y)
    {
        return true;
    }
    // a or b is zero or both are extremely close to it
    // relative error is less meaningful here
    else if (x == 0 || y == 0 || diff < epsilon * std::numeric_limits<double>::epsilon() ) //! @todo Added multiplication with epsilon here, otherwise it may return false without ever reaching the second comparison
    {
        return diff < (epsilon * std::numeric_limits<double>::epsilon() );
    }
    // use relative error
    else
    {
        return diff / (absX + absY) < epsilon;
    }
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::signedSquareL(const double x, const double x0)
{
//    return (-sqrt(x0) + sqrt(x0 + fabs(x))) * sign(x);
    return fabs(x)*pow(1/(pow(x0,2) + pow(fabs(x),2)),0.25)*sign(x);
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSignedSquareL(const double x, const double x0)
{
//    return (1.0 / (sqrt(x0 + fabs(x)) * 2.0));
    return (pow(1/(pow(x0,2) + pow(fabs(x),2)),1.25)*(2*pow(x0,2) + pow(fabs(x),2))*
            dxAbs(x)*sign(x))/2.;
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::squareAbsL(const double x, const double x0)
{
    return (-sqrt(x0) + sqrt(x0 + fabs(x)));
}

//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSquareAbsL(const double x, const double x0)
{
    return 1.0 / (sqrt(x0 + fabs(x)) * 2.0) * sign(x);
}

//! @brief Safe variant of atan2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::Atan2L(const double y, const double x)
{
    if (x!=0 || y!=0)
    {
        return atan2(y,x);
    }
    else
    {
        return 0;
    }
}

//! @brief Returns 1.0 if input variables have same sign, else returns 0.0
//! @ingroup AuxiliarySimulationFunctions
double hopsan::equalSigns(const double x, const double y)
{
//    //! @warning This will NOT work (double != double)
//    if (hopsan::sign(x) != hopsan::sign(y)) {
//        return 0.0;
//    }
//    return 1.0;

    if ( ((x < 0.0) && ( y < 0.0)) || ((x >= 0.0) && (y >= 0.0)) )
    {
        return 1.0;
    }
    else
    {
        return 0.0;
    }
}

//! @brief Safe variant of asin
//! @ingroup AuxiliarySimulationFunctions
double hopsan::ArcSinL(const double x)
{
    return asin(limit(x,-0.9999999999,0.9999999999));
}

//! @brief derivative of AsinL
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxArcSinL(const double x)
{
    return 1.0/sqrt(1 - pow(limit(x,-0.9999999999,0.9999999999),2));
}

//! @brief difference between two angles, fi1-fi2
//! @ingroup AuxiliarySimulationFunctions
double hopsan::diffAngle(const double fi1, const double fi2)
{   double output;
    double output0 = fi1-fi2;
    double output1 = fi1-fi2 + 2.0*pi;
    double output2 = fi1-fi2 - 2.0*pi;
                                      output = output0;
    if (fabs(output0)>= fabs(output1)){output = output1;}
    if (fabs(output0)>= fabs(output2)){output = output2;}

    return output;
}

//! @brief Lift coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CLift(const double alpha, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
    return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*alpha*
            CLalpha + 0.707107*(1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) +
              1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*sin(2*alpha);
}

//! @brief Induced drag coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CDragInd(const double alpha, const double AR, const double e, const double CLalpha, const double ap, const double an, const double awp, const double awn)
{
    return (0.31831*(1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
             pow(alpha,2)*pow(CLalpha,2))/(AR*e) +
          (1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*
           pow(sin(alpha),2);
}

//! @brief Moment coefficient for aircraft model
//! @ingroup AuxiliarySimulationFunctions
double hopsan::CMoment(const double alpha, const double Cm0, const double Cmfs, const double ap, const double an, const double awp, const double awn)
{
    return (1 - 1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) - 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*Cm0 +
            (1/(1 + pow(2.71828,(-2*(-alpha - an))/awn)) + 1/(1 + pow(2.71828,(-2*(alpha - ap))/awp)))*Cmfs*sign(alpha);
}

//! @brief Segment area, used to calculate valve openings with circular holes
//! @ingroup AuxiliarySimulationFunctions
double hopsan::segare(const double x, const double d)
{
    double x1;
    x1=x;
    if(x < 0)
    {
        x1=0;
    }
    else
    {
        if(x > d)
        {
           x1=d;
        }
        else
        {
           x1=x;
        }
    }
    return -(d*(2*(d - 2*x1)*sqrt(((d - x1)*x1)/pow(d,2)) - d*acos(1 - (2*x1)/d)))/4.;
}
//! @brief Segment area, used to calculate valve openings with circular holes
//! @ingroup AuxiliarySimulationFunctions
double hopsan::dxSegare(const double x, const double d)
{
    double x1;
    x1=x;
    if(x < 0)
    {
        x1=0;
    }
    else
    {
        if(x > d)
        {
           x1=d;
        }
        else
        {
           x1=x;
        }
    }
    return 2*sqrt((d - x)*x);
}

//! @brief Overloads void hopsan::limitValue() with a return value.
//! @ingroup AuxiliarySimulationFunctions
//! @see void hopsan::limitValue(&value, min, max)
//! @param x Value to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
double hopsan::limit(const double x, const double xmin, const double xmax)
{
    double output = x;
    limitValue(output, xmin, xmax);
    return output;
}

//! @brief Limits a value to a lower limit
//! @ingroup AuxiliarySimulationFunctions
//! @param x Value to be limited
//! @param xmin Minimum value of x
double hopsan::lowLimit(const double x, const double xmin)
{
    if(x < xmin)
    {
        return xmin;
    }
    else
    {
        return x;
    }
}

//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit(const double x, const double xmin, const double xmax)
{
    if (x >= xmax) { return 0.000000001; }
    if (x <= xmin) { return 0.000000001; }
    return 1.0;
}

//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit(const double x,const double xmin)
{
    if (x <= xmin) { return 0.000000001; }
    return 1.0;
}
//! @brief Sets the derivative of x to zero if x is outside of limits.
//! @ingroup AuxiliarySimulationFunctions
//! @details Returns 1.0 if x is within limits, else 0.0. Used to make the derivative of x zero if limit is reached.
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @returns Limited derivative of x
double hopsan::dxLowLimit2(const double x, const double sx, const double xmin)
{
    if (x <= xmin && sx <= 0.0) { return 0.000000001; }
    return 1.0;
}

//! @brief Limits the derivative of x when x is outside of its limits.
//! @ingroup AuxiliarySimulationFunctions
//! Returns 1.0 if x is within borders, or if x is outside borders but derivative has opposite sign (so that x can only move back to the limited range).
//! @param x Value whose derivative is to be limited
//! @param xmin Minimum value of x
//! @param xmax Maximum value of x
//! @returns Limited derivative of x
double hopsan::dxLimit2(const double x, const double sx, const double xmin, const double xmax)
{
    if (x >= xmax && sx >= 0.0) { return 0.000000001; }
    if (x <= xmin && sx <= 0.0) { return 0.000000001; }
    return 1.0;
}

//! @brief Returns the algebraic quotient x/y with any fractional parts discarded
//! @ingroup AuxiliarySimlationFunctions
//! @ingroup ModelicaWrapperFunctions
//! @param x Numerator
//! @param y Denominator
//! @returns Algebraic quotient with any fractional parts discarded
double hopsan::div(const double x, const double y)
{
    if(x/y > 0)
    {
        return floor(x/y);
    }
    else
    {
        return ceil(x/y);
    }
}
<|endoftext|>


<commit_before>/*
 OpenLieroX

 version parsing

 file created 29-02-2008 by albert
 code under LGPL
 */

#include "Version.h"
#include "LieroX.h"
#include "Debug.h"
#include "AuxLib.h"
#include "CodeAttributes.h"

#include "Version_generated.h"

#ifndef		LX_VERSION
#	define		LX_VERSION	"0.59_beta10"
#endif

#define		GAMENAME			"OpenLieroX"

#ifndef ONLY_MACRODEF  // The above defines are used in resurce.rc

const char* const fullGameName = GAMENAME "/" LX_VERSION;

const char* GetGameName() {
	return GAMENAME;
}

INLINE void setByString__optionalPostCheck(const Version* version, const std::string& versionStr) {
#ifdef DEBUG
	if(version->asString() != versionStr) {
		notes << "WARNING: Version::setByString: '" << versionStr << "' get parsed as '" << version->asString() << "'" << endl;
	}
#endif
}

void Version::setByString(const std::string& versionStr) {
	if(versionStr == "") { reset(); setByString__optionalPostCheck(this,versionStr); return; }

	std::string tmp = versionStr;

	size_t p = tmp.find_first_of(" /\\");
	if(p == std::string::npos)
		gamename = "OpenLieroX"; // old OLX sends sometimes not its name
	else {
		gamename = tmp.substr(0, p);
		tmp.erase(0, p + 1);
	}

	// reset some values
	num = subnum = subsubnum = revnum = 0;
	releasetype = RT_NORMAL;
	stringlwr(tmp); // to have beta instead of Beta

	// num
	p = tmp.find(".");
	bool fail = false;
	num = from_string<int>(tmp.substr(0, p), fail);
	if(fail) { num = 0; setByString__optionalPostCheck(this,versionStr); return; }
	if(p == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, p + 1);

	// subnum
	p = tmp.find_first_of("._-");
	subnum = from_string<int>(tmp.substr(0, p), fail);
	if(fail) { subnum = 0; setByString__optionalPostCheck(this,versionStr); return; }
	if(p == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, p + 1);

	// releasetype
	if(tmp == "") { setByString__optionalPostCheck(this,versionStr); return; }
	size_t nextNumP = tmp.find_first_of("0123456789");
	if(nextNumP == 0)
		releasetype = RT_NORMAL;
	else if(tmp.find("alpha") == 0)
		releasetype = RT_ALPHA;
	else if(tmp.find("beta") == 0)
		releasetype = RT_BETA;
	else if(tmp.find("rc") == 0)
		releasetype = RT_RC;
	else
		releasetype = RT_UNKNOWN;
	tmp.erase(0, nextNumP);

	// subsubnum
	if(tmp == "") { setByString__optionalPostCheck(this,versionStr); return; }
	if(tmp.find_first_of(".") == 0) tmp.erase(0, 1);
	p = tmp.find_first_of("._-");
	subsubnum = from_string<int>(tmp.substr(0, p), fail);
	if(fail) { subsubnum = 0; setByString__optionalPostCheck(this,versionStr); return; }
	if(p == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, p + 1);

	// revnum
	nextNumP = tmp.find_first_of("0123456789");
	if(nextNumP == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, nextNumP);
	revnum = from_string<int>(tmp, fail);
	if(fail) revnum = 0;

	setByString__optionalPostCheck(this,versionStr); return;
}

std::string Version::asString() const {
	std::string ret = gamename;
	ret += "/";
	ret += itoa(num);
	ret += ".";
	ret += itoa(subnum);

	if(subsubnum > 0) {
		switch(releasetype) {
		case RT_NORMAL: ret += "."; break;
		case RT_ALPHA: ret += "_alpha"; break;
		case RT_BETA: ret += "_beta"; break;
		case RT_RC: ret += "_rc"; break;
		case RT_UNKNOWN: ret += "_"; break;
		}
		ret += itoa(subsubnum);
	}

	if(revnum > 0) {
		ret += "_r";
		ret += itoa(revnum);
	}

	return ret;
}

std::string Version::asHumanString() const
{
	std::string ret = gamename;
	ret += " ";
	ret += itoa(num);
	ret += ".";
	ret += itoa(subnum);

	if(subsubnum > 0) {
		switch(releasetype) {
		case RT_NORMAL: ret += "."; break;
		case RT_ALPHA: ret += " alpha "; break;
		case RT_BETA: ret += " beta "; break;
		case RT_RC: ret += " rc "; break;
		case RT_UNKNOWN: ret += " "; break;
		}
		ret += itoa(subsubnum);
	}

	return ret;
}

std::string Version::releaseType() const
{
	switch(releasetype) {
	case RT_NORMAL: return "final";
	case RT_ALPHA: return "alpha";
	case RT_BETA: return "beta";
	case RT_RC: return "rc";
	case RT_UNKNOWN: return "unknown";
	}

	return "error"; // should not happen
}

static Version gameVersion(GetFullGameName());

const Version& GetGameVersion() {
	return gameVersion;
}

bool Version::isBanned() const {
	return
	*this == OLXBetaVersion(9) || // too much different games with this branding around
	*this == OLXBetaVersion(0,58,1) || // TODO: ehm, what was it again?
	(*this >= OLXBetaVersion(0,59,1) && *this <= OLXBetaVersion(0,59,4)); // Gusanos protocol has changed
}

#endif  // ONLY_MACRODEF
<commit_msg>banned versions: any other alpha/beta expect the current<commit_after>/*
 OpenLieroX

 version parsing

 file created 29-02-2008 by albert
 code under LGPL
 */

#include "Version.h"
#include "LieroX.h"
#include "Debug.h"
#include "AuxLib.h"
#include "CodeAttributes.h"

#include "Version_generated.h"

#ifndef		LX_VERSION
#	define		LX_VERSION	"0.59_beta10"
#endif

#define		GAMENAME			"OpenLieroX"

#ifndef ONLY_MACRODEF  // The above defines are used in resurce.rc

const char* const fullGameName = GAMENAME "/" LX_VERSION;

const char* GetGameName() {
	return GAMENAME;
}

INLINE void setByString__optionalPostCheck(const Version* version, const std::string& versionStr) {
#ifdef DEBUG
	if(version->asString() != versionStr) {
		notes << "WARNING: Version::setByString: '" << versionStr << "' get parsed as '" << version->asString() << "'" << endl;
	}
#endif
}

void Version::setByString(const std::string& versionStr) {
	if(versionStr == "") { reset(); setByString__optionalPostCheck(this,versionStr); return; }

	std::string tmp = versionStr;

	size_t p = tmp.find_first_of(" /\\");
	if(p == std::string::npos)
		gamename = "OpenLieroX"; // old OLX sends sometimes not its name
	else {
		gamename = tmp.substr(0, p);
		tmp.erase(0, p + 1);
	}

	// reset some values
	num = subnum = subsubnum = revnum = 0;
	releasetype = RT_NORMAL;
	stringlwr(tmp); // to have beta instead of Beta

	// num
	p = tmp.find(".");
	bool fail = false;
	num = from_string<int>(tmp.substr(0, p), fail);
	if(fail) { num = 0; setByString__optionalPostCheck(this,versionStr); return; }
	if(p == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, p + 1);

	// subnum
	p = tmp.find_first_of("._-");
	subnum = from_string<int>(tmp.substr(0, p), fail);
	if(fail) { subnum = 0; setByString__optionalPostCheck(this,versionStr); return; }
	if(p == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, p + 1);

	// releasetype
	if(tmp == "") { setByString__optionalPostCheck(this,versionStr); return; }
	size_t nextNumP = tmp.find_first_of("0123456789");
	if(nextNumP == 0)
		releasetype = RT_NORMAL;
	else if(tmp.find("alpha") == 0)
		releasetype = RT_ALPHA;
	else if(tmp.find("beta") == 0)
		releasetype = RT_BETA;
	else if(tmp.find("rc") == 0)
		releasetype = RT_RC;
	else
		releasetype = RT_UNKNOWN;
	tmp.erase(0, nextNumP);

	// subsubnum
	if(tmp == "") { setByString__optionalPostCheck(this,versionStr); return; }
	if(tmp.find_first_of(".") == 0) tmp.erase(0, 1);
	p = tmp.find_first_of("._-");
	subsubnum = from_string<int>(tmp.substr(0, p), fail);
	if(fail) { subsubnum = 0; setByString__optionalPostCheck(this,versionStr); return; }
	if(p == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, p + 1);

	// revnum
	nextNumP = tmp.find_first_of("0123456789");
	if(nextNumP == std::string::npos) { setByString__optionalPostCheck(this,versionStr); return; }
	tmp.erase(0, nextNumP);
	revnum = from_string<int>(tmp, fail);
	if(fail) revnum = 0;

	setByString__optionalPostCheck(this,versionStr); return;
}

std::string Version::asString() const {
	std::string ret = gamename;
	ret += "/";
	ret += itoa(num);
	ret += ".";
	ret += itoa(subnum);

	if(subsubnum > 0) {
		switch(releasetype) {
		case RT_NORMAL: ret += "."; break;
		case RT_ALPHA: ret += "_alpha"; break;
		case RT_BETA: ret += "_beta"; break;
		case RT_RC: ret += "_rc"; break;
		case RT_UNKNOWN: ret += "_"; break;
		}
		ret += itoa(subsubnum);
	}

	if(revnum > 0) {
		ret += "_r";
		ret += itoa(revnum);
	}

	return ret;
}

std::string Version::asHumanString() const
{
	std::string ret = gamename;
	ret += " ";
	ret += itoa(num);
	ret += ".";
	ret += itoa(subnum);

	if(subsubnum > 0) {
		switch(releasetype) {
		case RT_NORMAL: ret += "."; break;
		case RT_ALPHA: ret += " alpha "; break;
		case RT_BETA: ret += " beta "; break;
		case RT_RC: ret += " rc "; break;
		case RT_UNKNOWN: ret += " "; break;
		}
		ret += itoa(subsubnum);
	}

	return ret;
}

std::string Version::releaseType() const
{
	switch(releasetype) {
	case RT_NORMAL: return "final";
	case RT_ALPHA: return "alpha";
	case RT_BETA: return "beta";
	case RT_RC: return "rc";
	case RT_UNKNOWN: return "unknown";
	}

	return "error"; // should not happen
}

static Version gameVersion(GetFullGameName());

const Version& GetGameVersion() {
	return gameVersion;
}

bool Version::isBanned() const {
	if(*this == OLXBetaVersion(9)) return true; // too much different games with this branding around
	if(*this == OLXBetaVersion(0,58,1)) return true; // TODO: ehm, what was it again?
	if(releasetype == RT_ALPHA || releasetype == RT_BETA)
		if(*this < GetGameVersion()) return true; // another earlier beta - dont trust it
	return false;
}

#endif  // ONLY_MACRODEF
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: i_comrela.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-12 15:14:06 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <ary/idl/i_comrela.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary/ary.hxx>
#include <ary/idl/i_gate.hxx>
#include <ary/idl/ip_ce.hxx>
#include <ary/idl/ip_type.hxx>

namespace ary
{
namespace idl
{

// KORR_FUTURE Currently unneeded file. May become useful later.

}   //  namespace   idl
}   //  namespace   ary
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.24); FILE MERGED 2005/09/05 13:09:55 rt 1.2.24.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: i_comrela.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 16:40:47 $
 *
 *  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
 *
 ************************************************************************/

#include <precomp.h>
#include <ary/idl/i_comrela.hxx>

// NOT FULLY DEFINED SERVICES
#include <ary/ary.hxx>
#include <ary/idl/i_gate.hxx>
#include <ary/idl/ip_ce.hxx>
#include <ary/idl/ip_type.hxx>

namespace ary
{
namespace idl
{

// KORR_FUTURE Currently unneeded file. May become useful later.

}   //  namespace   idl
}   //  namespace   ary
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: namedvaluecollection.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX
#define COMPHELPER_NAMEDVALUECOLLECTION_HXX

#include <comphelper/comphelperdllapi.h>

/** === begin UNO includes === **/
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
/** === end UNO includes === **/

#include <memory>

//........................................................................
namespace comphelper
{
//........................................................................

    // ====================================================================
    // = NamedValueCollection
    // ====================================================================
    struct NamedValueCollection_Impl;
    /** a collection of named values, packed in various formats.
    */
    class COMPHELPER_DLLPUBLIC NamedValueCollection
    {
    private:
        ::std::auto_ptr< NamedValueCollection_Impl >    m_pImpl;

    public:
        NamedValueCollection();

        /** constructs a collection
            @param  _rElements
                the wrapped elements of the collection. The Any might contain a sequence of
                property values, a sequence of named values, or directly a property value or named value.
                All other cases are worth an assertion in non-product builds.
        */
        NamedValueCollection( const ::com::sun::star::uno::Any& _rElements );

        /** constructs a collection
            @param _rArguments
                a sequence of Any's containing either PropertyValue's or NamedValue's.
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of PropertyValues's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of NamedValue's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        ~NamedValueCollection();

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        /// returns the number of elements in the collection
        size_t  size() const;

        /// determines whether the collection is empty
        bool    empty() const;

        /** retrieves a value with a given name from the collection, if it is present

            @param _pAsciiValueName
                the ASCII name of the value to retrieve

            @param _out_rValue
                is the output parameter taking the desired value upon successful return. If
                a value with the given name is not present in the collection, or if a wrong-typed
                value is present, then this parameter will not be touched.

            @return
                <TRUE/> if there is a value with the given name, which could successfully
                be extraced. In this case, <arg>_out_rValue</arg> will contain the requested
                value.

                <FALSE/>, if there is no value with the given name.
            @throws IllegalArgumentException
                in case there is a value with the given name, but it cannot legally assigned to
                _out_rValue.
        */
        template < typename VALUE_TYPE >
        bool get_ensureType( const sal_Char* _pAsciiValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( ::rtl::OUString::createFromAscii( _pAsciiValueName ), &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        template < typename VALUE_TYPE >
        bool    get_ensureType( const ::rtl::OUString& _rValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( _rValueName, &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        /** retrieves a value with a given name, or defaults it to a given value, if its not present
            in the colllection
        */
        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rDefault ) const
        {
            return getOrDefault( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rDefault );
        }

        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rDefault ) const
        {
            VALUE_TYPE retVal( _rDefault );
            get_ensureType( _rValueName, retVal );
            return retVal;
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const sal_Char* _pAsciiValueName ) const
        {
            return get( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const ::rtl::OUString& _rValueName ) const
        {
            return impl_get( _rValueName );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const sal_Char* _pAsciiValueName ) const
        {
            return impl_has( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const ::rtl::OUString& _rValueName ) const
        {
            return impl_has( _rValueName );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), ::com::sun::star::uno::makeAny( _rValue ) );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( _rValueName, ::com::sun::star::uno::makeAny( _rValue ) );
        }

        inline bool put( const sal_Char* _pAsciiValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rValue );
        }

        inline bool put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( _rValueName, _rValue );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const sal_Char* _pAsciiValueName )
        {
            return impl_remove( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const ::rtl::OUString& _rValueName )
        {
            return impl_remove( _rValueName );
        }

        /** transforms the collection to a sequence of PropertyValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rValues ) const;

        /** transforms the collection to a sequence of NamedValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rValues ) const;

        /** transforms the collection into a sequence of PropertyValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
                getPropertyValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aValues;
            *this >>= aValues;
            return aValues;
        }

        /** transforms the collection into a sequence of NamedValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >
                getNamedValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > aValues;
            *this >>= aValues;
            return aValues;
        }

    private:
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        bool    get_ensureType(
                    const ::rtl::OUString& _rValueName,
                    void* _pValueLocation,
                    const ::com::sun::star::uno::Type& _rExpectedValueType
                ) const;

        const ::com::sun::star::uno::Any&
                impl_get( const ::rtl::OUString& _rValueName ) const;

        bool    impl_has( const ::rtl::OUString& _rValueName ) const;

        bool    impl_put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue );

        bool    impl_remove( const ::rtl::OUString& _rValueName );
    };

//........................................................................
} // namespace comphelper
//........................................................................

#endif // COMPHELPER_NAMEDVALUECOLLECTION_HXX

<commit_msg>INTEGRATION: CWS dba30b (1.8.8); FILE MERGED 2008/04/15 22:19:45 fs 1.8.8.2: RESYNC: (1.8-1.9); FILE MERGED 2008/03/16 14:00:35 fs 1.8.8.1: #i86996# added: copy ctor / 'merge'<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: namedvaluecollection.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX
#define COMPHELPER_NAMEDVALUECOLLECTION_HXX

#include <comphelper/comphelperdllapi.h>

/** === begin UNO includes === **/
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
/** === end UNO includes === **/

#include <memory>

//........................................................................
namespace comphelper
{
//........................................................................

    // ====================================================================
    // = NamedValueCollection
    // ====================================================================
    struct NamedValueCollection_Impl;
    /** a collection of named values, packed in various formats.
    */
    class COMPHELPER_DLLPUBLIC NamedValueCollection
    {
    private:
        ::std::auto_ptr< NamedValueCollection_Impl >    m_pImpl;

    public:
        NamedValueCollection();

        NamedValueCollection( const NamedValueCollection& _rCopySource );

        /** constructs a collection
            @param  _rElements
                the wrapped elements of the collection. The Any might contain a sequence of
                property values, a sequence of named values, or directly a property value or named value.
                All other cases are worth an assertion in non-product builds.
        */
        NamedValueCollection( const ::com::sun::star::uno::Any& _rElements );

        /** constructs a collection
            @param _rArguments
                a sequence of Any's containing either PropertyValue's or NamedValue's.
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of PropertyValues's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );

        /** constructs a collection
            @param _rArguments
                a sequence of NamedValue's
        */
        NamedValueCollection( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        ~NamedValueCollection();

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        inline void assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments )
        {
            impl_assign( _rArguments );
        }

        /// returns the number of elements in the collection
        size_t  size() const;

        /// determines whether the collection is empty
        bool    empty() const;

        /** merges the content of another collection into |this|
            @param _rAdditionalValues
                the collection whose values are to be merged
            @param _bOverwriteExisting
                defines whether or not elements which are already present in |this|
                should be overwritten (<TRUE/>) or preserved (<FALSE/>).
            @return |*this|
        */
        NamedValueCollection&
                merge(
                    const NamedValueCollection& _rAdditionalValues,
                    bool _bOverwriteExisting
                );

        /** retrieves a value with a given name from the collection, if it is present

            @param _pAsciiValueName
                the ASCII name of the value to retrieve

            @param _out_rValue
                is the output parameter taking the desired value upon successful return. If
                a value with the given name is not present in the collection, or if a wrong-typed
                value is present, then this parameter will not be touched.

            @return
                <TRUE/> if there is a value with the given name, which could successfully
                be extraced. In this case, <arg>_out_rValue</arg> will contain the requested
                value.

                <FALSE/>, if there is no value with the given name.
            @throws IllegalArgumentException
                in case there is a value with the given name, but it cannot legally assigned to
                _out_rValue.
        */
        template < typename VALUE_TYPE >
        bool get_ensureType( const sal_Char* _pAsciiValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( ::rtl::OUString::createFromAscii( _pAsciiValueName ), &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        template < typename VALUE_TYPE >
        bool    get_ensureType( const ::rtl::OUString& _rValueName, VALUE_TYPE& _out_rValue ) const
        {
            return get_ensureType( _rValueName, &_out_rValue, ::cppu::UnoType< VALUE_TYPE >::get() );
        }

        /** retrieves a value with a given name, or defaults it to a given value, if its not present
            in the colllection
        */
        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rDefault ) const
        {
            return getOrDefault( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rDefault );
        }

        template < typename VALUE_TYPE >
        VALUE_TYPE  getOrDefault( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rDefault ) const
        {
            VALUE_TYPE retVal( _rDefault );
            get_ensureType( _rValueName, retVal );
            return retVal;
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const sal_Char* _pAsciiValueName ) const
        {
            return get( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** retrieves a (untyped) value with a given name

            If the collection does not contain a value with the given name, an empty
            Any is returned.
        */
        const ::com::sun::star::uno::Any& get( const ::rtl::OUString& _rValueName ) const
        {
            return impl_get( _rValueName );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const sal_Char* _pAsciiValueName ) const
        {
            return impl_has( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /// determines whether a value with a given name is present in the collection
        inline bool has( const ::rtl::OUString& _rValueName ) const
        {
            return impl_has( _rValueName );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const sal_Char* _pAsciiValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), ::com::sun::star::uno::makeAny( _rValue ) );
        }

        /** puts a value into the collection

            @return <TRUE/> if and only if a value was already present previously, in
                which case it has been overwritten.
        */
        template < typename VALUE_TYPE >
        inline bool put( const ::rtl::OUString& _rValueName, const VALUE_TYPE& _rValue )
        {
            return impl_put( _rValueName, ::com::sun::star::uno::makeAny( _rValue ) );
        }

        inline bool put( const sal_Char* _pAsciiValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( ::rtl::OUString::createFromAscii( _pAsciiValueName ), _rValue );
        }

        inline bool put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue )
        {
            return impl_put( _rValueName, _rValue );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const sal_Char* _pAsciiValueName )
        {
            return impl_remove( ::rtl::OUString::createFromAscii( _pAsciiValueName ) );
        }

        /** removes the value with the given name from the collection

            @return <TRUE/> if and only if a value with the given name existed in the collection.
        */
        inline bool remove( const ::rtl::OUString& _rValueName )
        {
            return impl_remove( _rValueName );
        }

        /** transforms the collection to a sequence of PropertyValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rValues ) const;

        /** transforms the collection to a sequence of NamedValues

            @return
                the  number of elements in the sequence
        */
        sal_Int32 operator >>= ( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _out_rValues ) const;

        /** transforms the collection into a sequence of PropertyValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
                getPropertyValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aValues;
            *this >>= aValues;
            return aValues;
        }

        /** transforms the collection into a sequence of NamedValues
        */
        inline ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >
                getNamedValues() const
        {
            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > aValues;
            *this >>= aValues;
            return aValues;
        }

    private:
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rArguments );
        void    impl_assign( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& _rArguments );

        bool    get_ensureType(
                    const ::rtl::OUString& _rValueName,
                    void* _pValueLocation,
                    const ::com::sun::star::uno::Type& _rExpectedValueType
                ) const;

        const ::com::sun::star::uno::Any&
                impl_get( const ::rtl::OUString& _rValueName ) const;

        bool    impl_has( const ::rtl::OUString& _rValueName ) const;

        bool    impl_put( const ::rtl::OUString& _rValueName, const ::com::sun::star::uno::Any& _rValue );

        bool    impl_remove( const ::rtl::OUString& _rValueName );
    };

//........................................................................
} // namespace comphelper
//........................................................................

#endif // COMPHELPER_NAMEDVALUECOLLECTION_HXX

<|endoftext|>