<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

// Grappa 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
// Affero General Public License for more details.

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////

#pragma once

#include "GlobalAllocator.hpp"
#include "ParallelLoop.hpp"
#include "Metrics.hpp"
#include "FlatCombiner.hpp"
#include <utility>
#include <unordered_map>
#include <vector>

GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_insert_ops);
GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_insert_msgs);
GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_lookup_ops);
GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_lookup_msgs);

namespace Grappa {

template< typename K, typename V >
class GlobalHashMap {
protected:
  struct Entry {
    K key;
    V val;
    Entry( K key ) : key(key), val() {}
    Entry( K key, V val): key(key), val(val) {}
  };

  struct ResultEntry {
    bool found;
    ResultEntry * next;
    V val;
  };

public:
  struct Cell { // TODO: keep first few in the 64-byte block, then go to secondary storage
    std::vector<Entry> entries;

    Cell() : entries() { entries.reserve(10); }

    void clear() { entries.clear(); }

    std::pair<bool,V> lookup(K key) {

      for (auto& e : this->entries) if (e.key == key) return std::pair<bool,K>{true, e.val};
      return std::pair<bool,K>(false,V());
    }
    void insert(const K& key, const V& val) {
      bool found = false;
      for (auto& e : entries) {
        if (e.key == key) {
          e.val = val;
          found = true;
          break;
        }
      }
      if (!found) {
        entries.emplace_back(key, val);
      }
    }
  } GRAPPA_BLOCK_ALIGNED;
protected:
  struct Proxy {
    static const size_t LOCAL_HASH_SIZE = 1<<10;

    GlobalHashMap * owner;
    std::unordered_map<K,V> map;
    std::unordered_map<K,ResultEntry*> lookups;

    Proxy(GlobalHashMap * owner): owner(owner)
      , map(LOCAL_HASH_SIZE)
      , lookups(LOCAL_HASH_SIZE)
    {
      clear();
    }

    void clear() { map.clear(); lookups.clear(); }

    Proxy * clone_fresh() { return locale_new<Proxy>(owner); }

    bool is_full() {
      return map.size() >= LOCAL_HASH_SIZE
          || lookups.size() >= LOCAL_HASH_SIZE;
    }

    void insert(const K& newk, const V& newv) {
      if (map.count(newk) == 0) {
        map[newk] = newv;
      }
    }

    void sync() {
      CompletionEvent ce(map.size()+lookups.size());
      auto cea = make_global(&ce);

      for (auto& e : map) { auto& k = e.first; auto& v = e.second;
        ++hashmap_insert_msgs;
        auto cell = owner->base+owner->computeIndex(k);
        send_heap_message(cell.core(), [cell,cea,k,v]{
          cell->insert(k, v);
          complete(cea);
        });
      }

      for (auto& e : lookups) { auto k = e.first;
        ++hashmap_lookup_msgs;
        auto re = e.second;
        DVLOG(3) << "lookup " << k << " with re = " << re;
        auto cell = owner->base+owner->computeIndex(k);

        send_heap_message(cell.core(), [cell,k,cea,re]{
          Cell * c = cell.localize();
          bool found = false;
          V val;
          for (auto& e : c->entries) if (e.key == k) {
            found = true;
            val = e.val;
            break;
          }
          send_heap_message(cea.core(), [cea,re,found,val]{
            ResultEntry * r = re;
            while (r != nullptr) {
              r->found = found;
              r->val = val;
              r = r->next;
            }
            complete(cea);
          });
        });
      }
      ce.wait();
    }
  };

  // private members
  GlobalAddress<GlobalHashMap> self;
  GlobalAddress< Cell > base;
  size_t capacity;

  FlatCombiner<Proxy> proxy;

  uint64_t computeIndex(K key) {
    static std::hash<K> hasher;
    return hasher(key) % capacity;
  }

  // for creating local GlobalHashMap
  GlobalHashMap( GlobalAddress<GlobalHashMap> self, GlobalAddress<Cell> base, size_t capacity )
    : self(self), base(base), capacity(capacity)
    , proxy(locale_new<Proxy>(this))
  {
    CHECK_LT(sizeof(self)+sizeof(base)+sizeof(capacity)+sizeof(proxy), 2*block_size);
  }

public:
  // for static construction
  GlobalHashMap( ) {}

  static GlobalAddress<GlobalHashMap> create(size_t total_capacity) {
    auto base = global_alloc<Cell>(total_capacity);
    auto self = symmetric_global_alloc<GlobalHashMap>();
    call_on_all_cores([self,base,total_capacity]{
      new (self.localize()) GlobalHashMap(self, base, total_capacity);
    });
    forall(base, total_capacity, [](int64_t i, Cell& c) { new (&c) Cell(); });
    return self;
  }

  GlobalAddress<Cell> begin() { return this->base; }
  size_t ncells() { return this->capacity; }

  void clear() {
    forall(base, capacity, [](Cell& c){ c.clear(); });
  }

  void destroy() {
    auto self = this->self;
    forall(this->base, this->capacity, [](Cell& c){ c.~Cell(); });
    global_free(this->base);
    call_on_all_cores([self]{ self->~GlobalHashMap(); });
    global_free(self);
  }

  template< typename F >
  void forall_entries(F visit) {
    forall(base, capacity, [visit](int64_t i, Cell& c){
      // if cell is not hit then no action
      if (c.entries == nullptr) return;
      DVLOG(3) << "c<" << &c << "> entries:" << c.entries << " size: " << c.entries->size();
      for (Entry& e : *c.entries) {
        visit(e.key, *e.val);
      }
    });
  }

  bool lookup(K key, V * val) {
    ++hashmap_lookup_ops;
    if (FLAGS_flat_combining) {
      ResultEntry re{false,nullptr};
      DVLOG(3) << "lookup[" << key << "] = " << &re;

      proxy.combine([&re,key](Proxy& p){
        // if (p.map.count(key) > 0) {
        //   re.found = true;
        //   re.val = p.map[key];
        //   return FCStatus::SATISFIED;
        // } else {
          if (p.lookups.count(key) == 0) p.lookups[key] = nullptr;
          re.next = p.lookups[key];
          p.lookups[key] = &re;
          DVLOG(3) << "p.lookups[" << key << "] = " << &re;
          return FCStatus::BLOCKED;
        // }
      });
      *val = re.val;
      return re.found;
    } else {
      ++hashmap_lookup_msgs;
      auto result = delegate::call(base+computeIndex(key), [key](Cell* c){
        return c->lookup(key);
      });
      *val = result.second;
      return result.first;
    }
  }

  void insert(K key, V val) {
    ++hashmap_insert_ops;
    if (FLAGS_flat_combining) {
      proxy.combine([key,val](Proxy& p){ p.map[key] = val; return FCStatus::BLOCKED; });
    } else {
      ++hashmap_insert_msgs;
      delegate::call(base+computeIndex(key), [key,val](Cell * c) { c->insert(key,val); });
    }
  }

} GRAPPA_BLOCK_ALIGNED;

template< GlobalCompletionEvent * GCE = &impl::local_gce,
          int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG,
          typename T = decltype(nullptr),
          typename V = decltype(nullptr),
          typename F = decltype(nullptr) >
void forall(GlobalAddress<GlobalHashMap<T,V>> self, F visit) {
  forall<GCE,Threshold>(self->begin(), self->ncells(),
  [visit](typename GlobalHashMap<T,V>::Cell& c){
    for (auto& e : c.entries) {
      visit(e.key, e.val);
    }
  });
}

} // namespace Grappa
<commit_msg>GlobalHashMap::insert_async that takes arbitrary lambda (so we can, for instance, insert into a CoreSet value<commit_after>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

// Grappa 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
// Affero General Public License for more details.

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////

#pragma once

#include "GlobalAllocator.hpp"
#include "ParallelLoop.hpp"
#include "Metrics.hpp"
#include "FlatCombiner.hpp"
#include <utility>
#include <unordered_map>
#include <vector>

GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_insert_ops);
GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_insert_msgs);
GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_lookup_ops);
GRAPPA_DECLARE_METRIC(SimpleMetric<size_t>, hashmap_lookup_msgs);

namespace Grappa {

template< typename K, typename V >
class GlobalHashMap {
protected:
  struct Entry {
    K key;
    V val;
    Entry( K key ) : key(key), val() {}
    Entry( K key, V val): key(key), val(val) {}
  };

  struct ResultEntry {
    bool found;
    ResultEntry * next;
    V val;
  };

public:
  struct Cell { // TODO: keep first few in the 64-byte block, then go to secondary storage
    std::vector<Entry> entries;

    Cell() : entries() { entries.reserve(10); }

    void clear() { entries.clear(); }

    std::pair<bool,V> lookup(K key) {

      for (auto& e : this->entries) if (e.key == key) return std::pair<bool,K>{true, e.val};
      return std::pair<bool,K>(false,V());
    }
    void insert(const K& key, const V& val) {
      bool found = false;
      for (auto& e : entries) {
        if (e.key == key) {
          e.val = val;
          found = true;
          break;
        }
      }
      if (!found) {
        entries.emplace_back(key, val);
      }
    }
  } GRAPPA_BLOCK_ALIGNED;
protected:
  struct Proxy {
    static const size_t LOCAL_HASH_SIZE = 1<<10;

    GlobalHashMap * owner;
    std::unordered_map<K,V> map;
    std::unordered_map<K,ResultEntry*> lookups;

    Proxy(GlobalHashMap * owner): owner(owner)
      , map(LOCAL_HASH_SIZE)
      , lookups(LOCAL_HASH_SIZE)
    {
      clear();
    }

    void clear() { map.clear(); lookups.clear(); }

    Proxy * clone_fresh() { return locale_new<Proxy>(owner); }

    bool is_full() {
      return map.size() >= LOCAL_HASH_SIZE
          || lookups.size() >= LOCAL_HASH_SIZE;
    }

    void insert(const K& newk, const V& newv) {
      if (map.count(newk) == 0) {
        map[newk] = newv;
      }
    }

    void sync() {
      CompletionEvent ce(map.size()+lookups.size());
      auto cea = make_global(&ce);

      for (auto& e : map) { auto& k = e.first; auto& v = e.second;
        ++hashmap_insert_msgs;
        auto cell = owner->base+owner->computeIndex(k);
        send_heap_message(cell.core(), [cell,cea,k,v]{
          cell->insert(k, v);
          complete(cea);
        });
      }

      for (auto& e : lookups) { auto k = e.first;
        ++hashmap_lookup_msgs;
        auto re = e.second;
        DVLOG(3) << "lookup " << k << " with re = " << re;
        auto cell = owner->base+owner->computeIndex(k);

        send_heap_message(cell.core(), [cell,k,cea,re]{
          Cell * c = cell.localize();
          bool found = false;
          V val;
          for (auto& e : c->entries) if (e.key == k) {
            found = true;
            val = e.val;
            break;
          }
          send_heap_message(cea.core(), [cea,re,found,val]{
            ResultEntry * r = re;
            while (r != nullptr) {
              r->found = found;
              r->val = val;
              r = r->next;
            }
            complete(cea);
          });
        });
      }
      ce.wait();
    }
  };

  // private members
  GlobalAddress<GlobalHashMap> self;
  GlobalAddress< Cell > base;
  size_t capacity;

  FlatCombiner<Proxy> proxy;

  uint64_t computeIndex(K key) {
    static std::hash<K> hasher;
    return hasher(key) % capacity;
  }

  // for creating local GlobalHashMap
  GlobalHashMap( GlobalAddress<GlobalHashMap> self, GlobalAddress<Cell> base, size_t capacity )
    : self(self), base(base), capacity(capacity)
    , proxy(locale_new<Proxy>(this))
  {
    CHECK_LT(sizeof(self)+sizeof(base)+sizeof(capacity)+sizeof(proxy), 2*block_size);
  }

public:
  // for static construction
  GlobalHashMap( ) {}

  static GlobalAddress<GlobalHashMap> create(size_t total_capacity) {
    auto base = global_alloc<Cell>(total_capacity);
    auto self = symmetric_global_alloc<GlobalHashMap>();
    call_on_all_cores([self,base,total_capacity]{
      new (self.localize()) GlobalHashMap(self, base, total_capacity);
    });
    forall(base, total_capacity, [](int64_t i, Cell& c) { new (&c) Cell(); });
    return self;
  }

  GlobalAddress<Cell> begin() { return this->base; }
  size_t ncells() { return this->capacity; }

  void clear() {
    forall(base, capacity, [](Cell& c){ c.clear(); });
  }

  void destroy() {
    auto self = this->self;
    forall(this->base, this->capacity, [](Cell& c){ c.~Cell(); });
    global_free(this->base);
    call_on_all_cores([self]{ self->~GlobalHashMap(); });
    global_free(self);
  }

  template< typename F >
  void forall_entries(F visit) {
    forall(base, capacity, [visit](int64_t i, Cell& c){
      // if cell is not hit then no action
      if (c.entries == nullptr) return;
      DVLOG(3) << "c<" << &c << "> entries:" << c.entries << " size: " << c.entries->size();
      for (Entry& e : *c.entries) {
        visit(e.key, *e.val);
      }
    });
  }

  bool lookup(K key, V * val) {
    ++hashmap_lookup_ops;
    if (FLAGS_flat_combining) {
      ResultEntry re{false,nullptr};
      DVLOG(3) << "lookup[" << key << "] = " << &re;

      proxy.combine([&re,key](Proxy& p){
        // if (p.map.count(key) > 0) {
        //   re.found = true;
        //   re.val = p.map[key];
        //   return FCStatus::SATISFIED;
        // } else {
          if (p.lookups.count(key) == 0) p.lookups[key] = nullptr;
          re.next = p.lookups[key];
          p.lookups[key] = &re;
          DVLOG(3) << "p.lookups[" << key << "] = " << &re;
          return FCStatus::BLOCKED;
        // }
      });
      *val = re.val;
      return re.found;
    } else {
      ++hashmap_lookup_msgs;
      auto result = delegate::call(base+computeIndex(key), [key](Cell* c){
        return c->lookup(key);
      });
      *val = result.second;
      return result.first;
    }
  }

  void insert(K key, V val) {
    ++hashmap_insert_ops;
    if (FLAGS_flat_combining) {
      proxy.combine([key,val](Proxy& p){ p.map[key] = val; return FCStatus::BLOCKED; });
    } else {
      ++hashmap_insert_msgs;
      delegate::call(base+computeIndex(key), [key,val](Cell * c) { c->insert(key,val); });
    }
  }

  template< typename F = nullptr_t >
  void insert_async(K key, F on_insert) {
    ++hashmap_insert_msgs;
    delegate::call<SyncMode::Async>(base+computeIndex(key), [=](Cell& c){
      for (auto& e : c.entries) {
        if (e.key == key) {
          on_insert(e.val);
          return;
        }
      }
      c.entries.emplace_back(key);
      on_insert(c.entries.back().val);
    });
  }

} GRAPPA_BLOCK_ALIGNED;

template< GlobalCompletionEvent * GCE = &impl::local_gce,
          int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG,
          typename T = decltype(nullptr),
          typename V = decltype(nullptr),
          typename F = decltype(nullptr) >
void forall(GlobalAddress<GlobalHashMap<T,V>> self, F visit) {
  forall<GCE,Threshold>(self->begin(), self->ncells(),
  [visit](typename GlobalHashMap<T,V>::Cell& c){
    for (auto& e : c.entries) {
      visit(e.key, e.val);
    }
  });
}

} // namespace Grappa
<|endoftext|>


<commit_before>#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <iostream>
#include <unistd.h> //read, write
#include <string.h> //strerror
#include <string>

class TcpClient
{
	public:
		int descriptor;
		bool setup(const char* addr, uint16_t port);
		bool connection();
		bool send(const char* data);
		bool receive();
		char receivedData[1024];

	private:
		struct sockaddr_in server;
};

bool TcpClient::setup(const char *addr, uint16_t port)
{
	server.sin_addr.s_addr = inet_addr(addr);
	server.sin_family = AF_INET;
	server.sin_port = htons( port );
	descriptor = socket(AF_INET , SOCK_STREAM , 0);

	if(descriptor<0)
	{
		std::cerr <<"descriptor creation:  "<< strerror(errno) << std::endl;
		return false;
	}

	else
	{
		return true;
	}
}

bool TcpClient::connection()
{
	if (connect(descriptor , (struct sockaddr *)&server , sizeof(server)) < 0)
	{
		std::cerr <<"connection:  "<< strerror(errno) << std::endl;
		return false;
	}

	else
	{
		return true;
	}
}

bool TcpClient::receive()
{
  memset(receivedData, 0, sizeof(receivedData));
	if( read(descriptor,receivedData,1024)>0)
	{
		return true;
	}
	else return false;
}

bool TcpClient::send(const char* data) //this could be smart string pointer
{
	const size_t len = sizeof(data);
	write(descriptor , data , len);
	return true;
}
<commit_msg>esthetic correction |<commit_after>#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <iostream>
#include <unistd.h> //read, write
#include <string.h> //strerror
#include <string>

class TcpClient
{
	public:
		int descriptor;
		bool setup(const char* addr, uint16_t port);
		bool connection();
		bool send(const char* data);
		bool receive();
		char receivedData[1024];

	private:
		struct sockaddr_in server;
};

bool TcpClient::setup(const char *addr, uint16_t port)
{
	server.sin_addr.s_addr = inet_addr(addr);
	server.sin_family = AF_INET;
	server.sin_port = htons( port );
	descriptor = socket(AF_INET , SOCK_STREAM , 0);

	if(descriptor<0)
	{
		std::cerr <<"descriptor creation:  "<< strerror(errno) << std::endl;
		return false;
	}

	else
	{
		return true;
	}
}

bool TcpClient::connection()
{
	if (connect(descriptor , (struct sockaddr *)&server , sizeof(server)) < 0)
	{
		std::cerr <<"connection:  "<< strerror(errno) << std::endl;
		return false;
	}

	else
	{
		return true;
	}
}

bool TcpClient::receive()
{
  memset(receivedData, 0, sizeof(receivedData));
	if( read(descriptor,receivedData,1024)>0)
	{
		return true;
	}
	else return false;
}

bool TcpClient::send(const char* data) //this could be smart string pointer
{
	write(descriptor , data , strlen(data));
	return true;
}
<|endoftext|>


<commit_before>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <fstream>
// StdAir
#include <stdair/stdair_types.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/FareOptionStruct.hpp>
#include <stdair/service/Logger.hpp>
// TRAVEL-CCM
#include <travelccm/bom/PriceOrientedModel.hpp>

namespace TRAVELCCM {
  // ////////////////////////////////////////////////////////////////////
  const stdair::TravelSolutionStruct* PriceOrientedModel::
  chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,
                        const stdair::BookingRequestStruct& iBookingRequest) {
    stdair::TravelSolutionStruct* oChosenTS_ptr = NULL;

    // Get the willingness-to-pay of the customer
    const stdair::WTP_T& lWTP = iBookingRequest.getWTP();

    stdair::Fare_T lLowestFare = std::numeric_limits<stdair::Fare_T>::max();
    // Browse the travel solution list and choose the cheapest one.
    for (stdair::TravelSolutionList_T::iterator itTS =
           ioTravelSolutionList.begin(); itTS != ioTravelSolutionList.end();
         ++itTS) {
      stdair::TravelSolutionStruct& lCurrentTS = *itTS;

      const stdair::FareOptionList_T& lFareOptionList =
        lCurrentTS.getFareOptionList();
      for (stdair::FareOptionList_T::const_iterator itFO =
             lFareOptionList.begin(); itFO != lFareOptionList.end(); ++itFO) {
        const stdair::FareOptionStruct& lCurrentFO = *itFO;

        // Check the availability.
        const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();
        const stdair::ClassList_StringList_T& lClassPath =
          lCurrentFO.getClassPath();
        const stdair::ClassAvailabilityMapHolder_T& lClassAvailabilityMapHolder =
          lCurrentTS.getClassAvailabilityMapHolder();
        bool lAvlSuff = true;
        stdair::ClassAvailabilityMapHolder_T::const_iterator itCAM =
          lClassAvailabilityMapHolder.begin();
        stdair::ClassList_StringList_T::const_iterator itClassList =
          lClassPath.begin();
        assert (lClassAvailabilityMapHolder.size() > 0 && lClassPath.size() > 0);

        for (; itCAM != lClassAvailabilityMapHolder.end() &&
               itClassList != lClassPath.end(); ++itCAM, ++itClassList) {
          const stdair::ClassList_String_T& lCurrentClassList = *itClassList;
          const stdair::ClassAvailabilityMap_T& lClassAvlMap = *itCAM;
          stdair::ClassCode_T lFirstClass;
          lFirstClass.append (lCurrentClassList, 0, 1);
          const stdair::ClassAvailabilityMap_T::const_iterator itClassAvl =
            lClassAvlMap.find (lFirstClass);

          // DEBUG
          if (itClassAvl == lClassAvlMap.end()) {
            std::ostringstream ostr;
            for (stdair::ClassAvailabilityMap_T::const_iterator it =
                   lClassAvlMap.begin(); it != lClassAvlMap.end(); ++it) {
              ostr << it->first << ", " << it->second << "    ";
            }

            STDAIR_LOG_DEBUG ("Can not find the class: " << lFirstClass
                              << " within the following map: " << ostr.str());

          }
          assert (itClassAvl != lClassAvlMap.end());

          const stdair::Availability_T& lAvl = itClassAvl->second;
          if (lAvl < lPartySize) {
            lAvlSuff = false;
          }
        }

        // Choose the current fare option and the current solution
        // if the current fare is lower than the current lowest fare.
        const stdair::Fare_T& lCurrentFare = lCurrentFO.getFare();
        if (lCurrentFare < lLowestFare && lCurrentFare <= lWTP) {
          lLowestFare = lCurrentFare;
          oChosenTS_ptr = &lCurrentTS;
          oChosenTS_ptr->setChosenFareOption (lCurrentFO);
        }
      }
    }

    return oChosenTS_ptr;
  }

}
<commit_msg>[travelccm] Added debug messages.<commit_after>// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <fstream>
// StdAir
#include <stdair/stdair_types.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/bom/FareOptionStruct.hpp>
#include <stdair/service/Logger.hpp>
// TRAVEL-CCM
#include <travelccm/bom/PriceOrientedModel.hpp>

namespace TRAVELCCM {
  // ////////////////////////////////////////////////////////////////////
  const stdair::TravelSolutionStruct* PriceOrientedModel::
  chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,
                        const stdair::BookingRequestStruct& iBookingRequest) {
    stdair::TravelSolutionStruct* oChosenTS_ptr = NULL;

    // Get the willingness-to-pay of the customer
    const stdair::WTP_T& lWTP = iBookingRequest.getWTP();

    stdair::Fare_T lLowestFare = std::numeric_limits<stdair::Fare_T>::max();
    // Browse the travel solution list and choose the cheapest one.
    for (stdair::TravelSolutionList_T::iterator itTS =
           ioTravelSolutionList.begin(); itTS != ioTravelSolutionList.end();
         ++itTS) {
      stdair::TravelSolutionStruct& lCurrentTS = *itTS;

      const stdair::FareOptionList_T& lFareOptionList =
        lCurrentTS.getFareOptionList();
      for (stdair::FareOptionList_T::const_iterator itFO =
             lFareOptionList.begin(); itFO != lFareOptionList.end(); ++itFO) {
        const stdair::FareOptionStruct& lCurrentFO = *itFO;

        // Check the availability.
        const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();
        const stdair::ClassList_StringList_T& lClassPath =
          lCurrentFO.getClassPath();
        const stdair::ClassAvailabilityMapHolder_T& lClassAvailabilityMapHolder =
          lCurrentTS.getClassAvailabilityMapHolder();
        bool lAvlSuff = true;
        stdair::ClassAvailabilityMapHolder_T::const_iterator itCAMH =
          lClassAvailabilityMapHolder.begin();
        stdair::ClassList_StringList_T::const_iterator itClassList =
          lClassPath.begin();
        assert (lClassAvailabilityMapHolder.size() > 0 && lClassPath.size() > 0);

        for (; itCAMH != lClassAvailabilityMapHolder.end(),
               itClassList != lClassPath.end(); ++itCAMH, ++itClassList) {
          const stdair::ClassList_String_T& lCurrentClassList = *itClassList;
          const stdair::ClassAvailabilityMap_T& lClassAvlMap = *itCAMH;
          stdair::ClassCode_T lFirstClass;
          lFirstClass.append (lCurrentClassList, 0, 1);
          const stdair::ClassAvailabilityMap_T::const_iterator itClassAvl =
            lClassAvlMap.find (lFirstClass);

          // DEBUG
          if (itClassAvl == lClassAvlMap.end()) {
            std::ostringstream ostr;
            for (stdair::ClassAvailabilityMap_T::const_iterator it =
                   lClassAvlMap.begin(); it != lClassAvlMap.end(); ++it) {
              ostr << it->first << ", " << it->second << "    ";
            }

            STDAIR_LOG_DEBUG ("Can not find the class: " << lFirstClass
                              << " within the following map: " << ostr.str());

          }
          assert (itClassAvl != lClassAvlMap.end());

          const stdair::Availability_T& lAvl = itClassAvl->second;
          if (lAvl < lPartySize) {
            lAvlSuff = false;
          }
        }

        // Choose the current fare option and the current solution
        // if the current fare is lower than the current lowest fare.
        const stdair::Fare_T& lCurrentFare = lCurrentFO.getFare();
        if (lCurrentFare < lLowestFare) {
          lLowestFare = lCurrentFare;
          oChosenTS_ptr = &lCurrentTS;
          oChosenTS_ptr->setChosenFareOption (lCurrentFO);
        }
      }
    }

    return oChosenTS_ptr;
  }

}
<|endoftext|>


<commit_before>#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include "soa/types/periodic_utils.h"
#include <boost/test/unit_test.hpp>

using namespace std;
using namespace ML;
using namespace Datacratic;

BOOST_AUTO_TEST_CASE(time_period_test)
{
    TimePeriod tp("20s");
    BOOST_CHECK_EQUAL(tp.interval, 20);
    BOOST_CHECK_EQUAL(tp.toString(), "20s");

    tp.parse("1m");
    BOOST_CHECK_EQUAL(tp.interval, 60);
    BOOST_CHECK_EQUAL(tp.toString(), "1m");

    tp.parse("90s");
    BOOST_CHECK_EQUAL(tp.interval, 90);
    BOOST_CHECK_EQUAL(tp.toString(), "90s");

    bool threw = false;
    try {
        JML_TRACE_EXCEPTIONS(false);
        tp.parse("1m25s");
    }
    catch (...) {
        threw = true;
    }
    BOOST_CHECK(threw);

    tp.parse("1h");
    BOOST_CHECK_EQUAL(tp.interval, 3600);
    BOOST_CHECK_EQUAL(tp.toString(), "1h");

    tp.parse("1d");
    BOOST_CHECK_EQUAL(tp.interval, 3600 * 24);
    BOOST_CHECK_EQUAL(tp.toString(), "1d");
}

#if 1
BOOST_AUTO_TEST_CASE(time_period_granularity_multiplier)
{
    JML_TRACE_EXCEPTIONS(false);

    /* different families */
    BOOST_CHECK_THROW(granularityMultiplier(YEARS, MINUTES), ML::Exception);

    /* seconds cannot be translated to minutes */
    BOOST_CHECK_THROW(granularityMultiplier(SECONDS, MINUTES), ML::Exception);

    int mult = granularityMultiplier(MILLISECONDS, MILLISECONDS);
    BOOST_CHECK_EQUAL(mult, 1);

    mult = granularityMultiplier(MINUTES, MILLISECONDS);
    BOOST_CHECK_EQUAL(mult, 60000);

    mult = granularityMultiplier(MINUTES, MINUTES);
    BOOST_CHECK_EQUAL(mult, 1);

    mult = granularityMultiplier(WEEKS, MINUTES);
    BOOST_CHECK_EQUAL(mult, 10080);

    mult = granularityMultiplier(YEARS, YEARS);
    BOOST_CHECK_EQUAL(mult, 1);

    mult = granularityMultiplier(YEARS, MONTHS);
    BOOST_CHECK_EQUAL(mult, 12);
}
#endif

#if 1
/* Ensure that operators + and += works well for TimePeriod */
BOOST_AUTO_TEST_CASE(time_period_op_plus_equal)
{
    /* same unit */
    {
        TimePeriod period1("2m");
        TimePeriod period2("5m");

        TimePeriod total = period1 + period2;

        BOOST_CHECK_EQUAL(total.granularity, MINUTES);
        BOOST_CHECK_EQUAL(total.number, 7);
        BOOST_CHECK_EQUAL(total.interval, 420);
    }

    /* distinct compatible units */
    {
        TimePeriod period1("1h");
        TimePeriod period2("2s");

        TimePeriod total = period1 + period2;

        BOOST_CHECK_EQUAL(total.granularity, SECONDS);
        BOOST_CHECK_EQUAL(total.number, 3602);
        BOOST_CHECK_EQUAL(total.interval, 3602);

        /* operator += */
        period1 += period2;

        BOOST_CHECK_EQUAL(period1.granularity, SECONDS);
        BOOST_CHECK_EQUAL(period1.number, 3602);
        BOOST_CHECK_EQUAL(period1.interval, 3602);
    }

    /* same as above, in reverse order */
    {
        TimePeriod period1("2s");
        TimePeriod period2("1h");

        TimePeriod total = period1 + period2;

        BOOST_CHECK_EQUAL(total.granularity, SECONDS);
        BOOST_CHECK_EQUAL(total.number, 3602);
        BOOST_CHECK_EQUAL(total.interval, 3602);

        /* operator += */
        period1 += period2;

        BOOST_CHECK_EQUAL(period1.granularity, SECONDS);
        BOOST_CHECK_EQUAL(period1.number, 3602);
        BOOST_CHECK_EQUAL(period1.interval, 3602);
    }

    /* incompatible units */
    {
        TimePeriod yearly;
        yearly.granularity = YEARS;
        yearly.number = 1;
        yearly.interval = -1; // years do not have a fixed set of seconds
        TimePeriod minutely("2m");

        JML_TRACE_EXCEPTIONS(false);
        BOOST_CHECK_THROW(yearly + minutely, ML::Exception);
    }
}
#endif
<commit_msg>PLAT-766: test answers Jeremy's question<commit_after>#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include "soa/types/periodic_utils.h"
#include <boost/test/unit_test.hpp>

using namespace std;
using namespace ML;
using namespace Datacratic;

BOOST_AUTO_TEST_CASE(time_period_test)
{
    TimePeriod tp("20s");
    BOOST_CHECK_EQUAL(tp.interval, 20);
    BOOST_CHECK_EQUAL(tp.toString(), "20s");

    tp.parse("1m");
    BOOST_CHECK_EQUAL(tp.interval, 60);
    BOOST_CHECK_EQUAL(tp.toString(), "1m");

    tp.parse("90s");
    BOOST_CHECK_EQUAL(tp.interval, 90);
    BOOST_CHECK_EQUAL(tp.toString(), "90s");

    bool threw = false;
    try {
        JML_TRACE_EXCEPTIONS(false);
        tp.parse("1m25s");
    }
    catch (...) {
        threw = true;
    }
    BOOST_CHECK(threw);

    tp.parse("1h");
    BOOST_CHECK_EQUAL(tp.interval, 3600);
    BOOST_CHECK_EQUAL(tp.toString(), "1h");

    tp.parse("1d");
    BOOST_CHECK_EQUAL(tp.interval, 3600 * 24);
    BOOST_CHECK_EQUAL(tp.toString(), "1d");
}

#if 1
BOOST_AUTO_TEST_CASE(time_period_granularity_multiplier)
{
    JML_TRACE_EXCEPTIONS(false);

    /* different families */
    BOOST_CHECK_THROW(granularityMultiplier(YEARS, MINUTES), ML::Exception);

    /* seconds cannot be translated to minutes */
    BOOST_CHECK_THROW(granularityMultiplier(SECONDS, MINUTES), ML::Exception);

    int mult = granularityMultiplier(MILLISECONDS, MILLISECONDS);
    BOOST_CHECK_EQUAL(mult, 1);

    mult = granularityMultiplier(MINUTES, MILLISECONDS);
    BOOST_CHECK_EQUAL(mult, 60000);

    mult = granularityMultiplier(MINUTES, MINUTES);
    BOOST_CHECK_EQUAL(mult, 1);

    mult = granularityMultiplier(WEEKS, MINUTES);
    BOOST_CHECK_EQUAL(mult, 10080);

    mult = granularityMultiplier(YEARS, YEARS);
    BOOST_CHECK_EQUAL(mult, 1);

    mult = granularityMultiplier(YEARS, MONTHS);
    BOOST_CHECK_EQUAL(mult, 12);
}
#endif

#if 1
/* Ensure that operators + and += works well for TimePeriod */
BOOST_AUTO_TEST_CASE(time_period_op_plus_equal)
{
    /* same unit */
    {
        TimePeriod period1("2m");
        TimePeriod period2("5m");

        TimePeriod total = period1 + period2;

        BOOST_CHECK_EQUAL(total.granularity, MINUTES);
        BOOST_CHECK_EQUAL(total.number, 7);
        BOOST_CHECK_EQUAL(total.interval, 420);
    }

    /* distinct compatible units */
    {
        TimePeriod period1("1h");
        TimePeriod period2("2s");

        TimePeriod total = period1 + period2;

        BOOST_CHECK_EQUAL(total.granularity, SECONDS);
        BOOST_CHECK_EQUAL(total.number, 3602);
        BOOST_CHECK_EQUAL(total.interval, 3602);

        /* operator += */
        period1 += period2;

        BOOST_CHECK_EQUAL(period1.granularity, SECONDS);
        BOOST_CHECK_EQUAL(period1.number, 3602);
        BOOST_CHECK_EQUAL(period1.interval, 3602);
    }

    /* same as above, in reverse order */
    {
        TimePeriod period1("2s");
        TimePeriod period2("1h");

        TimePeriod total = period1 + period2;

        BOOST_CHECK_EQUAL(total.granularity, SECONDS);
        BOOST_CHECK_EQUAL(total.number, 3602);
        BOOST_CHECK_EQUAL(total.interval, 3602);

        /* operator += */
        period1 += period2;

        BOOST_CHECK_EQUAL(period1.granularity, SECONDS);
        BOOST_CHECK_EQUAL(period1.number, 3602);
        BOOST_CHECK_EQUAL(period1.interval, 3602);
    }

    /* incompatible units */
    {
        TimePeriod yearly;
        yearly.granularity = YEARS;
        yearly.number = 1;
        yearly.interval = -1; // years do not have a fixed set of seconds
        TimePeriod minutely("2m");

        JML_TRACE_EXCEPTIONS(false);
        BOOST_CHECK_THROW(yearly + minutely, ML::Exception);
    }

    {
        TimePeriod t;

        t += "1s";
        BOOST_CHECK_EQUAL(t.granularity, SECONDS);
        BOOST_CHECK_EQUAL(t.number, 1);
        BOOST_CHECK_EQUAL(t.interval, 1);
    }
}
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tdoc_content.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-05 10:40:51 $
 *
 *  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): Kai Sommerfeld ( kso@sun.com )
 *
 *
 ************************************************************************/

#ifndef INCLUDED_TDOC_CONTENT_HXX
#define INCLUDED_TDOC_CONTENT_HXX

#ifndef _UCBHELPER_CONTENTHELPER_HXX
#include <ucbhelper/contenthelper.hxx>
#endif

#ifndef _COM_SUN_STAR_TASK_DOCUMENTPASSWORDREQUEST_HPP_
#include <com/sun/star/task/DocumentPasswordRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTCREATOR_HPP_
#include <com/sun/star/ucb/XContentCreator.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandFailedException.hpp>
#endif

#ifndef INCLUDED_TDOC_PROVIDER_HXX
#include "tdoc_provider.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace sdbc  { class XRow; }
    namespace io    { class XInputStream; class XOutputStream; }
    namespace beans { struct PropertyValue; }
    namespace ucb   { struct OpenCommandArgument2; struct TransferInfo; }
} } }

namespace tdoc_ucp
{

//=========================================================================

#define TDOC_ROOT_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsRootContent"
#define TDOC_DOCUMENT_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsDocumentContent"
#define TDOC_FOLDER_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsFolderContent"
#define TDOC_STREAM_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsStreamContent"

//=========================================================================

enum ContentType { STREAM, FOLDER, DOCUMENT, ROOT };

class ContentProperties
{
public:
    ContentProperties()
    {}

    ContentProperties( const ContentType & rType, const rtl::OUString & rTitle )
    : m_eType( rType ),
      m_aContentType( rType == STREAM
        ? rtl::OUString::createFromAscii( TDOC_STREAM_CONTENT_TYPE )
        : rType == FOLDER
            ? rtl::OUString::createFromAscii( TDOC_FOLDER_CONTENT_TYPE )
            : rType == DOCUMENT
                ? rtl::OUString::createFromAscii( TDOC_DOCUMENT_CONTENT_TYPE )
                : rtl::OUString::createFromAscii( TDOC_ROOT_CONTENT_TYPE ) ),
      m_aTitle( rTitle )
    {}

    ContentType getType() const { return m_eType; }

    // Properties

    const rtl::OUString & getContentType() const { return m_aContentType; }

    bool getIsFolder()   const { return m_eType > STREAM; }
    bool getIsDocument() const { return !getIsFolder(); }

    const rtl::OUString & getTitle() const { return m_aTitle; }
    void setTitle( const rtl::OUString & rTitle ) { m_aTitle = rTitle; }

private:
    ContentType   m_eType;
    rtl::OUString m_aContentType;
    rtl::OUString m_aTitle;
};

//=========================================================================

class Content : public ::ucb::ContentImplHelper,
                public com::sun::star::ucb::XContentCreator
{
    enum ContentState { TRANSIENT,  // created via createNewContent,
                                       // but did not process "insert" yet
                        PERSISTENT, // processed "insert"
                        DEAD        // processed "delete" / document was closed
                      };

    ContentProperties m_aProps;
    ContentState      m_eState;
    ContentProvider*  m_pProvider;

private:
    Content( const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
             ContentProvider* pProvider,
             const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier,
            const ContentProperties & rProps );
    Content( const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
             ContentProvider* pProvider,
             const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier,
             const com::sun::star::ucb::ContentInfo& Info );

    virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property >
    getProperties( const com::sun::star::uno::Reference<
                    com::sun::star::ucb::XCommandEnvironment > & xEnv );
    virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo >
    getCommands( const com::sun::star::uno::Reference<
                    com::sun::star::ucb::XCommandEnvironment > & xEnv );
    virtual ::rtl::OUString getParentURL();

    bool isContentCreator();

    static bool hasData( ContentProvider* pProvider, const Uri & rUri );
    bool hasData( const Uri & rUri ) { return hasData( m_pProvider, rUri ); }

    static bool loadData( ContentProvider* pProvider,
                          const Uri & rUri,
                          ContentProperties& rProps );
    bool storeData( const com::sun::star::uno::Reference<
                        com::sun::star::io::XInputStream >& xData,
                    const com::sun::star::uno::Reference<
                        com::sun::star::ucb::XCommandEnvironment >& xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );
    bool renameData( const com::sun::star::uno::Reference<
                        com::sun::star::ucb::XContentIdentifier >& xOldId,
                     const com::sun::star::uno::Reference<
                        com::sun::star::ucb::XContentIdentifier >& xNewId );
    bool removeData();

    bool copyData( const Uri & rSourceUri );

    ::com::sun::star::uno::Reference<
        ::com::sun::star::ucb::XContentIdentifier >
    makeNewIdentifier( const rtl::OUString& rTitle );

    typedef rtl::Reference< Content > ContentRef;
    typedef std::list< ContentRef > ContentRefList;
    void queryChildren( ContentRefList& rChildren );

    sal_Bool exchangeIdentity(
                const ::com::sun::star::uno::Reference<
                        ::com::sun::star::ucb::XContentIdentifier >& xNewId );

    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
    getPropertyValues( const ::com::sun::star::uno::Sequence<
                             ::com::sun::star::beans::Property >& rProperties );
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
    setPropertyValues(
            const ::com::sun::star::uno::Sequence<
                    ::com::sun::star::beans::PropertyValue >& rValues,
            const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    com::sun::star::uno::Any
    open( const ::com::sun::star::ucb::OpenCommandArgument2& rArg,
          const ::com::sun::star::uno::Reference<
            ::com::sun::star::ucb::XCommandEnvironment >& xEnv )
        throw( ::com::sun::star::uno::Exception );

    void insert( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::io::XInputStream >& xData,
                 sal_Int32 nNameClashResolve,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    void destroy( sal_Bool bDeletePhysical,
                  const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo,
                   const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
    getPropertyValues( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,
                       const ::com::sun::star::uno::Sequence<
                        ::com::sun::star::beans::Property >& rProperties,
                       const ContentProperties& rData,
                       ContentProvider* pProvider,
                       const ::rtl::OUString& rContentId );

    static bool commitStorage(
        const com::sun::star::uno::Reference<
            com::sun::star::embed::XStorage > & xStorage );

    static bool closeOutputStream(
        const com::sun::star::uno::Reference<
            com::sun::star::io::XOutputStream > & xOut );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >
    getInputStream( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::ucb::XCommandEnvironment > &
                            xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
    getTruncatedOutputStream(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );

    ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >
    queryChildContent( const rtl::OUString & rRelativeChildUri );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream >
    getStream( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );

public:
    // Create existing content. Fail, if not already exists.
    static Content* create(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            ContentProvider* pProvider,
            const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier );

    // Create new content. Fail, if already exists.
    static Content* create(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            ContentProvider* pProvider,
            const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier,
            const com::sun::star::ucb::ContentInfo& Info );

    virtual ~Content();

    // XInterface
    XINTERFACE_DECL()

    // XTypeProvider
    XTYPEPROVIDER_DECL()

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL
    getImplementationName()
        throw( ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
    getSupportedServiceNames()
        throw( ::com::sun::star::uno::RuntimeException );

    // XContent
    virtual rtl::OUString SAL_CALL
    getContentType()
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier > SAL_CALL
    getIdentifier()
        throw( com::sun::star::uno::RuntimeException );

    // XCommandProcessor
    virtual com::sun::star::uno::Any SAL_CALL
    execute( const com::sun::star::ucb::Command& aCommand,
             sal_Int32 CommandId,
             const com::sun::star::uno::Reference<
                 com::sun::star::ucb::XCommandEnvironment >& Environment )
        throw( com::sun::star::uno::Exception,
               com::sun::star::ucb::CommandAbortedException,
               com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL
    abort( sal_Int32 CommandId )
        throw( com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Additional interfaces
    //////////////////////////////////////////////////////////////////////

    // XContentCreator
    virtual com::sun::star::uno::Sequence<
                com::sun::star::ucb::ContentInfo > SAL_CALL
    queryCreatableContentsInfo()
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Reference<
                com::sun::star::ucb::XContent > SAL_CALL
    createNewContent( const com::sun::star::ucb::ContentInfo& Info )
        throw( com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Non-interface methods.
    //////////////////////////////////////////////////////////////////////

    static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
    getPropertyValues( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,
                       const ::com::sun::star::uno::Sequence<
                        ::com::sun::star::beans::Property >& rProperties,
                       ContentProvider* pProvider,
                       const ::rtl::OUString& rContentId );

    void notifyDocumentClosed();
    void notifyChildRemoved( const rtl::OUString & rRelativeChildUri );
    void notifyChildInserted( const rtl::OUString & rRelativeChildUri );

    rtl::Reference< ContentProvider > getContentProvider() const
    { return rtl::Reference< ContentProvider >( m_pProvider ); }
};

} // namespace tdoc_ucp

#endif /* !INCLUDED_TDOC_CONTENT_HXX */
<commit_msg>INTEGRATION: CWS scriptingf7 (1.3.2); FILE MERGED 2004/07/12 17:43:52 toconnor 1.3.2.3: RESYNC: (1.4-1.5); FILE MERGED 2004/06/23 08:47:19 toconnor 1.3.2.2: RESYNC: (1.3-1.4); FILE MERGED 2004/06/04 13:52:58 kso 1.3.2.1: #i29649# - Fixed impl and usage of Content::copyData(). Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
 *
 *  $RCSfile: tdoc_content.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-07-23 13:51:10 $
 *
 *  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): Kai Sommerfeld ( kso@sun.com )
 *
 *
 ************************************************************************/

#ifndef INCLUDED_TDOC_CONTENT_HXX
#define INCLUDED_TDOC_CONTENT_HXX

#ifndef _UCBHELPER_CONTENTHELPER_HXX
#include <ucbhelper/contenthelper.hxx>
#endif

#ifndef _COM_SUN_STAR_TASK_DOCUMENTPASSWORDREQUEST_HPP_
#include <com/sun/star/task/DocumentPasswordRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTCREATOR_HPP_
#include <com/sun/star/ucb/XContentCreator.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_
#include <com/sun/star/ucb/CommandFailedException.hpp>
#endif

#ifndef INCLUDED_TDOC_PROVIDER_HXX
#include "tdoc_provider.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace sdbc  { class XRow; }
    namespace io    { class XInputStream; class XOutputStream; }
    namespace beans { struct PropertyValue; }
    namespace ucb   { struct OpenCommandArgument2; struct TransferInfo; }
} } }

namespace tdoc_ucp
{

//=========================================================================

#define TDOC_ROOT_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsRootContent"
#define TDOC_DOCUMENT_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsDocumentContent"
#define TDOC_FOLDER_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsFolderContent"
#define TDOC_STREAM_CONTENT_SERVICE_NAME \
                "com.sun.star.ucb.TransientDocumentsStreamContent"

//=========================================================================

enum ContentType { STREAM, FOLDER, DOCUMENT, ROOT };

class ContentProperties
{
public:
    ContentProperties()
    {}

    ContentProperties( const ContentType & rType, const rtl::OUString & rTitle )
    : m_eType( rType ),
      m_aContentType( rType == STREAM
        ? rtl::OUString::createFromAscii( TDOC_STREAM_CONTENT_TYPE )
        : rType == FOLDER
            ? rtl::OUString::createFromAscii( TDOC_FOLDER_CONTENT_TYPE )
            : rType == DOCUMENT
                ? rtl::OUString::createFromAscii( TDOC_DOCUMENT_CONTENT_TYPE )
                : rtl::OUString::createFromAscii( TDOC_ROOT_CONTENT_TYPE ) ),
      m_aTitle( rTitle )
    {}

    ContentType getType() const { return m_eType; }

    // Properties

    const rtl::OUString & getContentType() const { return m_aContentType; }

    bool getIsFolder()   const { return m_eType > STREAM; }
    bool getIsDocument() const { return !getIsFolder(); }

    const rtl::OUString & getTitle() const { return m_aTitle; }
    void setTitle( const rtl::OUString & rTitle ) { m_aTitle = rTitle; }

private:
    ContentType   m_eType;
    rtl::OUString m_aContentType;
    rtl::OUString m_aTitle;
};

//=========================================================================

class Content : public ::ucb::ContentImplHelper,
                public com::sun::star::ucb::XContentCreator
{
    enum ContentState { TRANSIENT,  // created via createNewContent,
                                       // but did not process "insert" yet
                        PERSISTENT, // processed "insert"
                        DEAD        // processed "delete" / document was closed
                      };

    ContentProperties m_aProps;
    ContentState      m_eState;
    ContentProvider*  m_pProvider;

private:
    Content( const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
             ContentProvider* pProvider,
             const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier,
            const ContentProperties & rProps );
    Content( const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
             ContentProvider* pProvider,
             const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier,
             const com::sun::star::ucb::ContentInfo& Info );

    virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property >
    getProperties( const com::sun::star::uno::Reference<
                    com::sun::star::ucb::XCommandEnvironment > & xEnv );
    virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo >
    getCommands( const com::sun::star::uno::Reference<
                    com::sun::star::ucb::XCommandEnvironment > & xEnv );
    virtual ::rtl::OUString getParentURL();

    bool isContentCreator();

    static bool hasData( ContentProvider* pProvider, const Uri & rUri );
    bool hasData( const Uri & rUri ) { return hasData( m_pProvider, rUri ); }

    static bool loadData( ContentProvider* pProvider,
                          const Uri & rUri,
                          ContentProperties& rProps );
    bool storeData( const com::sun::star::uno::Reference<
                        com::sun::star::io::XInputStream >& xData,
                    const com::sun::star::uno::Reference<
                        com::sun::star::ucb::XCommandEnvironment >& xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );
    bool renameData( const com::sun::star::uno::Reference<
                        com::sun::star::ucb::XContentIdentifier >& xOldId,
                     const com::sun::star::uno::Reference<
                        com::sun::star::ucb::XContentIdentifier >& xNewId );
    bool removeData();

    bool copyData( const Uri & rSourceUri, const rtl::OUString & rNewName );

    ::com::sun::star::uno::Reference<
        ::com::sun::star::ucb::XContentIdentifier >
    makeNewIdentifier( const rtl::OUString& rTitle );

    typedef rtl::Reference< Content > ContentRef;
    typedef std::list< ContentRef > ContentRefList;
    void queryChildren( ContentRefList& rChildren );

    sal_Bool exchangeIdentity(
                const ::com::sun::star::uno::Reference<
                        ::com::sun::star::ucb::XContentIdentifier >& xNewId );

    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
    getPropertyValues( const ::com::sun::star::uno::Sequence<
                             ::com::sun::star::beans::Property >& rProperties );
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >
    setPropertyValues(
            const ::com::sun::star::uno::Sequence<
                    ::com::sun::star::beans::PropertyValue >& rValues,
            const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    com::sun::star::uno::Any
    open( const ::com::sun::star::ucb::OpenCommandArgument2& rArg,
          const ::com::sun::star::uno::Reference<
            ::com::sun::star::ucb::XCommandEnvironment >& xEnv )
        throw( ::com::sun::star::uno::Exception );

    void insert( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::io::XInputStream >& xData,
                 sal_Int32 nNameClashResolve,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    void destroy( sal_Bool bDeletePhysical,
                  const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo,
                   const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
    getPropertyValues( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,
                       const ::com::sun::star::uno::Sequence<
                        ::com::sun::star::beans::Property >& rProperties,
                       const ContentProperties& rData,
                       ContentProvider* pProvider,
                       const ::rtl::OUString& rContentId );

    static bool commitStorage(
        const com::sun::star::uno::Reference<
            com::sun::star::embed::XStorage > & xStorage );

    static bool closeOutputStream(
        const com::sun::star::uno::Reference<
            com::sun::star::io::XOutputStream > & xOut );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >
    getInputStream( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::ucb::XCommandEnvironment > &
                            xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >
    getTruncatedOutputStream(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );

    ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >
    queryChildContent( const rtl::OUString & rRelativeChildUri );

    ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream >
    getStream( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XCommandEnvironment > & xEnv )
        throw ( ::com::sun::star::ucb::CommandFailedException,
                ::com::sun::star::task::DocumentPasswordRequest );

public:
    // Create existing content. Fail, if not already exists.
    static Content* create(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            ContentProvider* pProvider,
            const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier );

    // Create new content. Fail, if already exists.
    static Content* create(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            ContentProvider* pProvider,
            const com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier >& Identifier,
            const com::sun::star::ucb::ContentInfo& Info );

    virtual ~Content();

    // XInterface
    XINTERFACE_DECL()

    // XTypeProvider
    XTYPEPROVIDER_DECL()

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL
    getImplementationName()
        throw( ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
    getSupportedServiceNames()
        throw( ::com::sun::star::uno::RuntimeException );

    // XContent
    virtual rtl::OUString SAL_CALL
    getContentType()
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Reference<
                com::sun::star::ucb::XContentIdentifier > SAL_CALL
    getIdentifier()
        throw( com::sun::star::uno::RuntimeException );

    // XCommandProcessor
    virtual com::sun::star::uno::Any SAL_CALL
    execute( const com::sun::star::ucb::Command& aCommand,
             sal_Int32 CommandId,
             const com::sun::star::uno::Reference<
                 com::sun::star::ucb::XCommandEnvironment >& Environment )
        throw( com::sun::star::uno::Exception,
               com::sun::star::ucb::CommandAbortedException,
               com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL
    abort( sal_Int32 CommandId )
        throw( com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Additional interfaces
    //////////////////////////////////////////////////////////////////////

    // XContentCreator
    virtual com::sun::star::uno::Sequence<
                com::sun::star::ucb::ContentInfo > SAL_CALL
    queryCreatableContentsInfo()
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Reference<
                com::sun::star::ucb::XContent > SAL_CALL
    createNewContent( const com::sun::star::ucb::ContentInfo& Info )
        throw( com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Non-interface methods.
    //////////////////////////////////////////////////////////////////////

    static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >
    getPropertyValues( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,
                       const ::com::sun::star::uno::Sequence<
                        ::com::sun::star::beans::Property >& rProperties,
                       ContentProvider* pProvider,
                       const ::rtl::OUString& rContentId );

    void notifyDocumentClosed();
    void notifyChildRemoved( const rtl::OUString & rRelativeChildUri );
    void notifyChildInserted( const rtl::OUString & rRelativeChildUri );

    rtl::Reference< ContentProvider > getContentProvider() const
    { return rtl::Reference< ContentProvider >( m_pProvider ); }
};

} // namespace tdoc_ucp

#endif /* !INCLUDED_TDOC_CONTENT_HXX */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: textsearch.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: fme $ $Date: 2002-08-02 09:57:34 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _UNOTOOLS_TEXTSEARCH_HXX
#define _UNOTOOLS_TEXTSEARCH_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XTEXTSEARCH_HPP_
#include <com/sun/star/util/XTextSearch.hpp>
#endif

// Forward-Deklaration
class CharClass;

namespace com {
    namespace sun {
        namespace star {
            namespace util {
                struct SearchResult;
                struct SearchOptions;
            }
        }
    }
}

// ............................................................................
namespace utl
{
// ............................................................................

// SS - Klasse fuers Suchen
class SearchParam
{
public:
    enum SearchType{ SRCH_NORMAL, SRCH_REGEXP, SRCH_LEVDIST };

private:
    String sSrchStr;            // the search string
    String sReplaceStr;         // the replace string

    SearchType eSrchType;       // search normal/regular/LevDist

    int bWordOnly   : 1;        // used by normal search
    int bSrchInSel  : 1;        // search only in the selection
    int bCaseSense  : 1;        //

    // values for the "weight Levenshtein-Distance"
    int bLEV_Relaxed : 1;
    int nLEV_OtherX;
    int nLEV_ShorterY;
    int nLEV_LongerZ;

    // asian flags - used for the transliteration
    long nTransliterationFlags;

public:
    SearchParam( const String &rText,
                    SearchType eSrchType = SearchParam::SRCH_NORMAL,
                    BOOL bCaseSens = TRUE,
                    BOOL bWrdOnly = FALSE,
                    BOOL bSrchInSel = FALSE );
    SearchParam( const SearchParam& );

    const String&   GetSrchStr() const          { return sSrchStr; }
    const String&   GetReplaceStr() const       { return sReplaceStr; }
    SearchType      GetSrchType() const         { return eSrchType; }

    int             IsCaseSensitive() const     { return bCaseSense; }
    int             IsSrchInSelection() const   { return bSrchInSel; }
    int             IsSrchWordOnly() const      { return bWordOnly; }

    void SetSrchStr( const String& rStr )       { sSrchStr = rStr; }
    void SetReplaceStr( const String& rStr )    { sReplaceStr = rStr; }
    void SetSrchType( SearchType eType )        { eSrchType = eType; }

    void SetCaseSensitive( int bFlag )          { bCaseSense = bFlag; }
    void SetSrchInSelection( int bFlag )        { bSrchInSel = bFlag; }
    void SetSrchWordOnly( int bFlag )           { bWordOnly = bFlag; }

    int             IsSrchRelaxed() const       { return bLEV_Relaxed; }
    int             GetLEVOther() const         { return nLEV_OtherX; }
    int             GetLEVShorter() const       { return nLEV_ShorterY; }
    int             GetLEVLonger() const        { return nLEV_LongerZ; }

    void SetSrchRelaxed( int bFlag )            { bLEV_Relaxed = bFlag; }
    void SetLEVOther( int nValue )              { nLEV_OtherX = nValue; }
    void SetLEVShorter( int nValue )            { nLEV_ShorterY = nValue; }
    void SetLEVLonger( int nValue )             { nLEV_LongerZ = nValue; }

    long GetTransliterationFlags() const        { return nTransliterationFlags; }
    void SetTransliterationFlags( long nValue ) { nTransliterationFlags = nValue; }
};

//  Klasse zum Suchen eines Strings in einem String.
//  Unterstuetzt werden folgende Verfahren:
//      - normalen Text (Bayer/Moore)
//      - regulaere Ausdruecke
//      - gewichtete Levenshtein Distanz
//
//  Es kann Vorwaerts und Rueckwaerts gesucht werden!

class TextSearch
{
    com::sun::star::uno::Reference < com::sun::star::util::XTextSearch >
            xTextSearch;

    void Init( const SearchParam & rParam,
               const ::com::sun::star::lang::Locale& rLocale );

public:
    // rText ist der zusuchende String
    // this first two CTORs are deprecated!
    TextSearch( const SearchParam & rPara, ULONG nLanguage );
    TextSearch( const SearchParam & rPara, const CharClass& rCClass );

    TextSearch( const ::com::sun::star::util::SearchOptions& rPara );
    ~TextSearch();

    /* search in the (selected) text the search string:
        rScrTxt - the text, in in which we search
        pStart  - start position for the saerch
        pEnde   - end postion for the search

        RETURN values   ==  TRUE: something is found
                        - pStart start pos of the found text,
                        - pStart end pos of the found text,
                        - pSrchResult - the search reult with all found
                             positons. Is only filled with more positions
                             if the regular expression handles goups.

                        == FALSE: nothing found, pStart,pEnde unchanged.

        Definitions: start pos always inclusive, end pos always exclusive!
                     The position must always in the right direction!
                    search forward: start <= end
                    search backward: end <= start
    */
    int SearchFrwrd( const String &rStr,
                    xub_StrLen* pStart, xub_StrLen* pEnde,
                    ::com::sun::star::util::SearchResult* pSrchResult = 0 );
    int SearchBkwrd( const String &rStr,
                    xub_StrLen* pStart, xub_StrLen* pEnde,
                    ::com::sun::star::util::SearchResult* pSrchResult = 0 );

    void SetLocale( const ::com::sun::star::util::SearchOptions& rOpt,
                    const ::com::sun::star::lang::Locale& rLocale );
};

// ............................................................................
}   // namespace utl
// ............................................................................

#endif

<commit_msg>INTEGRATION: CWS visibility03 (1.5.188); FILE MERGED 2005/02/28 04:33:54 mnicel 1.5.188.1: Issue number:  40092 Part of visibility work<commit_after>/*************************************************************************
 *
 *  $RCSfile: textsearch.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 12:28:20 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef INCLUDED_UNOTOOLSDLLAPI_H
#include "unotools/unotoolsdllapi.h"
#endif

#ifndef _UNOTOOLS_TEXTSEARCH_HXX
#define _UNOTOOLS_TEXTSEARCH_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XTEXTSEARCH_HPP_
#include <com/sun/star/util/XTextSearch.hpp>
#endif

// Forward-Deklaration
class CharClass;

namespace com {
    namespace sun {
        namespace star {
            namespace util {
                struct SearchResult;
                struct SearchOptions;
            }
        }
    }
}

// ............................................................................
namespace utl
{
// ............................................................................

// SS - Klasse fuers Suchen
class UNOTOOLS_DLLPUBLIC SearchParam
{
public:
    enum SearchType{ SRCH_NORMAL, SRCH_REGEXP, SRCH_LEVDIST };

private:
    String sSrchStr;            // the search string
    String sReplaceStr;         // the replace string

    SearchType eSrchType;       // search normal/regular/LevDist

    int bWordOnly   : 1;        // used by normal search
    int bSrchInSel  : 1;        // search only in the selection
    int bCaseSense  : 1;        //

    // values for the "weight Levenshtein-Distance"
    int bLEV_Relaxed : 1;
    int nLEV_OtherX;
    int nLEV_ShorterY;
    int nLEV_LongerZ;

    // asian flags - used for the transliteration
    long nTransliterationFlags;

public:
    SearchParam( const String &rText,
                    SearchType eSrchType = SearchParam::SRCH_NORMAL,
                    BOOL bCaseSens = TRUE,
                    BOOL bWrdOnly = FALSE,
                    BOOL bSrchInSel = FALSE );
    SearchParam( const SearchParam& );

    const String&   GetSrchStr() const          { return sSrchStr; }
    const String&   GetReplaceStr() const       { return sReplaceStr; }
    SearchType      GetSrchType() const         { return eSrchType; }

    int             IsCaseSensitive() const     { return bCaseSense; }
    int             IsSrchInSelection() const   { return bSrchInSel; }
    int             IsSrchWordOnly() const      { return bWordOnly; }

    void SetSrchStr( const String& rStr )       { sSrchStr = rStr; }
    void SetReplaceStr( const String& rStr )    { sReplaceStr = rStr; }
    void SetSrchType( SearchType eType )        { eSrchType = eType; }

    void SetCaseSensitive( int bFlag )          { bCaseSense = bFlag; }
    void SetSrchInSelection( int bFlag )        { bSrchInSel = bFlag; }
    void SetSrchWordOnly( int bFlag )           { bWordOnly = bFlag; }

    int             IsSrchRelaxed() const       { return bLEV_Relaxed; }
    int             GetLEVOther() const         { return nLEV_OtherX; }
    int             GetLEVShorter() const       { return nLEV_ShorterY; }
    int             GetLEVLonger() const        { return nLEV_LongerZ; }

    void SetSrchRelaxed( int bFlag )            { bLEV_Relaxed = bFlag; }
    void SetLEVOther( int nValue )              { nLEV_OtherX = nValue; }
    void SetLEVShorter( int nValue )            { nLEV_ShorterY = nValue; }
    void SetLEVLonger( int nValue )             { nLEV_LongerZ = nValue; }

    long GetTransliterationFlags() const        { return nTransliterationFlags; }
    void SetTransliterationFlags( long nValue ) { nTransliterationFlags = nValue; }
};

//  Klasse zum Suchen eines Strings in einem String.
//  Unterstuetzt werden folgende Verfahren:
//      - normalen Text (Bayer/Moore)
//      - regulaere Ausdruecke
//      - gewichtete Levenshtein Distanz
//
//  Es kann Vorwaerts und Rueckwaerts gesucht werden!

class UNOTOOLS_DLLPUBLIC TextSearch
{
    com::sun::star::uno::Reference < com::sun::star::util::XTextSearch >
            xTextSearch;

    void Init( const SearchParam & rParam,
               const ::com::sun::star::lang::Locale& rLocale );

public:
    // rText ist der zusuchende String
    // this first two CTORs are deprecated!
    TextSearch( const SearchParam & rPara, ULONG nLanguage );
    TextSearch( const SearchParam & rPara, const CharClass& rCClass );

    TextSearch( const ::com::sun::star::util::SearchOptions& rPara );
    ~TextSearch();

    /* search in the (selected) text the search string:
        rScrTxt - the text, in in which we search
        pStart  - start position for the saerch
        pEnde   - end postion for the search

        RETURN values   ==  TRUE: something is found
                        - pStart start pos of the found text,
                        - pStart end pos of the found text,
                        - pSrchResult - the search reult with all found
                             positons. Is only filled with more positions
                             if the regular expression handles goups.

                        == FALSE: nothing found, pStart,pEnde unchanged.

        Definitions: start pos always inclusive, end pos always exclusive!
                     The position must always in the right direction!
                    search forward: start <= end
                    search backward: end <= start
    */
    int SearchFrwrd( const String &rStr,
                    xub_StrLen* pStart, xub_StrLen* pEnde,
                    ::com::sun::star::util::SearchResult* pSrchResult = 0 );
    int SearchBkwrd( const String &rStr,
                    xub_StrLen* pStart, xub_StrLen* pEnde,
                    ::com::sun::star::util::SearchResult* pSrchResult = 0 );

    void SetLocale( const ::com::sun::star::util::SearchOptions& rOpt,
                    const ::com::sun::star::lang::Locale& rLocale );
};

// ............................................................................
}   // namespace utl
// ............................................................................

#endif

<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <Eigen/Polynomials>
#include <iostream>

using namespace std;

template<int Size>
struct ei_increment_if_fixed_size
{
  enum {
    ret = (Size == Dynamic) ? Dynamic : Size+1
  };
};

template<typename _Scalar, int _Deg>
void realRoots_to_monicPolynomial_test(int deg)
{
  typedef ei_increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  PolynomialType pols(deg+1);
  EvalRootsType roots = EvalRootsType::Random(deg);
  realRoots_to_monicPolynomial( roots, pols );

  EvalRootsType evr( deg );
  for( int i=0; i<roots.size(); ++i ){
    evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }

  bool evalToZero = evr.isZero( test_precision<_Scalar>() );
  if( !evalToZero ){
    cerr << evr.transpose() << endl; }
  VERIFY( evalToZero );
}

template<typename _Scalar> void realRoots_to_monicPolynomial_scalar()
{
  CALL_SUBTEST_2( (realRoots_to_monicPolynomial_test<_Scalar,2>(2)) );
  CALL_SUBTEST_3( (realRoots_to_monicPolynomial_test<_Scalar,3>(3)) );
  CALL_SUBTEST_4( (realRoots_to_monicPolynomial_test<_Scalar,4>(4)) );
  CALL_SUBTEST_5( (realRoots_to_monicPolynomial_test<_Scalar,5>(5)) );
  CALL_SUBTEST_6( (realRoots_to_monicPolynomial_test<_Scalar,6>(6)) );
  CALL_SUBTEST_7( (realRoots_to_monicPolynomial_test<_Scalar,7>(7)) );
  CALL_SUBTEST_8( (realRoots_to_monicPolynomial_test<_Scalar,17>(17)) );

  int deg = ei_random<int>(18,26);
  CALL_SUBTEST_9( (realRoots_to_monicPolynomial_test<_Scalar,Dynamic>(deg)) );
}

template<typename _Scalar, int _Deg>
void CauchyBounds(int deg)
{
  typedef ei_increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  PolynomialType pols(deg+1);
  EvalRootsType roots = EvalRootsType::Random(deg);
  realRoots_to_monicPolynomial( roots, pols );
  _Scalar M = cauchy_max_bound( pols );
  _Scalar m = cauchy_min_bound( pols );
  _Scalar Max = roots.array().abs().maxCoeff();
  _Scalar min = roots.array().abs().minCoeff();
  bool eval = (M >= Max) && (m <= min);
  if( !eval )
  {
    cerr << "Roots: " << roots << endl;
    cerr << "Bounds: (" << m << ", " << M << ")" << endl;
    cerr << "Min,Max: (" << min << ", " << Max << ")" << endl;
  }
  VERIFY( eval );
}

template<typename _Scalar> void CauchyBounds_scalar()
{
  CALL_SUBTEST_2( (CauchyBounds<_Scalar,2>(2)) );
  CALL_SUBTEST_3( (CauchyBounds<_Scalar,3>(3)) );
  CALL_SUBTEST_4( (CauchyBounds<_Scalar,4>(4)) );
  CALL_SUBTEST_5( (CauchyBounds<_Scalar,5>(5)) );
  CALL_SUBTEST_6( (CauchyBounds<_Scalar,6>(6)) );
  CALL_SUBTEST_7( (CauchyBounds<_Scalar,7>(7)) );
  CALL_SUBTEST_8( (CauchyBounds<_Scalar,17>(17)) );

  int deg = ei_random<int>(18,26);
  CALL_SUBTEST_9( (CauchyBounds<_Scalar,Dynamic>(deg)) );
}

void test_polynomialutils()
{
  for(int i = 0; i < g_repeat; i++)
  {
    realRoots_to_monicPolynomial_scalar<double>();
    realRoots_to_monicPolynomial_scalar<float>();
    CauchyBounds_scalar<double>();
    CauchyBounds_scalar<float>();
  }
}
<commit_msg>Fix wrong header and warnings in polynomialutils.cpp<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>

using namespace std;

template<int Size>
struct ei_increment_if_fixed_size
{
  enum {
    ret = (Size == Dynamic) ? Dynamic : Size+1
  };
};

template<typename _Scalar, int _Deg>
void realRoots_to_monicPolynomial_test(int deg)
{
  typedef ei_increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  PolynomialType pols(deg+1);
  EvalRootsType roots = EvalRootsType::Random(deg);
  roots_to_monicPolynomial( roots, pols );

  EvalRootsType evr( deg );
  for( int i=0; i<roots.size(); ++i ){
    evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }

  bool evalToZero = evr.isZero( test_precision<_Scalar>() );
  if( !evalToZero ){
    cerr << evr.transpose() << endl; }
  VERIFY( evalToZero );
}

template<typename _Scalar> void realRoots_to_monicPolynomial_scalar()
{
  CALL_SUBTEST_2( (realRoots_to_monicPolynomial_test<_Scalar,2>(2)) );
  CALL_SUBTEST_3( (realRoots_to_monicPolynomial_test<_Scalar,3>(3)) );
  CALL_SUBTEST_4( (realRoots_to_monicPolynomial_test<_Scalar,4>(4)) );
  CALL_SUBTEST_5( (realRoots_to_monicPolynomial_test<_Scalar,5>(5)) );
  CALL_SUBTEST_6( (realRoots_to_monicPolynomial_test<_Scalar,6>(6)) );
  CALL_SUBTEST_7( (realRoots_to_monicPolynomial_test<_Scalar,7>(7)) );
  CALL_SUBTEST_8( (realRoots_to_monicPolynomial_test<_Scalar,17>(17)) );

  CALL_SUBTEST_9( (realRoots_to_monicPolynomial_test<_Scalar,Dynamic>(
          ei_random<int>(18,26) )) );
}

template<typename _Scalar, int _Deg>
void CauchyBounds(int deg)
{
  typedef ei_increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  PolynomialType pols(deg+1);
  EvalRootsType roots = EvalRootsType::Random(deg);
  roots_to_monicPolynomial( roots, pols );
  _Scalar M = cauchy_max_bound( pols );
  _Scalar m = cauchy_min_bound( pols );
  _Scalar Max = roots.array().abs().maxCoeff();
  _Scalar min = roots.array().abs().minCoeff();
  bool eval = (M >= Max) && (m <= min);
  if( !eval )
  {
    cerr << "Roots: " << roots << endl;
    cerr << "Bounds: (" << m << ", " << M << ")" << endl;
    cerr << "Min,Max: (" << min << ", " << Max << ")" << endl;
  }
  VERIFY( eval );
}

template<typename _Scalar> void CauchyBounds_scalar()
{
  CALL_SUBTEST_2( (CauchyBounds<_Scalar,2>(2)) );
  CALL_SUBTEST_3( (CauchyBounds<_Scalar,3>(3)) );
  CALL_SUBTEST_4( (CauchyBounds<_Scalar,4>(4)) );
  CALL_SUBTEST_5( (CauchyBounds<_Scalar,5>(5)) );
  CALL_SUBTEST_6( (CauchyBounds<_Scalar,6>(6)) );
  CALL_SUBTEST_7( (CauchyBounds<_Scalar,7>(7)) );
  CALL_SUBTEST_8( (CauchyBounds<_Scalar,17>(17)) );

  CALL_SUBTEST_9( (CauchyBounds<_Scalar,Dynamic>(
          ei_random<int>(18,26) )) );
}

void test_polynomialutils()
{
  for(int i = 0; i < g_repeat; i++)
  {
    realRoots_to_monicPolynomial_scalar<double>();
    realRoots_to_monicPolynomial_scalar<float>();
    CauchyBounds_scalar<double>();
    CauchyBounds_scalar<float>();
  }
}
<|endoftext|>


<commit_before>#include "LaplaceRand.h"

LaplaceRand::LaplaceRand(double location, double scale)
{
    setLocation(location);
    setScale(scale);
}

std::string LaplaceRand::name()
{
    return "Laplace(" + toStringWithPrecision(getLocation()) + ", " + toStringWithPrecision(getScale()) + ")";
}

void LaplaceRand::setLocation(double location)
{
    mu = location;
}

void LaplaceRand::setScale(double scale)
{
    b = std::max(scale, MIN_POSITIVE);
    bInv = 1.0 / b;
}

double LaplaceRand::f(double x) const
{
    double y = -std::fabs(x - mu);
    y *= bInv;
    y = std::exp(y);
    y *= bInv;
    return .5 * y;
}

double LaplaceRand::F(double x) const
{
    double y = x - mu;
    y *= bInv;
    if (x < mu)
        return .5 * std::exp(y);
    y = -.5 * std::exp(-y);
    return y + 1;
}

double LaplaceRand::variate() const
{
    return LaplaceRand::variate(mu, b);
}

double LaplaceRand::variate(double location, double scale)
{
    double e = scale * ExponentialRand::standardVariate();
    return location + (((signed)RandGenerator::variate() > 0) ? e : -e);
}

std::complex<double> LaplaceRand::CF(double t) const
{
    double bt = b * t;
    double denominator = 1 + bt * bt;
    return std::complex<double>(std::cos(t) / denominator, std::sin(t) / denominator);
}

double LaplaceRand::Median() const
{
    return mu;
}

double LaplaceRand::Mode() const
{
    return mu;
}

double LaplaceRand::Skewness() const
{
    return 0.0;
}

double LaplaceRand::ExcessKurtosis() const
{
    return 3.0;
}

bool LaplaceRand::fitToData(const QVector<double> &sample)
{
    if (sample.size() == 0)
        return false;

    /// Calculate median
    /// we use root-finding algorithm for median search
    /// but note, that it is better to use median-for-median algorithm
    double median = 0.0;
    double min = sample[0], max = min;
    for (double var : sample) {
        min = std::min(var, min);
        max = std::max(var, max);
    }

    if (!RandMath::findRoot([sample] (double med)
    {
        /// sum of sign(x) - derivative of sum of abs(x)
        double x = 0;
        for (double var : sample) {
            if (var > med)
                ++x;
            else if (var < med)
                --x;
        }
        return x;
    },
    min, max, median
    ))
        return false;

    /// Calculate scale
    double deviation = 0.0;
    for (double var : sample) {
        deviation += std::fabs(var - median);
    }
    deviation /= sample.size();

    setLocation(median);
    setScale(deviation);
    return true;
}

<commit_msg>Update LaplaceRand.cpp<commit_after>#include "LaplaceRand.h"

LaplaceRand::LaplaceRand(double location, double scale)
{
    setLocation(location);
    setScale(scale);
}

std::string LaplaceRand::name()
{
    return "Laplace(" + toStringWithPrecision(getLocation()) + ", " + toStringWithPrecision(getScale()) + ")";
}

void LaplaceRand::setLocation(double location)
{
    mu = location;
}

void LaplaceRand::setScale(double scale)
{
    b = scale;
    if (b <= 0)
        b = MIN_POSITIVE;
    bInv = 1.0 / b;
}

double LaplaceRand::f(double x) const
{
    double y = -std::fabs(x - mu);
    y *= bInv;
    y = std::exp(y);
    y *= bInv;
    return .5 * y;
}

double LaplaceRand::F(double x) const
{
    double y = x - mu;
    y *= bInv;
    if (x < mu)
        return .5 * std::exp(y);
    y = -.5 * std::exp(-y);
    return y + 1;
}

double LaplaceRand::variate() const
{
    return LaplaceRand::variate(mu, b);
}

double LaplaceRand::variate(double location, double scale)
{
    double e = scale * ExponentialRand::standardVariate();
    return location + (((signed)RandGenerator::variate() > 0) ? e : -e);
}

std::complex<double> LaplaceRand::CF(double t) const
{
    double bt = b * t;
    double denominator = 1 + bt * bt;
    return std::complex<double>(std::cos(t) / denominator, std::sin(t) / denominator);
}

double LaplaceRand::Median() const
{
    return mu;
}

double LaplaceRand::Mode() const
{
    return mu;
}

double LaplaceRand::Skewness() const
{
    return 0.0;
}

double LaplaceRand::ExcessKurtosis() const
{
    return 3.0;
}

bool LaplaceRand::fitToData(const QVector<double> &sample)
{
    if (sample.size() == 0)
        return false;

    /// Calculate median
    /// we use root-finding algorithm for median search
    /// but note, that it is better to use median-for-median algorithm
    double median = 0.0;
    double min = sample[0], max = min;
    for (double var : sample) {
        min = std::min(var, min);
        max = std::max(var, max);
    }

    if (!RandMath::findRoot([sample] (double med)
    {
        /// sum of sign(x) - derivative of sum of abs(x)
        double x = 0;
        for (double var : sample) {
            if (var > med)
                ++x;
            else if (var < med)
                --x;
        }
        return x;
    },
    min, max, median
    ))
        return false;

    /// Calculate scale
    double deviation = 0.0;
    for (double var : sample) {
        deviation += std::fabs(var - median);
    }
    deviation /= sample.size();

    setLocation(median);
    setScale(deviation);
    return true;
}

<|endoftext|>