text stringlengths 54 60.6k |
|---|
<commit_before>#ifndef TOML11_REGION_H
#define TOML11_REGION_H
#include "exception.hpp"
#include <memory>
#include <vector>
#include <algorithm>
#include <initializer_list>
#include <iterator>
#include <iostream>
namespace toml
{
namespace detail
{
// helper function to avoid std::string(0, 'c')
template<typename Iterator>
std::string make_string(Iterator first, Iterator last)
{
if(first == last) {return "";}
return std::string(first, last);
}
inline std::string make_string(std::size_t len, char c)
{
if(len == 0) {return "";}
return std::string(len, c);
}
// location in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct location
{
static_assert(std::is_same<char, typename Container::value_type>::value,"");
using const_iterator = typename Container::const_iterator;
using source_ptr = std::shared_ptr<const Container>;
location(std::string name, Container cont)
: source_(std::make_shared<Container>(std::move(cont))),
source_name_(std::move(name)), iter_(source_->cbegin())
{}
location(const location&) = default;
location(location&&) = default;
location& operator=(const location&) = default;
location& operator=(location&&) = default;
~location() = default;
const_iterator& iter() noexcept {return iter_;}
const_iterator iter() const noexcept {return iter_;}
const_iterator begin() const noexcept {return source_->cbegin();}
const_iterator end() const noexcept {return source_->cend();}
source_ptr const& source() const& noexcept {return source_;}
source_ptr&& source() && noexcept {return std::move(source_);}
std::string const& name() const noexcept {return source_name_;}
private:
source_ptr source_;
std::string source_name_;
const_iterator iter_;
};
// region in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// combinators returns this.
// it will be used to generate better error messages.
struct region_base
{
region_base() = default;
virtual ~region_base() = default;
region_base(const region_base&) = default;
region_base(region_base&& ) = default;
region_base& operator=(const region_base&) = default;
region_base& operator=(region_base&& ) = default;
virtual bool is_ok() const noexcept {return false;}
virtual std::string str() const {return std::string("unknown region");}
virtual std::string name() const {return std::string("unknown file");}
virtual std::string line() const {return std::string("unknown line");}
virtual std::string line_num() const {return std::string("?");}
virtual std::size_t before() const noexcept {return 0;}
virtual std::size_t size() const noexcept {return 0;}
virtual std::size_t after() const noexcept {return 0;}
};
template<typename Container>
struct region final : public region_base
{
static_assert(std::is_same<char, typename Container::value_type>::value,"");
using const_iterator = typename Container::const_iterator;
using source_ptr = std::shared_ptr<const Container>;
// delete default constructor. source_ never be null.
region() = delete;
region(const location<Container>& loc)
: source_(loc.source()), source_name_(loc.name()),
first_(loc.iter()), last_(loc.iter())
{}
region(location<Container>&& loc)
: source_(loc.source()), source_name_(loc.name()),
first_(loc.iter()), last_(loc.iter())
{}
region(const location<Container>& loc, const_iterator f, const_iterator l)
: source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)
{}
region(location<Container>&& loc, const_iterator f, const_iterator l)
: source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)
{}
region(const region&) = default;
region(region&&) = default;
region& operator=(const region&) = default;
region& operator=(region&&) = default;
~region() = default;
region& operator+=(const region& other)
{
if(this->begin() != other.begin() || this->end() != other.end() ||
this->last_ != other.first_)
{
throw internal_error("invalid region concatenation");
}
this->last_ = other.last_;
return *this;
}
bool is_ok() const noexcept override {return static_cast<bool>(source_);}
std::string str() const override {return make_string(first_, last_);}
std::string line() const override
{
if(this->contain_newline())
{
return make_string(this->line_begin(),
std::find(this->line_begin(), this->last(), '\n'));
}
return make_string(this->line_begin(), this->line_end());
}
std::string line_num() const override
{
return std::to_string(1 + std::count(this->begin(), this->first(), '\n'));
}
std::size_t size() const noexcept override
{
return std::distance(first_, last_);
}
std::size_t before() const noexcept override
{
return std::distance(this->line_begin(), this->first());
}
std::size_t after() const noexcept override
{
return std::distance(this->last(), this->line_end());
}
bool contain_newline() const noexcept
{
return std::find(this->first(), this->last(), '\n') != this->last();
}
const_iterator line_begin() const noexcept
{
using reverse_iterator = std::reverse_iterator<const_iterator>;
return std::find(reverse_iterator(this->first()),
reverse_iterator(this->begin()), '\n').base();
}
const_iterator line_end() const noexcept
{
return std::find(this->last(), this->end(), '\n');
}
const_iterator begin() const noexcept {return source_->cbegin();}
const_iterator end() const noexcept {return source_->cend();}
const_iterator first() const noexcept {return first_;}
const_iterator last() const noexcept {return last_;}
source_ptr const& source() const& noexcept {return source_;}
source_ptr&& source() && noexcept {return std::move(source_);}
std::string name() const override {return source_name_;}
private:
source_ptr source_;
std::string source_name_;
const_iterator first_, last_;
};
// to show a better error message.
inline std::string format_underline(const std::string& message,
const region_base& reg, const std::string& comment_for_underline)
{
const auto line = reg.line();
const auto line_number = reg.line_num();
std::string retval;
retval += message;
retval += "\n --> ";
retval += reg.name();
retval += "\n ";
retval += line_number;
retval += " | ";
retval += line;
retval += '\n';
retval += make_string(line_number.size() + 1, ' ');
retval += " | ";
retval += make_string(reg.before(), ' ');
retval += make_string(reg.size(), '~');
retval += ' ';
retval += comment_for_underline;
return retval;
}
// to show a better error message.
template<typename Container>
std::string
format_underline(const std::string& message, const location<Container>& loc,
const std::string& comment_for_underline,
std::vector<std::string> helps = {})
{
using const_iterator = typename location<Container>::const_iterator;
using reverse_iterator = std::reverse_iterator<const_iterator>;
const auto line_begin = std::find(reverse_iterator(loc.iter()),
reverse_iterator(loc.begin()),
'\n').base();
const auto line_end = std::find(loc.iter(), loc.end(), '\n');
const auto line_number = std::to_string(
1 + std::count(loc.begin(), loc.iter(), '\n'));
std::string retval;
retval += message;
retval += "\n --> ";
retval += loc.name();
retval += "\n ";
retval += line_number;
retval += " | ";
retval += make_string(line_begin, line_end);
retval += '\n';
retval += make_string(line_number.size() + 1, ' ');
retval += " | ";
retval += make_string(std::distance(line_begin, loc.iter()),' ');
retval += '^';
retval += make_string(std::distance(loc.iter(), line_end), '-');
retval += ' ';
retval += comment_for_underline;
if(helps.size() != 0)
{
retval += '\n';
retval += make_string(line_number.size() + 1, ' ');
retval += " | ";
for(const auto help : helps)
{
retval += "\nHint: ";
retval += help;
}
}
return retval;
}
} // detail
} // toml
#endif// TOML11_REGION_H
<commit_msg>enable format_underline to print hint with region<commit_after>#ifndef TOML11_REGION_H
#define TOML11_REGION_H
#include "exception.hpp"
#include <memory>
#include <vector>
#include <algorithm>
#include <initializer_list>
#include <iterator>
#include <iostream>
namespace toml
{
namespace detail
{
// helper function to avoid std::string(0, 'c')
template<typename Iterator>
std::string make_string(Iterator first, Iterator last)
{
if(first == last) {return "";}
return std::string(first, last);
}
inline std::string make_string(std::size_t len, char c)
{
if(len == 0) {return "";}
return std::string(len, c);
}
// location in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// it can be used not only for resource handling, but also error message.
template<typename Container>
struct location
{
static_assert(std::is_same<char, typename Container::value_type>::value,"");
using const_iterator = typename Container::const_iterator;
using source_ptr = std::shared_ptr<const Container>;
location(std::string name, Container cont)
: source_(std::make_shared<Container>(std::move(cont))),
source_name_(std::move(name)), iter_(source_->cbegin())
{}
location(const location&) = default;
location(location&&) = default;
location& operator=(const location&) = default;
location& operator=(location&&) = default;
~location() = default;
const_iterator& iter() noexcept {return iter_;}
const_iterator iter() const noexcept {return iter_;}
const_iterator begin() const noexcept {return source_->cbegin();}
const_iterator end() const noexcept {return source_->cend();}
source_ptr const& source() const& noexcept {return source_;}
source_ptr&& source() && noexcept {return std::move(source_);}
std::string const& name() const noexcept {return source_name_;}
private:
source_ptr source_;
std::string source_name_;
const_iterator iter_;
};
// region in a container, normally in a file content.
// shared_ptr points the resource that the iter points.
// combinators returns this.
// it will be used to generate better error messages.
struct region_base
{
region_base() = default;
virtual ~region_base() = default;
region_base(const region_base&) = default;
region_base(region_base&& ) = default;
region_base& operator=(const region_base&) = default;
region_base& operator=(region_base&& ) = default;
virtual bool is_ok() const noexcept {return false;}
virtual std::string str() const {return std::string("unknown region");}
virtual std::string name() const {return std::string("unknown file");}
virtual std::string line() const {return std::string("unknown line");}
virtual std::string line_num() const {return std::string("?");}
virtual std::size_t before() const noexcept {return 0;}
virtual std::size_t size() const noexcept {return 0;}
virtual std::size_t after() const noexcept {return 0;}
};
template<typename Container>
struct region final : public region_base
{
static_assert(std::is_same<char, typename Container::value_type>::value,"");
using const_iterator = typename Container::const_iterator;
using source_ptr = std::shared_ptr<const Container>;
// delete default constructor. source_ never be null.
region() = delete;
region(const location<Container>& loc)
: source_(loc.source()), source_name_(loc.name()),
first_(loc.iter()), last_(loc.iter())
{}
region(location<Container>&& loc)
: source_(loc.source()), source_name_(loc.name()),
first_(loc.iter()), last_(loc.iter())
{}
region(const location<Container>& loc, const_iterator f, const_iterator l)
: source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)
{}
region(location<Container>&& loc, const_iterator f, const_iterator l)
: source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)
{}
region(const region&) = default;
region(region&&) = default;
region& operator=(const region&) = default;
region& operator=(region&&) = default;
~region() = default;
region& operator+=(const region& other)
{
if(this->begin() != other.begin() || this->end() != other.end() ||
this->last_ != other.first_)
{
throw internal_error("invalid region concatenation");
}
this->last_ = other.last_;
return *this;
}
bool is_ok() const noexcept override {return static_cast<bool>(source_);}
std::string str() const override {return make_string(first_, last_);}
std::string line() const override
{
if(this->contain_newline())
{
return make_string(this->line_begin(),
std::find(this->line_begin(), this->last(), '\n'));
}
return make_string(this->line_begin(), this->line_end());
}
std::string line_num() const override
{
return std::to_string(1 + std::count(this->begin(), this->first(), '\n'));
}
std::size_t size() const noexcept override
{
return std::distance(first_, last_);
}
std::size_t before() const noexcept override
{
return std::distance(this->line_begin(), this->first());
}
std::size_t after() const noexcept override
{
return std::distance(this->last(), this->line_end());
}
bool contain_newline() const noexcept
{
return std::find(this->first(), this->last(), '\n') != this->last();
}
const_iterator line_begin() const noexcept
{
using reverse_iterator = std::reverse_iterator<const_iterator>;
return std::find(reverse_iterator(this->first()),
reverse_iterator(this->begin()), '\n').base();
}
const_iterator line_end() const noexcept
{
return std::find(this->last(), this->end(), '\n');
}
const_iterator begin() const noexcept {return source_->cbegin();}
const_iterator end() const noexcept {return source_->cend();}
const_iterator first() const noexcept {return first_;}
const_iterator last() const noexcept {return last_;}
source_ptr const& source() const& noexcept {return source_;}
source_ptr&& source() && noexcept {return std::move(source_);}
std::string name() const override {return source_name_;}
private:
source_ptr source_;
std::string source_name_;
const_iterator first_, last_;
};
// to show a better error message.
inline std::string format_underline(const std::string& message,
const region_base& reg, const std::string& comment_for_underline,
std::vector<std::string> helps = {})
{
const auto line = reg.line();
const auto line_number = reg.line_num();
std::string retval;
retval += message;
retval += "\n --> ";
retval += reg.name();
retval += "\n ";
retval += line_number;
retval += " | ";
retval += line;
retval += '\n';
retval += make_string(line_number.size() + 1, ' ');
retval += " | ";
retval += make_string(reg.before(), ' ');
retval += make_string(reg.size(), '~');
retval += ' ';
retval += comment_for_underline;
if(helps.size() != 0)
{
retval += '\n';
retval += make_string(line_number.size() + 1, ' ');
retval += " | ";
for(const auto help : helps)
{
retval += "\nHint: ";
retval += help;
}
}
return retval;
}
// to show a better error message.
template<typename Container>
std::string
format_underline(const std::string& message, const location<Container>& loc,
const std::string& comment_for_underline,
std::vector<std::string> helps = {})
{
using const_iterator = typename location<Container>::const_iterator;
using reverse_iterator = std::reverse_iterator<const_iterator>;
const auto line_begin = std::find(reverse_iterator(loc.iter()),
reverse_iterator(loc.begin()),
'\n').base();
const auto line_end = std::find(loc.iter(), loc.end(), '\n');
const auto line_number = std::to_string(
1 + std::count(loc.begin(), loc.iter(), '\n'));
std::string retval;
retval += message;
retval += "\n --> ";
retval += loc.name();
retval += "\n ";
retval += line_number;
retval += " | ";
retval += make_string(line_begin, line_end);
retval += '\n';
retval += make_string(line_number.size() + 1, ' ');
retval += " | ";
retval += make_string(std::distance(line_begin, loc.iter()),' ');
retval += '^';
retval += make_string(std::distance(loc.iter(), line_end), '-');
retval += ' ';
retval += comment_for_underline;
if(helps.size() != 0)
{
retval += '\n';
retval += make_string(line_number.size() + 1, ' ');
retval += " | ";
for(const auto help : helps)
{
retval += "\nHint: ";
retval += help;
}
}
return retval;
}
} // detail
} // toml
#endif// TOML11_REGION_H
<|endoftext|> |
<commit_before><commit_msg>Proper detection of MMX and SSE support<commit_after><|endoftext|> |
<commit_before>#include "place_page_info.hpp"
#include "indexer/feature_utils.hpp"
#include "indexer/osm_editor.hpp"
#include "platform/measurement_utils.hpp"
namespace place_page
{
char const * const Info::kSubtitleSeparator = " • ";
char const * const Info::kStarSymbol = "★";
char const * const Info::kMountainSymbol = "▲";
char const * const Info::kEmptyRatingSymbol = "-";
char const * const Info::kPricingSymbol = "$";
bool Info::IsFeature() const { return m_featureID.IsValid(); }
bool Info::IsBookmark() const { return m_bac.IsValid(); }
bool Info::IsMyPosition() const { return m_isMyPosition; }
bool Info::IsSponsoredHotel() const { return m_isSponsoredHotel; }
bool Info::IsHotel() const { return m_isHotel; }
bool Info::ShouldShowAddPlace() const
{
auto const isPointOrBuilding = IsPointType() || IsBuilding();
return m_canEditOrAdd && !(IsFeature() && isPointOrBuilding);
}
bool Info::ShouldShowAddBusiness() const { return m_canEditOrAdd && IsBuilding(); }
bool Info::ShouldShowEditPlace() const
{
return m_canEditOrAdd &&
// TODO(mgsergio): Does IsFeature() imply !IsMyPosition()?
!IsMyPosition() && IsFeature();
}
bool Info::HasApiUrl() const { return !m_apiUrl.empty(); }
bool Info::HasWifi() const { return GetInternet() == osm::Internet::Wlan; }
string Info::FormatNewBookmarkName() const
{
string const title = GetTitle();
if (title.empty())
return GetLocalizedType();
return title;
}
string Info::GetTitle() const
{
if (!m_customName.empty())
return m_customName;
string name;
feature::GetReadableName(GetID(), m_name, name);
return name;
}
string Info::GetSubtitle() const
{
if (!IsFeature())
{
if (IsBookmark())
return m_bookmarkCategoryName;
return {};
}
vector<string> values;
// Bookmark category.
if (IsBookmark())
values.push_back(m_bookmarkCategoryName);
// Type.
values.push_back(GetLocalizedType());
// Cuisines.
for (string const & cuisine : GetLocalizedCuisines())
values.push_back(cuisine);
// Stars.
string const stars = FormatStars();
if (!stars.empty())
values.push_back(stars);
// Operator.
string const op = GetOperator();
if (!op.empty())
values.push_back(op);
// Elevation.
string const eleStr = GetElevationFormatted();
if (!eleStr.empty())
values.push_back(kMountainSymbol + eleStr);
if (HasWifi())
values.push_back(m_localizedWifiString);
return strings::JoinStrings(values, kSubtitleSeparator);
}
string Info::FormatStars() const
{
string stars;
for (int i = 0; i < GetStars(); ++i)
stars.append(kStarSymbol);
return stars;
}
string Info::GetFormattedCoordinate(bool isDMS) const
{
auto const & ll = GetLatLon();
return isDMS ? measurement_utils::FormatLatLon(ll.lat, ll.lon) : measurement_utils::FormatLatLonAsDMS(ll.lat, ll.lon, 2);
}
string Info::GetCustomName() const { return m_customName; }
BookmarkAndCategory Info::GetBookmarkAndCategory() const { return m_bac; }
string Info::GetBookmarkCategoryName() const { return m_bookmarkCategoryName; }
string const & Info::GetApiUrl() const { return m_apiUrl; }
string const & Info::GetSponsoredBookingUrl() const { return m_sponsoredBookingUrl; }
string const & Info::GetSponsoredDescriptionUrl() const {return m_sponsoredDescriptionUrl; }
string Info::GetRatingFormatted() const
{
if (!IsSponsoredHotel())
return string();
auto const r = GetMetadata().Get(feature::Metadata::FMD_RATING);
char const * rating = r.empty() ? kEmptyRatingSymbol : r.c_str();
int const size = snprintf(nullptr, 0, m_localizedRatingString.c_str(), rating);
if (size < 0)
{
LOG(LERROR, ("Incorrect size for string:", m_localizedRatingString, ", rating:", rating));
return string();
}
vector<char> buf(size + 1);
snprintf(buf.data(), buf.size(), m_localizedRatingString.c_str(), rating);
return string(buf.begin(), buf.end());
}
string Info::GetApproximatePricing() const
{
if (!IsSponsoredHotel())
return string();
int pricing;
strings::to_int(GetMetadata().Get(feature::Metadata::FMD_PRICE_RATE), pricing);
string result;
for (auto i = 0; i < pricing; i++)
result.append(kPricingSymbol);
return result;
}
void Info::SetMercator(m2::PointD const & mercator) { m_mercator = mercator; }
} // namespace place_page
<commit_msg>[map] Added flats to place page subtitle.<commit_after>#include "place_page_info.hpp"
#include "indexer/feature_utils.hpp"
#include "indexer/osm_editor.hpp"
#include "platform/measurement_utils.hpp"
namespace place_page
{
char const * const Info::kSubtitleSeparator = " • ";
char const * const Info::kStarSymbol = "★";
char const * const Info::kMountainSymbol = "▲";
char const * const Info::kEmptyRatingSymbol = "-";
char const * const Info::kPricingSymbol = "$";
bool Info::IsFeature() const { return m_featureID.IsValid(); }
bool Info::IsBookmark() const { return m_bac.IsValid(); }
bool Info::IsMyPosition() const { return m_isMyPosition; }
bool Info::IsSponsoredHotel() const { return m_isSponsoredHotel; }
bool Info::IsHotel() const { return m_isHotel; }
bool Info::ShouldShowAddPlace() const
{
auto const isPointOrBuilding = IsPointType() || IsBuilding();
return m_canEditOrAdd && !(IsFeature() && isPointOrBuilding);
}
bool Info::ShouldShowAddBusiness() const { return m_canEditOrAdd && IsBuilding(); }
bool Info::ShouldShowEditPlace() const
{
return m_canEditOrAdd &&
// TODO(mgsergio): Does IsFeature() imply !IsMyPosition()?
!IsMyPosition() && IsFeature();
}
bool Info::HasApiUrl() const { return !m_apiUrl.empty(); }
bool Info::HasWifi() const { return GetInternet() == osm::Internet::Wlan; }
string Info::FormatNewBookmarkName() const
{
string const title = GetTitle();
if (title.empty())
return GetLocalizedType();
return title;
}
string Info::GetTitle() const
{
if (!m_customName.empty())
return m_customName;
string name;
feature::GetReadableName(GetID(), m_name, name);
return name;
}
string Info::GetSubtitle() const
{
if (!IsFeature())
{
if (IsBookmark())
return m_bookmarkCategoryName;
return {};
}
vector<string> values;
// Bookmark category.
if (IsBookmark())
values.push_back(m_bookmarkCategoryName);
// Type.
values.push_back(GetLocalizedType());
// Flats.
string const flats = GetFlats();
if (!flats.empty())
values.push_back(flats);
// Cuisines.
for (string const & cuisine : GetLocalizedCuisines())
values.push_back(cuisine);
// Stars.
string const stars = FormatStars();
if (!stars.empty())
values.push_back(stars);
// Operator.
string const op = GetOperator();
if (!op.empty())
values.push_back(op);
// Elevation.
string const eleStr = GetElevationFormatted();
if (!eleStr.empty())
values.push_back(kMountainSymbol + eleStr);
if (HasWifi())
values.push_back(m_localizedWifiString);
return strings::JoinStrings(values, kSubtitleSeparator);
}
string Info::FormatStars() const
{
string stars;
for (int i = 0; i < GetStars(); ++i)
stars.append(kStarSymbol);
return stars;
}
string Info::GetFormattedCoordinate(bool isDMS) const
{
auto const & ll = GetLatLon();
return isDMS ? measurement_utils::FormatLatLon(ll.lat, ll.lon) : measurement_utils::FormatLatLonAsDMS(ll.lat, ll.lon, 2);
}
string Info::GetCustomName() const { return m_customName; }
BookmarkAndCategory Info::GetBookmarkAndCategory() const { return m_bac; }
string Info::GetBookmarkCategoryName() const { return m_bookmarkCategoryName; }
string const & Info::GetApiUrl() const { return m_apiUrl; }
string const & Info::GetSponsoredBookingUrl() const { return m_sponsoredBookingUrl; }
string const & Info::GetSponsoredDescriptionUrl() const {return m_sponsoredDescriptionUrl; }
string Info::GetRatingFormatted() const
{
if (!IsSponsoredHotel())
return string();
auto const r = GetMetadata().Get(feature::Metadata::FMD_RATING);
char const * rating = r.empty() ? kEmptyRatingSymbol : r.c_str();
int const size = snprintf(nullptr, 0, m_localizedRatingString.c_str(), rating);
if (size < 0)
{
LOG(LERROR, ("Incorrect size for string:", m_localizedRatingString, ", rating:", rating));
return string();
}
vector<char> buf(size + 1);
snprintf(buf.data(), buf.size(), m_localizedRatingString.c_str(), rating);
return string(buf.begin(), buf.end());
}
string Info::GetApproximatePricing() const
{
if (!IsSponsoredHotel())
return string();
int pricing;
strings::to_int(GetMetadata().Get(feature::Metadata::FMD_PRICE_RATE), pricing);
string result;
for (auto i = 0; i < pricing; i++)
result.append(kPricingSymbol);
return result;
}
void Info::SetMercator(m2::PointD const & mercator) { m_mercator = mercator; }
} // namespace place_page
<|endoftext|> |
<commit_before>#include <array>
#include <list>
#include <deque>
#include <utility>
#include <algorithm>
#include <functional>
//#include <iostream> //debug
template <typename ValType, size_t NQueues, typename PriorityType>
class NPriorityQueue{
public:
//types
using PriorityList = std::array<PriorityType, NQueues>;
//functions
NPriorityQueue& enqueue(ValType value, PriorityList priorities){
//std::cout << "Enqueueing " << value << std::endl; //debug
elements_.push_front({value, priorities});
for(size_t N=0; N<priorities_.size(); ++N){
insert_sorted_(N, elements_.begin());
}
return *this;
}
template<size_t N> ValType&& dequeue(){
static_assert(N<NQueues, "dequeue()'s N out of bounds.");
//std::cout << "dequeueing " << N << std::endl; //debug
auto pelement = priorities_[N].front();
//std::cout << "...element is " << pelement->first << std::endl; //debug
for(size_t listN = 0; listN<priorities_.size(); ++listN){
auto to_erase = find_sorted_(listN, pelement);
//std::cout << "...erasing" << std::endl; //debug
priorities_[listN].erase(to_erase);
}
elements_.erase(pelement);
return std::move(pelement->first);
}
size_t count(){return elements_.size();}
void clear(){elements_.clear(); priorities_.clear();}
private:
//types
using Element = std::pair<ValType, PriorityList>;
using pElement = typename std::list<Element>::iterator;
using PriorityListItr = typename std::deque<pElement>::iterator;
//functions
std::function<bool(const pElement&, const pElement&)> compare_(size_t N) const{
return [N](const pElement& a, const pElement& b){
PriorityType ap = a->second[N];
PriorityType bp = b->second[N];
return ap<bp;
};
}
void insert_sorted_(size_t N, pElement ptr){
//std::cout << "...inserting " << ptr->first << " into " << N //debug
//<< " with priority " << ptr->second[N] << std::endl; //debug
auto& list = priorities_[N];
auto position = std::upper_bound(list.begin(), list.end(), ptr,
compare_(N));
priorities_[N].insert(position, ptr);
}
PriorityListItr find_sorted_(size_t N, pElement pel){
//std::cout << "...finding in " << N << std::endl; //debug
auto& list = priorities_[N];
auto range = std::equal_range(list.begin(), list.end(), pel,
compare_(N));
for(auto itr=range.first; itr!=range.second; ++itr){
//if(*itr==pel) std::cout << "...found." << std::endl; //debug
if(*itr==pel) return itr;
}
//std::cout << "...not found" << std::endl; //debug
return list.end(); //if not found
}
//members
std::list<Element> elements_;
std::array<std::deque<pElement>, NQueues> priorities_;
};
<commit_msg>Cleaned up NPriorityQueue<commit_after>#include <array>
#include <list>
#include <deque>
#include <utility>
#include <algorithm>
#include <functional>
template <typename ValType, size_t NQueues, typename PriorityType>
class NPriorityQueue{
public:
//types
using PriorityList = std::array<PriorityType, NQueues>;
//functions
/* Adds _value_ with priorities listed in _priorities_ */
NPriorityQueue& enqueue(ValType value, PriorityList priorities){
elements_.push_front({value, priorities});
for(size_t N=0; N<priorities_.size(); ++N){
insert_sorted_(N, elements_.begin());
}
return *this;
}
/* Removes the highest-priority element from list N */
template<size_t N> ValType&& dequeue(){
static_assert(N<NQueues, "dequeue()'s N out of bounds.");
auto pel = priorities_[N].front(); //pointer to element
for(size_t listN = 0; listN<priorities_.size(); ++listN){
auto to_erase = find_sorted_(listN, pel);
priorities_[listN].erase(to_erase);
}
elements_.erase(pel);
return std::move(pel->first);
}
/* Returns number of elements held */
size_t count(){return elements_.size();}
/* Empties the queue */
void clear(){
for(auto& list : priorities_){
list.clear();
}
elements_.clear();
}
private:
//types
using Element = std::pair<ValType, PriorityList>;
using pElement = typename std::list<Element>::iterator;
using PriorityListItr = typename std::deque<pElement>::iterator;
//functions
/* Returns function for comparing elements of list _N_ */
std::function<bool(const pElement&, const pElement&)> compare_(size_t N)
const{
return [N](const pElement& a, const pElement& b){
return a->second[N] < b->second[N];
};
}
/* Inserts _pel_ into list _N_ in sorted order */
void insert_sorted_(size_t N, pElement pel){//pel = pointer to element
auto& list = priorities_[N];
auto position = std::upper_bound(list.begin(), list.end(), pel,
compare_(N));
priorities_[N].insert(position, pel);
}
/* Finds _pel_ in list _N_. Returns iterator-to-last if not found. */
PriorityListItr find_sorted_(size_t N, pElement pel){
auto& list = priorities_[N];
auto range = std::equal_range(list.begin(), list.end(), pel,
compare_(N));
for(auto itr=range.first; itr!=range.second; ++itr){
if(*itr==pel) return itr;
}
return list.end(); //if not found
}
//members
std::list<Element> elements_;
std::array<std::deque<pElement>, NQueues> priorities_;
};
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2016 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "assert-macros.h"
#include <syslog.h>
#include <errno.h>
#include "SpinelNCPTaskLeave.h"
#include "SpinelNCPInstance.h"
#include "spinel-extra.h"
using namespace nl;
using namespace nl::wpantund;
nl::wpantund::SpinelNCPTaskLeave::SpinelNCPTaskLeave(
SpinelNCPInstance* instance,
CallbackWithStatusArg1 cb
): SpinelNCPTask(instance, cb)
{
}
int
nl::wpantund::SpinelNCPTaskLeave::vprocess_event(int event, va_list args)
{
int ret = kWPANTUNDStatus_Failure;
EH_BEGIN();
// The first event to a task is EVENT_STARTING_TASK. The following
// line makes sure that we don't start processing this task
// until it is properly scheduled. All tasks immediately receive
// the initial `EVENT_STARTING_TASK` event, but further events
// will only be received by that task once it is that task's turn
// to execute.
EH_WAIT_UNTIL(EVENT_STARTING_TASK != event);
mNextCommand = SpinelPackData(
SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
SPINEL_PROP_NET_STACK_UP,
false
);
EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
ret = mNextCommandRet;
require_noerr(ret, on_error);
mNextCommand = SpinelPackData(
SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
SPINEL_PROP_NET_IF_UP,
false
);
EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
ret = mNextCommandRet;
require_noerr(ret, on_error);
if (mInstance->mCapabilities.count(SPINEL_CAP_NET_SAVE)) {
mNextCommand = SpinelPackData(SPINEL_FRAME_PACK_CMD_NET_CLEAR);
EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
ret = mNextCommandRet;
require_noerr(ret, on_error);
}
ret = kWPANTUNDStatus_Ok;
finish(ret);
EH_EXIT();
on_error:
if (ret == kWPANTUNDStatus_Ok) {
ret = kWPANTUNDStatus_Failure;
}
syslog(LOG_ERR, "Leave failed: %d", ret);
mInstance->reinitialize_ncp();
finish(ret);
EH_END();
}
<commit_msg>ncp-spinel: Allow leave command to work even while NCP is initializing.<commit_after>/*
*
* Copyright (c) 2016 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "assert-macros.h"
#include <syslog.h>
#include <errno.h>
#include "SpinelNCPTaskLeave.h"
#include "SpinelNCPInstance.h"
#include "spinel-extra.h"
using namespace nl;
using namespace nl::wpantund;
nl::wpantund::SpinelNCPTaskLeave::SpinelNCPTaskLeave(
SpinelNCPInstance* instance,
CallbackWithStatusArg1 cb
): SpinelNCPTask(instance, cb)
{
}
int
nl::wpantund::SpinelNCPTaskLeave::vprocess_event(int event, va_list args)
{
int ret = kWPANTUNDStatus_Failure;
EH_BEGIN();
if (!mInstance->mEnabled) {
ret = kWPANTUNDStatus_InvalidWhenDisabled;
finish(ret);
EH_EXIT();
}
if (mInstance->get_ncp_state() == UPGRADING) {
ret = kWPANTUNDStatus_InvalidForCurrentState;
finish(ret);
EH_EXIT();
}
// Wait for a bit to see if the NCP will enter the right state.
EH_REQUIRE_WITHIN(
NCP_DEFAULT_COMMAND_RESPONSE_TIMEOUT,
!ncp_state_is_initializing(mInstance->get_ncp_state()),
on_error
);
// The first event to a task is EVENT_STARTING_TASK. The following
// line makes sure that we don't start processing this task
// until it is properly scheduled. All tasks immediately receive
// the initial `EVENT_STARTING_TASK` event, but further events
// will only be received by that task once it is that task's turn
// to execute.
EH_WAIT_UNTIL(EVENT_STARTING_TASK != event);
mNextCommand = SpinelPackData(
SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
SPINEL_PROP_NET_STACK_UP,
false
);
EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
ret = mNextCommandRet;
require_noerr(ret, on_error);
mNextCommand = SpinelPackData(
SPINEL_FRAME_PACK_CMD_PROP_VALUE_SET(SPINEL_DATATYPE_BOOL_S),
SPINEL_PROP_NET_IF_UP,
false
);
EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
ret = mNextCommandRet;
require_noerr(ret, on_error);
if (mInstance->mCapabilities.count(SPINEL_CAP_NET_SAVE)) {
mNextCommand = SpinelPackData(SPINEL_FRAME_PACK_CMD_NET_CLEAR);
EH_SPAWN(&mSubPT, vprocess_send_command(event, args));
ret = mNextCommandRet;
require_noerr(ret, on_error);
}
ret = kWPANTUNDStatus_Ok;
finish(ret);
EH_EXIT();
on_error:
if (ret == kWPANTUNDStatus_Ok) {
ret = kWPANTUNDStatus_Failure;
}
syslog(LOG_ERR, "Leave failed: %d", ret);
mInstance->reinitialize_ncp();
finish(ret);
EH_END();
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliACORDEPreprocessor.h"
#include "TRandom.h"
#include "TFile.h"
#include "AliCDBMetaData.h"
#include "AliCDBEntry.h"
#include "AliLog.h"
#include "AliACORDECalibData.h"
#include <TTimeStamp.h>
#include <TObjString.h>
#include <TList.h>
#include <TH1F.h>
//
// This is the first version of ACORDE Preprocessor
// It takes data from DAQ and passes it to the class AliACORDECalibModule and
// stores reference data.
//
// Authors
// Pedro Gonzalez pedro.gonzalez@fcfm.buap.mx
// Irais Bautista irais@fcfm.buap.mx
// Arturo Fernandez Tellez afernan@cern.ch
ClassImp(AliACORDEPreprocessor)
//______________________________________________________________________________________________
AliACORDEPreprocessor::AliACORDEPreprocessor(AliShuttleInterface* shuttle) :
AliPreprocessor("ACO", shuttle),
fCalData(0)
{
// constructor
}
//______________________________________________________________________________________________
AliACORDEPreprocessor::~AliACORDEPreprocessor()
{
// destructor
}
//______________________________________________________________________________________________
void AliACORDEPreprocessor::Initialize(Int_t run, UInt_t startTime,
UInt_t endTime)
{
// Creates AliACORDECalibModule object
AliPreprocessor::Initialize(run, startTime, endTime);
Log(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
fCalData = new AliACORDECalibData();
}
//______________________________________________________________________________________________
UInt_t AliACORDEPreprocessor::Process(TMap* /*dcsAliasMap*/)
{
TH1D *fH1,*fH2,*fH3,*fH4; //Histogram of the rates per module
TFile *daqFile=0x0;
// retrieve the run type from the Shuttle,
TString runType = GetRunType();
//acorde STANDALONE_BC
//acorde STANDALONE_PULSER
if(runType !="STANDALONE_PULSER")
{
Log("RunType is not STANDALONE_PULSER, nothing to do");
return 1;
}
Log(Form("Run type for run %d: %s", fRun, runType.Data()));
TString SourcesId = "CALIB";
//retrieve the list of sources that produced the file with id RATES
TList* sourceList = GetFileSources(kDAQ,SourcesId.Data());
if (!sourceList)
{
Log(Form("Error: No sources found for id %s", SourcesId.Data()));
return 2;
}
// TODO We have the list of sources that produced the files with Id RATES
// Now we will loop on the list and we'll query the files one by one.
Log(Form("The following sources produced files with the id %s",SourcesId.Data()));
sourceList->Print();
TIter iter(sourceList);
TObjString *source = 0;
while((source=dynamic_cast<TObjString*> (iter.Next())))
{
TString fileName = GetFile(kDAQ,SourcesId.Data(), source->GetName());
if (fileName.Length() > 0)
Log(Form("Got the file %s, now we can extract some values.", fileName.Data()));
daqFile = new TFile(fileName.Data(),"READ");
if(!daqFile)
{
Log(Form("There are not histos 1"));
return 3;
}
fH1 = (TH1D*)daqFile->Get("fHist1");
fH2 = (TH1D*)daqFile->Get("fHist2");
fH3 = (TH1D*)daqFile->Get("fHist3");
fH4 = (TH1D*)daqFile->Get("fHist4");
if(fH1!=NULL&&fH2!=NULL&&fH3!=NULL&&fH4!=NULL)
{
fCalData->AddHHits(fH1);
fCalData->AddHTHits(fH2);
fCalData->AddHMultiHits(fH3);
fCalData->AddHTMultiHits(fH4);
}
else
{
Log(Form("There are not histos 2"));
return 4;
}
}
delete sourceList;
//Now we have to store
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Pedro and Irais");
metaData.SetComment("This preprocessor fills an AliACORDECalibModule object.");
Bool_t result = StoreReferenceData("Calib", "Data",fCalData, &metaData);
delete fCalData;
fCalData = 0;
if (!result)
return 4;
return 0;
}
<commit_msg>Correction of Acorde's Preprocessor (Luciano Diaz)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include "AliACORDEPreprocessor.h"
#include "TRandom.h"
#include "TFile.h"
#include "AliCDBMetaData.h"
#include "AliCDBEntry.h"
#include "AliLog.h"
#include "AliACORDECalibData.h"
#include <TTimeStamp.h>
#include <TObjString.h>
#include <TList.h>
#include <TH1F.h>
//
// This is the first version of ACORDE Preprocessor
// It takes data from DAQ and passes it to the class AliACORDECalibModule and
// stores reference data.
//
// Authors
// Pedro Gonzalez pedro.gonzalez@fcfm.buap.mx
// Irais Bautista irais@fcfm.buap.mx
// Arturo Fernandez Tellez afernan@cern.ch
ClassImp(AliACORDEPreprocessor)
//______________________________________________________________________________________________
AliACORDEPreprocessor::AliACORDEPreprocessor(AliShuttleInterface* shuttle) :
AliPreprocessor("ACO", shuttle),
fCalData(0)
{
// constructor
}
//______________________________________________________________________________________________
AliACORDEPreprocessor::~AliACORDEPreprocessor()
{
// destructor
}
//______________________________________________________________________________________________
void AliACORDEPreprocessor::Initialize(Int_t run, UInt_t startTime,
UInt_t endTime)
{
// Creates AliACORDECalibModule object
AliPreprocessor::Initialize(run, startTime, endTime);
Log(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
fCalData = new AliACORDECalibData();
}
//______________________________________________________________________________________________
UInt_t AliACORDEPreprocessor::Process(TMap* /*dcsAliasMap*/)
{
TH1D *fH1,*fH2,*fH3,*fH4; //Histogram of the rates per module
TFile *daqFile=0x0;
// retrieve the run type from the Shuttle,
TString runType = GetRunType();
//acorde STANDALONE_BC
//acorde STANDALONE_PULSER
if(runType !="STANDALONE_PULSER")
{
Log("RunType is not STANDALONE_PULSER, nothing to do");
return 0;
}
Log(Form("Run type for run %d: %s", fRun, runType.Data()));
TString SourcesId = "CALIB";
//retrieve the list of sources that produced the file with id RATES
TList* sourceList = GetFileSources(kDAQ,SourcesId.Data());
if (!sourceList)
{
Log(Form("Error: No sources found for id %s", SourcesId.Data()));
return 2;
}
// TODO We have the list of sources that produced the files with Id RATES
// Now we will loop on the list and we'll query the files one by one.
Log(Form("The following sources produced files with the id %s",SourcesId.Data()));
sourceList->Print();
TIter iter(sourceList);
TObjString *source = 0;
while((source=dynamic_cast<TObjString*> (iter.Next())))
{
TString fileName = GetFile(kDAQ,SourcesId.Data(), source->GetName());
if (fileName.Length() > 0)
Log(Form("Got the file %s, now we can extract some values.", fileName.Data()));
daqFile = new TFile(fileName.Data(),"READ");
if(!daqFile)
{
Log(Form("There are not histos 1"));
return 3;
}
fH1 = (TH1D*)daqFile->Get("fHist1");
fH2 = (TH1D*)daqFile->Get("fHist2");
fH3 = (TH1D*)daqFile->Get("fHist3");
fH4 = (TH1D*)daqFile->Get("fHist4");
if(fH1!=NULL&&fH2!=NULL&&fH3!=NULL&&fH4!=NULL)
{
fCalData->AddHHits(fH1);
fCalData->AddHTHits(fH2);
fCalData->AddHMultiHits(fH3);
fCalData->AddHTMultiHits(fH4);
}
else
{
Log(Form("There are not histos 2"));
return 4;
}
}
delete sourceList;
//Now we have to store
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Pedro and Irais");
metaData.SetComment("This preprocessor fills an AliACORDECalibModule object.");
Bool_t result = StoreReferenceData("Calib", "Data",fCalData, &metaData);
delete fCalData;
fCalData = 0;
if (!result)
return 4;
return 0;
}
<|endoftext|> |
<commit_before>#include "compressor.h"
#include "agenda.h"
#include "context.h"
#include <zlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "scope_guard.h"
#include "errors.h"
using namespace es3;
using namespace boost::filesystem;
#define MINIMAL_BLOCK (1024*1024)
#define COMPRESSION_THRESHOLD 10000000
namespace es3
{
struct compress_task : public sync_task
{
compressor_ptr parent_;
uint64_t block_num_, offset_, size_, block_total_;
virtual std::string get_class() const
{
return "compression"+int_to_string(get_class_limit());
}
virtual size_t get_class_limit() const
{
return parent_->context_->max_compressors_;
}
virtual void operator()(agenda_ptr agenda)
{
std::pair<std::string,uint64_t> res=do_compress();
parent_->on_complete(res.first, block_num_, res.second);
}
std::pair<std::string,uint64_t> do_compress()
{
handle_t src(open(parent_->path_.c_str(), O_RDONLY));
lseek64(src.get(), offset_, SEEK_SET) | libc_die;
//Generate the temp name
path tmp_nm = path(parent_->context_->scratch_path_) /
unique_path("scratchy-%%%%-%%%%-%%%%-%%%%");
handle_t tmp_desc(open(tmp_nm.c_str(), O_RDWR|O_CREAT,
S_IRUSR|S_IWUSR));
VLOG(2) << "Compressing part " << block_num_ << " out of " <<
block_total_ << " of " << parent_->path_;
z_stream stream = {0};
deflateInit2(&stream, 1, Z_DEFLATED,
15|16, //15 window bits | GZIP
8,
Z_DEFAULT_STRATEGY);
ON_BLOCK_EXIT(&deflateEnd, &stream);
std::vector<char> buf;
std::vector<char> buf_out;
buf.resize(1024*1024*2);
buf_out.resize(1024*1024);
size_t consumed=0;
size_t raw_consumed=0;
while(raw_consumed<size_)
{
size_t chunk = std::min(uint64_t(buf.size()),
size_-raw_consumed);
ssize_t ln=read(src.get(), &buf[0], chunk) | libc_die;
assert(ln>0);
raw_consumed+=ln;
stream.avail_in = ln;
stream.next_in = (Bytef*)&buf[0];
do
{
stream.avail_out= buf_out.size();
stream.next_out = (Bytef*)&buf_out[0];
int c_err=deflate(&stream, Z_NO_FLUSH);
if (c_err!=Z_OK)
err(errFatal) << "Failed to compress "
<< parent_->path_;
size_t cur_consumed=buf_out.size() - stream.avail_out;
write(tmp_desc.get(), &buf_out[0], cur_consumed) | libc_die;
consumed += cur_consumed;
} while(stream.avail_in!=0);
}
assert(raw_consumed==size_);
//We're writing the epilogue
stream.avail_out= buf_out.size();
stream.next_out = (Bytef*)&buf_out[0];
int c_err=deflate(&stream, Z_FINISH);
if (c_err!=Z_STREAM_END) //Epilogue must always fit
err(errFatal) << "Failed to finish compression of "
<< parent_->path_;
size_t cur_consumed=buf_out.size() - stream.avail_out;
consumed += cur_consumed;
if (cur_consumed!=0)
write(tmp_desc.get(), &buf_out[0], cur_consumed) | libc_die;
VLOG(2) << "Done compressing part " << block_num_ << " out of " <<
block_total_ << " of " << parent_->path_;
return std::pair<std::string,uint64_t>(tmp_nm.c_str(), consumed);
}
};
}; //namespace es3
void file_compressor::operator()(agenda_ptr agenda)
{
uint64_t file_sz=file_size(path_);
if (file_sz<=MINIMAL_BLOCK)
{
handle_t desc(open(path_.c_str(), O_RDONLY));
on_finish_(zip_result_ptr(new compressed_result(path_, desc.size())));
return;
}
//Start compressing
uint64_t estimate_num_blocks = file_sz / MINIMAL_BLOCK;
assert(estimate_num_blocks>0);
if (estimate_num_blocks> context_->max_compressors_)
estimate_num_blocks = context_->max_compressors_;
uint64_t block_sz = file_sz / estimate_num_blocks;
assert(block_sz>0);
uint64_t num_blocks = file_sz / block_sz +
((file_sz%block_sz)==0?0:1);
result_=zip_result_ptr(new compressed_result(num_blocks));
num_pending_ = num_blocks;
for(uint64_t f=0; f<num_blocks; ++f)
{
boost::shared_ptr<compress_task> ptr(new compress_task());
ptr->parent_=shared_from_this();
ptr->block_num_=f;
ptr->block_total_=num_blocks;
ptr->offset_=block_sz*f;
ptr->size_=file_sz-ptr->offset_;
if (ptr->size_>block_sz)
ptr->size_=block_sz;
agenda->schedule(ptr);
}
}
void file_compressor::on_complete(const std::string &name, uint64_t num,
uint64_t resulting_size)
{
{
guard_t lock(m_);
num_pending_--;
result_->files_.at(num) = name;
result_->sizes_.at(num) = resulting_size;
}
if (num_pending_==0)
{
on_finish_(result_);
}
}
void file_decompressor::operator()(agenda_ptr agenda)
{
z_stream stream = {0};
inflateInit2(&stream, 15 | 16);
ON_BLOCK_EXIT(&inflateEnd, &stream);
std::vector<char> buf;
std::vector<char> buf_out;
buf.resize(1024*1024);
buf_out.resize(1024*1024*2);
uint64_t written_so_far=0;
handle_t in_fl(open(source_.c_str(), O_RDONLY) |
libc_die2("Failed to decompress to "+result_.string()+
", can't open temporary file"));
//Create the temporary output file
path temp_name_template=result_.string()+"-%%%%%%%%%";
path temp_out_name=bf::unique_path(temp_name_template);
ON_BLOCK_EXIT(&unlink, temp_out_name.c_str());
handle_t out_fl(open(temp_out_name.c_str(), O_WRONLY|O_CREAT, 0600) |
libc_die2("Failed to decompress to "+result_.string()));
while(true)
{
size_t cur_chunk=read(in_fl.get(), &buf[0], buf.size()) | libc_die;
if (cur_chunk==0)
break;
stream.avail_in = cur_chunk;
stream.next_in = (Bytef*)&buf[0];
while (stream.avail_in>0)
{
stream.next_out = (Bytef*)&buf_out[0];
stream.avail_out = buf_out.size();
int res = inflate(&stream, Z_SYNC_FLUSH);
if (res<0)
err(errFatal) << "GZ error, failed to decompress " << result_;
size_t to_write = buf_out.size()-stream.avail_out;
written_so_far+=to_write;
write(out_fl.get(), &buf_out[0], to_write) | libc_die;
if (res == Z_STREAM_END)
{
//For gzip files with concatenated content
inflateEnd(&stream);
inflateInit2(&stream, 15 | 16);
}
}
}
bf::last_write_time(temp_out_name, mtime_);
chmod(temp_out_name.c_str(), mode_)
| libc_die2("Failed to set mode on "+result_.string());
rename(temp_out_name.c_str(), result_.c_str())
| libc_die2("Failed to replace "+result_.string());
}
std::string file_decompressor::get_class() const
{
return "decompression"+int_to_string(get_class_limit());
}
size_t file_decompressor::get_class_limit() const
{
return context_->max_compressors_;
}
bool es3::should_compress(const bf::path &p, uint64_t sz)
{
std::string ext=p.extension().c_str();
if (ext==".gz" || ext==".zip" ||
ext==".tgz" || ext==".bz2" || ext==".7z")
return false;
if (sz <= COMPRESSION_THRESHOLD)
return false;
//Check for GZIP magic
int fl=open(bf::absolute(p).c_str(), O_RDONLY)
| libc_die2("Can't open file "+p.string());
ON_BLOCK_EXIT(&close, fl);
char magic[4]={0};
read(fl, magic, 4) | libc_die2("Can't read "+p.string());
if (magic[0]==0x1F && magic[1] == 0x8B && magic[2]==0x8 && magic[3]==0x8)
return false;
return true;
}
<commit_msg>Code cleanups<commit_after>#include "compressor.h"
#include "agenda.h"
#include "context.h"
#include <zlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "scope_guard.h"
#include "errors.h"
using namespace es3;
using namespace boost::filesystem;
#define MINIMAL_BLOCK (1024*1024)
#define COMPRESSION_THRESHOLD 10000000
namespace es3
{
struct compress_task : public sync_task
{
compressor_ptr parent_;
uint64_t block_num_, offset_, size_, block_total_;
virtual std::string get_class() const
{
return "compression"+int_to_string(get_class_limit());
}
virtual size_t get_class_limit() const
{
return parent_->context_->max_compressors_;
}
virtual void operator()(agenda_ptr agenda)
{
std::pair<std::string,uint64_t> res=do_compress();
parent_->on_complete(res.first, block_num_, res.second);
}
std::pair<std::string,uint64_t> do_compress()
{
handle_t src(open(parent_->path_.c_str(), O_RDONLY));
lseek64(src.get(), offset_, SEEK_SET) | libc_die;
//Generate the temp name
path tmp_nm = path(parent_->context_->scratch_path_) /
unique_path("scratchy-%%%%-%%%%-%%%%-%%%%");
handle_t tmp_desc(open(tmp_nm.c_str(), O_RDWR|O_CREAT,
S_IRUSR|S_IWUSR));
VLOG(2) << "Compressing part " << block_num_ << " out of " <<
block_total_ << " of " << parent_->path_;
z_stream stream = {0};
deflateInit2(&stream, 1, Z_DEFLATED,
15|16, //15 window bits | GZIP
8,
Z_DEFAULT_STRATEGY);
ON_BLOCK_EXIT(&deflateEnd, &stream);
std::vector<char> buf;
std::vector<char> buf_out;
buf.resize(1024*1024*2);
buf_out.resize(1024*1024);
size_t consumed=0;
size_t raw_consumed=0;
while(raw_consumed<size_)
{
size_t chunk = std::min(uint64_t(buf.size()),
size_-raw_consumed);
ssize_t ln=read(src.get(), &buf[0], chunk) | libc_die;
assert(ln>0);
raw_consumed+=ln;
stream.avail_in = ln;
stream.next_in = (Bytef*)&buf[0];
do
{
stream.avail_out= buf_out.size();
stream.next_out = (Bytef*)&buf_out[0];
int c_err=deflate(&stream, Z_NO_FLUSH);
if (c_err!=Z_OK)
err(errFatal) << "Failed to compress "
<< parent_->path_;
size_t cur_consumed=buf_out.size() - stream.avail_out;
write(tmp_desc.get(), &buf_out[0], cur_consumed) | libc_die;
consumed += cur_consumed;
} while(stream.avail_in!=0);
}
assert(raw_consumed==size_);
//We're writing the epilogue
stream.avail_out= buf_out.size();
stream.next_out = (Bytef*)&buf_out[0];
int c_err=deflate(&stream, Z_FINISH);
if (c_err!=Z_STREAM_END) //Epilogue must always fit
err(errFatal) << "Failed to finish compression of "
<< parent_->path_;
size_t cur_consumed=buf_out.size() - stream.avail_out;
consumed += cur_consumed;
if (cur_consumed!=0)
write(tmp_desc.get(), &buf_out[0], cur_consumed) | libc_die;
VLOG(2) << "Done compressing part " << block_num_ << " out of " <<
block_total_ << " of " << parent_->path_;
return std::pair<std::string,uint64_t>(tmp_nm.c_str(), consumed);
}
};
}; //namespace es3
void file_compressor::operator()(agenda_ptr agenda)
{
uint64_t file_sz=file_size(path_);
assert(file_sz>MINIMAL_BLOCK);
//Start compressing
uint64_t estimate_num_blocks = file_sz / MINIMAL_BLOCK;
assert(estimate_num_blocks>0);
if (estimate_num_blocks> context_->max_compressors_)
estimate_num_blocks = context_->max_compressors_;
uint64_t block_sz = file_sz / estimate_num_blocks;
assert(block_sz>0);
uint64_t num_blocks = file_sz / block_sz +
((file_sz%block_sz)==0?0:1);
result_=zip_result_ptr(new compressed_result(num_blocks));
num_pending_ = num_blocks;
for(uint64_t f=0; f<num_blocks; ++f)
{
boost::shared_ptr<compress_task> ptr(new compress_task());
ptr->parent_=shared_from_this();
ptr->block_num_=f;
ptr->block_total_=num_blocks;
ptr->offset_=block_sz*f;
ptr->size_=file_sz-ptr->offset_;
if (ptr->size_>block_sz)
ptr->size_=block_sz;
agenda->schedule(ptr);
}
}
void file_compressor::on_complete(const std::string &name, uint64_t num,
uint64_t resulting_size)
{
{
guard_t lock(m_);
assert(num_pending_!=0);
num_pending_--;
result_->files_.at(num) = name;
result_->sizes_.at(num) = resulting_size;
}
if (num_pending_==0)
on_finish_(result_);
}
void file_decompressor::operator()(agenda_ptr agenda)
{
z_stream stream = {0};
inflateInit2(&stream, 15 | 16);
ON_BLOCK_EXIT(&inflateEnd, &stream);
std::vector<char> buf;
std::vector<char> buf_out;
buf.resize(1024*1024);
buf_out.resize(1024*1024*2);
uint64_t written_so_far=0;
handle_t in_fl(open(source_.c_str(), O_RDONLY) |
libc_die2("Failed to decompress to "+result_.string()+
", can't open temporary file"));
//Create the temporary output file
path temp_name_template=result_.string()+"-%%%%%%%%%";
path temp_out_name=bf::unique_path(temp_name_template);
ON_BLOCK_EXIT(&unlink, temp_out_name.c_str());
handle_t out_fl(open(temp_out_name.c_str(), O_WRONLY|O_CREAT, 0600) |
libc_die2("Failed to decompress to "+result_.string()));
while(true)
{
size_t cur_chunk=read(in_fl.get(), &buf[0], buf.size()) | libc_die;
if (cur_chunk==0)
break;
stream.avail_in = cur_chunk;
stream.next_in = (Bytef*)&buf[0];
while (stream.avail_in>0)
{
stream.next_out = (Bytef*)&buf_out[0];
stream.avail_out = buf_out.size();
int res = inflate(&stream, Z_SYNC_FLUSH);
if (res<0)
err(errFatal) << "GZ error, failed to decompress " << result_;
size_t to_write = buf_out.size()-stream.avail_out;
written_so_far+=to_write;
write(out_fl.get(), &buf_out[0], to_write) | libc_die;
if (res == Z_STREAM_END)
{
//For gzip files with concatenated content
inflateEnd(&stream);
inflateInit2(&stream, 15 | 16);
}
}
}
bf::last_write_time(temp_out_name, mtime_);
chmod(temp_out_name.c_str(), mode_)
| libc_die2("Failed to set mode on "+result_.string());
rename(temp_out_name.c_str(), result_.c_str())
| libc_die2("Failed to replace "+result_.string());
}
std::string file_decompressor::get_class() const
{
return "decompression"+int_to_string(get_class_limit());
}
size_t file_decompressor::get_class_limit() const
{
return context_->max_compressors_;
}
bool es3::should_compress(const bf::path &p, uint64_t sz)
{
std::string ext=p.extension().c_str();
if (ext==".gz" || ext==".zip" ||
ext==".tgz" || ext==".bz2" || ext==".7z")
return false;
if (sz <= COMPRESSION_THRESHOLD)
return false;
//Check for GZIP magic
int fl=open(bf::absolute(p).c_str(), O_RDONLY)
| libc_die2("Can't open file "+p.string());
ON_BLOCK_EXIT(&close, fl);
char magic[4]={0};
read(fl, magic, 4) | libc_die2("Can't read "+p.string());
if (magic[0]==0x1F && magic[1] == 0x8B && magic[2]==0x8 && magic[3]==0x8)
return false;
return true;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "cpasterplugin.h"
#include "pasteview.h"
#include "kdepasteprotocol.h"
#include "pastebindotcomprotocol.h"
#include "pastebindotcaprotocol.h"
#include "fileshareprotocol.h"
#include "pasteselectdialog.h"
#include "settingspage.h"
#include "settings.h"
#include "urlopenprotocol.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/id.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <utils/qtcassert.h>
#include <utils/fileutils.h>
#include <texteditor/itexteditor.h>
#include <QtPlugin>
#include <QDebug>
#include <QDir>
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QInputDialog>
#include <QUrl>
using namespace Core;
using namespace TextEditor;
namespace CodePaster {
/*!
\class CodePaster::CodePasterService
\brief The CodePasterService class is a service registered with PluginManager
that provides CodePaster \c post() functionality.
\sa ExtensionSystem::PluginManager::getObjectByClassName, ExtensionSystem::invoke
\sa VcsBase::VcsBaseEditorWidget
*/
CodePasterService::CodePasterService(QObject *parent) :
QObject(parent)
{
}
void CodePasterService::postText(const QString &text, const QString &mimeType)
{
QTC_ASSERT(CodepasterPlugin::instance(), return);
CodepasterPlugin::instance()->post(text, mimeType);
}
void CodePasterService::postCurrentEditor()
{
QTC_ASSERT(CodepasterPlugin::instance(), return);
CodepasterPlugin::instance()->postEditor();
}
void CodePasterService::postClipboard()
{
QTC_ASSERT(CodepasterPlugin::instance(), return);
CodepasterPlugin::instance()->postClipboard();
}
// ---------- CodepasterPlugin
CodepasterPlugin *CodepasterPlugin::m_instance = 0;
CodepasterPlugin::CodepasterPlugin() :
m_settings(new Settings),
m_postEditorAction(0), m_postClipboardAction(0), m_fetchAction(0)
{
CodepasterPlugin::m_instance = this;
}
CodepasterPlugin::~CodepasterPlugin()
{
delete m_urlOpen;
qDeleteAll(m_protocols);
CodepasterPlugin::m_instance = 0;
}
bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
// Create the globalcontext list to register actions accordingly
Core::Context globalcontext(Core::Constants::C_GLOBAL);
// Create the settings Page
m_settings->fromSettings(Core::ICore::settings());
SettingsPage *settingsPage = new SettingsPage(m_settings);
addAutoReleasedObject(settingsPage);
// Create the protocols and append them to the Settings
Protocol *protos[] = { new PasteBinDotComProtocol,
new PasteBinDotCaProtocol,
new KdePasteProtocol,
new FileShareProtocol
};
const int count = sizeof(protos) / sizeof(Protocol *);
for (int i = 0; i < count; ++i) {
connect(protos[i], SIGNAL(pasteDone(QString)), this, SLOT(finishPost(QString)));
connect(protos[i], SIGNAL(fetchDone(QString,QString,bool)),
this, SLOT(finishFetch(QString,QString,bool)));
settingsPage->addProtocol(protos[i]->name());
if (protos[i]->hasSettings())
addAutoReleasedObject(protos[i]->settingsPage());
m_protocols.append(protos[i]);
}
m_urlOpen = new UrlOpenProtocol;
connect(m_urlOpen, SIGNAL(fetchDone(QString,QString,bool)),
this, SLOT(finishFetch(QString,QString,bool)));
//register actions
Core::ActionContainer *toolsContainer =
Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
Core::ActionContainer *cpContainer =
Core::ActionManager::createMenu("CodePaster");
cpContainer->menu()->setTitle(tr("&Code Pasting"));
toolsContainer->addMenu(cpContainer);
Core::Command *command;
m_postEditorAction = new QAction(tr("Paste Snippet..."), this);
command = Core::ActionManager::registerAction(m_postEditorAction, "CodePaster.Post", globalcontext);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+C,Meta+P") : tr("Alt+C,Alt+P")));
connect(m_postEditorAction, SIGNAL(triggered()), this, SLOT(postEditor()));
cpContainer->addAction(command);
m_postClipboardAction = new QAction(tr("Paste Clipboard..."), this);
command = Core::ActionManager::registerAction(m_postClipboardAction, "CodePaster.PostClipboard", globalcontext);
connect(m_postClipboardAction, SIGNAL(triggered()), this, SLOT(postClipboard()));
cpContainer->addAction(command);
m_fetchAction = new QAction(tr("Fetch Snippet..."), this);
command = Core::ActionManager::registerAction(m_fetchAction, "CodePaster.Fetch", globalcontext);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+C,Meta+F") : tr("Alt+C,Alt+F")));
connect(m_fetchAction, SIGNAL(triggered()), this, SLOT(fetch()));
cpContainer->addAction(command);
m_fetchUrlAction = new QAction(tr("Fetch from URL..."), this);
command = Core::ActionManager::registerAction(m_fetchUrlAction, "CodePaster.FetchUrl", globalcontext);
connect(m_fetchUrlAction, SIGNAL(triggered()), this, SLOT(fetchUrl()));
cpContainer->addAction(command);
addAutoReleasedObject(new CodePasterService);
return true;
}
void CodepasterPlugin::extensionsInitialized()
{
}
ExtensionSystem::IPlugin::ShutdownFlag CodepasterPlugin::aboutToShutdown()
{
// Delete temporary, fetched files
foreach (const QString &fetchedSnippet, m_fetchedSnippets) {
QFile file(fetchedSnippet);
if (file.exists())
file.remove();
}
return SynchronousShutdown;
}
void CodepasterPlugin::postEditor()
{
QString data;
QString mimeType;
if (IEditor *editor = EditorManager::currentEditor()) {
if (ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor)) {
data = textEditor->selectedText();
if (data.isEmpty())
data = textEditor->textDocument()->plainText();
mimeType = textEditor->document()->mimeType();
}
}
post(data, mimeType);
}
void CodepasterPlugin::postClipboard()
{
QString subtype = QLatin1String("plain");
const QString text = qApp->clipboard()->text(subtype, QClipboard::Clipboard);
if (!text.isEmpty())
post(text, QString());
}
static inline void fixSpecialCharacters(QString &data)
{
QChar *uc = data.data();
QChar *e = uc + data.size();
for (; uc != e; ++uc) {
switch (uc->unicode()) {
case 0xfdd0: // QTextBeginningOfFrame
case 0xfdd1: // QTextEndOfFrame
case QChar::ParagraphSeparator:
case QChar::LineSeparator:
*uc = QLatin1Char('\n');
break;
case QChar::Nbsp:
*uc = QLatin1Char(' ');
break;
default:
break;
}
}
}
void CodepasterPlugin::post(QString data, const QString &mimeType)
{
fixSpecialCharacters(data);
const QString username = m_settings->username;
PasteView view(m_protocols, mimeType, ICore::dialogParent());
view.setProtocol(m_settings->protocol);
const FileDataList diffChunks = splitDiffToFiles(data);
const int dialogResult = diffChunks.isEmpty() ?
view.show(username, QString(), QString(), m_settings->expiryDays, data) :
view.show(username, QString(), QString(), m_settings->expiryDays, diffChunks);
// Save new protocol in case user changed it.
if (dialogResult == QDialog::Accepted
&& m_settings->protocol != view.protocol()) {
m_settings->protocol = view.protocol();
m_settings->toSettings(Core::ICore::settings());
}
}
void CodepasterPlugin::fetchUrl()
{
QUrl url;
do {
bool ok = true;
url = QUrl(QInputDialog::getText(ICore::dialogParent(), tr("Fetch from URL"), tr("Enter URL:"), QLineEdit::Normal, QString(), &ok));
if (!ok)
return;
} while (!url.isValid());
m_urlOpen->fetch(url.toString());
}
void CodepasterPlugin::fetch()
{
PasteSelectDialog dialog(m_protocols, ICore::dialogParent());
dialog.setProtocol(m_settings->protocol);
if (dialog.exec() != QDialog::Accepted)
return;
// Save new protocol in case user changed it.
if (m_settings->protocol != dialog.protocol()) {
m_settings->protocol = dialog.protocol();
m_settings->toSettings(Core::ICore::settings());
}
const QString pasteID = dialog.pasteId();
if (pasteID.isEmpty())
return;
Protocol *protocol = m_protocols[dialog.protocolIndex()];
if (Protocol::ensureConfiguration(protocol))
protocol->fetch(pasteID);
}
void CodepasterPlugin::finishPost(const QString &link)
{
if (m_settings->copyToClipboard)
QApplication::clipboard()->setText(link);
MessageManager::write(link, m_settings->displayOutput ? Core::MessageManager::ModeSwitch : Core::MessageManager::Silent);
}
// Extract the characters that can be used for a file name from a title
// "CodePaster.com-34" -> "CodePastercom34".
static inline QString filePrefixFromTitle(const QString &title)
{
QString rc;
const int titleSize = title.size();
rc.reserve(titleSize);
for (int i = 0; i < titleSize; i++)
if (title.at(i).isLetterOrNumber())
rc.append(title.at(i));
if (rc.isEmpty()) {
rc = QLatin1String("qtcreator");
} else {
if (rc.size() > 15)
rc.truncate(15);
}
return rc;
}
// Return a temp file pattern with extension or not
static inline QString tempFilePattern(const QString &prefix, const QString &extension)
{
// Get directory
QString pattern = QDir::tempPath();
if (!pattern.endsWith(QDir::separator()))
pattern.append(QDir::separator());
// Prefix, placeholder, extension
pattern += prefix;
pattern += QLatin1String("_XXXXXX.");
pattern += extension;
return pattern;
}
void CodepasterPlugin::finishFetch(const QString &titleDescription,
const QString &content,
bool error)
{
// Failure?
if (error) {
MessageManager::write(content);
return;
}
if (content.isEmpty()) {
MessageManager::write(tr("Empty snippet received for \"%1\".").arg(titleDescription));
return;
}
// If the mime type has a preferred suffix (cpp/h/patch...), use that for
// the temporary file. This is to make it more convenient to "Save as"
// for the user and also to be able to tell a patch or diff in the VCS plugins
// by looking at the file name of DocumentManager::currentFile() without expensive checking.
// Default to "txt".
QByteArray byteContent = content.toUtf8();
QString suffix;
if (const MimeType mimeType = MimeDatabase::findByData(byteContent))
suffix = mimeType.preferredSuffix();
if (suffix.isEmpty())
suffix = QLatin1String("txt");
const QString filePrefix = filePrefixFromTitle(titleDescription);
Utils::TempFileSaver saver(tempFilePattern(filePrefix, suffix));
saver.setAutoRemove(false);
saver.write(byteContent);
if (!saver.finalize()) {
MessageManager::write(saver.errorString());
return;
}
const QString fileName = saver.fileName();
m_fetchedSnippets.push_back(fileName);
// Open editor with title.
Core::IEditor *editor = EditorManager::openEditor(fileName);
QTC_ASSERT(editor, return);
editor->document()->setDisplayName(titleDescription);
}
CodepasterPlugin *CodepasterPlugin::instance()
{
return m_instance;
}
} // namespace CodePaster
Q_EXPORT_PLUGIN(CodePaster::CodepasterPlugin)
<commit_msg>Refactor text retrieval of the code paster plugin.<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "cpasterplugin.h"
#include "pasteview.h"
#include "kdepasteprotocol.h"
#include "pastebindotcomprotocol.h"
#include "pastebindotcaprotocol.h"
#include "fileshareprotocol.h"
#include "pasteselectdialog.h"
#include "settingspage.h"
#include "settings.h"
#include "urlopenprotocol.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/id.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <utils/qtcassert.h>
#include <utils/fileutils.h>
#include <texteditor/itexteditor.h>
#include <QtPlugin>
#include <QDebug>
#include <QDir>
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QInputDialog>
#include <QUrl>
using namespace Core;
using namespace TextEditor;
namespace CodePaster {
/*!
\class CodePaster::CodePasterService
\brief The CodePasterService class is a service registered with PluginManager
that provides CodePaster \c post() functionality.
\sa ExtensionSystem::PluginManager::getObjectByClassName, ExtensionSystem::invoke
\sa VcsBase::VcsBaseEditorWidget
*/
CodePasterService::CodePasterService(QObject *parent) :
QObject(parent)
{
}
void CodePasterService::postText(const QString &text, const QString &mimeType)
{
QTC_ASSERT(CodepasterPlugin::instance(), return);
CodepasterPlugin::instance()->post(text, mimeType);
}
void CodePasterService::postCurrentEditor()
{
QTC_ASSERT(CodepasterPlugin::instance(), return);
CodepasterPlugin::instance()->postEditor();
}
void CodePasterService::postClipboard()
{
QTC_ASSERT(CodepasterPlugin::instance(), return);
CodepasterPlugin::instance()->postClipboard();
}
// ---------- CodepasterPlugin
CodepasterPlugin *CodepasterPlugin::m_instance = 0;
CodepasterPlugin::CodepasterPlugin() :
m_settings(new Settings),
m_postEditorAction(0), m_postClipboardAction(0), m_fetchAction(0)
{
CodepasterPlugin::m_instance = this;
}
CodepasterPlugin::~CodepasterPlugin()
{
delete m_urlOpen;
qDeleteAll(m_protocols);
CodepasterPlugin::m_instance = 0;
}
bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
// Create the globalcontext list to register actions accordingly
Core::Context globalcontext(Core::Constants::C_GLOBAL);
// Create the settings Page
m_settings->fromSettings(Core::ICore::settings());
SettingsPage *settingsPage = new SettingsPage(m_settings);
addAutoReleasedObject(settingsPage);
// Create the protocols and append them to the Settings
Protocol *protos[] = { new PasteBinDotComProtocol,
new PasteBinDotCaProtocol,
new KdePasteProtocol,
new FileShareProtocol
};
const int count = sizeof(protos) / sizeof(Protocol *);
for (int i = 0; i < count; ++i) {
connect(protos[i], SIGNAL(pasteDone(QString)), this, SLOT(finishPost(QString)));
connect(protos[i], SIGNAL(fetchDone(QString,QString,bool)),
this, SLOT(finishFetch(QString,QString,bool)));
settingsPage->addProtocol(protos[i]->name());
if (protos[i]->hasSettings())
addAutoReleasedObject(protos[i]->settingsPage());
m_protocols.append(protos[i]);
}
m_urlOpen = new UrlOpenProtocol;
connect(m_urlOpen, SIGNAL(fetchDone(QString,QString,bool)),
this, SLOT(finishFetch(QString,QString,bool)));
//register actions
Core::ActionContainer *toolsContainer =
Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
Core::ActionContainer *cpContainer =
Core::ActionManager::createMenu("CodePaster");
cpContainer->menu()->setTitle(tr("&Code Pasting"));
toolsContainer->addMenu(cpContainer);
Core::Command *command;
m_postEditorAction = new QAction(tr("Paste Snippet..."), this);
command = Core::ActionManager::registerAction(m_postEditorAction, "CodePaster.Post", globalcontext);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+C,Meta+P") : tr("Alt+C,Alt+P")));
connect(m_postEditorAction, SIGNAL(triggered()), this, SLOT(postEditor()));
cpContainer->addAction(command);
m_postClipboardAction = new QAction(tr("Paste Clipboard..."), this);
command = Core::ActionManager::registerAction(m_postClipboardAction, "CodePaster.PostClipboard", globalcontext);
connect(m_postClipboardAction, SIGNAL(triggered()), this, SLOT(postClipboard()));
cpContainer->addAction(command);
m_fetchAction = new QAction(tr("Fetch Snippet..."), this);
command = Core::ActionManager::registerAction(m_fetchAction, "CodePaster.Fetch", globalcontext);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+C,Meta+F") : tr("Alt+C,Alt+F")));
connect(m_fetchAction, SIGNAL(triggered()), this, SLOT(fetch()));
cpContainer->addAction(command);
m_fetchUrlAction = new QAction(tr("Fetch from URL..."), this);
command = Core::ActionManager::registerAction(m_fetchUrlAction, "CodePaster.FetchUrl", globalcontext);
connect(m_fetchUrlAction, SIGNAL(triggered()), this, SLOT(fetchUrl()));
cpContainer->addAction(command);
addAutoReleasedObject(new CodePasterService);
return true;
}
void CodepasterPlugin::extensionsInitialized()
{
}
ExtensionSystem::IPlugin::ShutdownFlag CodepasterPlugin::aboutToShutdown()
{
// Delete temporary, fetched files
foreach (const QString &fetchedSnippet, m_fetchedSnippets) {
QFile file(fetchedSnippet);
if (file.exists())
file.remove();
}
return SynchronousShutdown;
}
void CodepasterPlugin::postEditor()
{
IEditor *editor = EditorManager::currentEditor();
if (!editor)
return;
const IDocument *document = editor->document();
const QString mimeType = document->mimeType();
QString data;
if (const ITextEditor *textEditor = qobject_cast<const ITextEditor *>(editor))
data = textEditor->selectedText();
if (data.isEmpty()) {
if (const ITextEditorDocument *textDocument = qobject_cast<const ITextEditorDocument *>(document))
data = textDocument->plainText();
}
post(data, mimeType);
}
void CodepasterPlugin::postClipboard()
{
QString subtype = QLatin1String("plain");
const QString text = qApp->clipboard()->text(subtype, QClipboard::Clipboard);
if (!text.isEmpty())
post(text, QString());
}
static inline void fixSpecialCharacters(QString &data)
{
QChar *uc = data.data();
QChar *e = uc + data.size();
for (; uc != e; ++uc) {
switch (uc->unicode()) {
case 0xfdd0: // QTextBeginningOfFrame
case 0xfdd1: // QTextEndOfFrame
case QChar::ParagraphSeparator:
case QChar::LineSeparator:
*uc = QLatin1Char('\n');
break;
case QChar::Nbsp:
*uc = QLatin1Char(' ');
break;
default:
break;
}
}
}
void CodepasterPlugin::post(QString data, const QString &mimeType)
{
fixSpecialCharacters(data);
const QString username = m_settings->username;
PasteView view(m_protocols, mimeType, ICore::dialogParent());
view.setProtocol(m_settings->protocol);
const FileDataList diffChunks = splitDiffToFiles(data);
const int dialogResult = diffChunks.isEmpty() ?
view.show(username, QString(), QString(), m_settings->expiryDays, data) :
view.show(username, QString(), QString(), m_settings->expiryDays, diffChunks);
// Save new protocol in case user changed it.
if (dialogResult == QDialog::Accepted
&& m_settings->protocol != view.protocol()) {
m_settings->protocol = view.protocol();
m_settings->toSettings(Core::ICore::settings());
}
}
void CodepasterPlugin::fetchUrl()
{
QUrl url;
do {
bool ok = true;
url = QUrl(QInputDialog::getText(ICore::dialogParent(), tr("Fetch from URL"), tr("Enter URL:"), QLineEdit::Normal, QString(), &ok));
if (!ok)
return;
} while (!url.isValid());
m_urlOpen->fetch(url.toString());
}
void CodepasterPlugin::fetch()
{
PasteSelectDialog dialog(m_protocols, ICore::dialogParent());
dialog.setProtocol(m_settings->protocol);
if (dialog.exec() != QDialog::Accepted)
return;
// Save new protocol in case user changed it.
if (m_settings->protocol != dialog.protocol()) {
m_settings->protocol = dialog.protocol();
m_settings->toSettings(Core::ICore::settings());
}
const QString pasteID = dialog.pasteId();
if (pasteID.isEmpty())
return;
Protocol *protocol = m_protocols[dialog.protocolIndex()];
if (Protocol::ensureConfiguration(protocol))
protocol->fetch(pasteID);
}
void CodepasterPlugin::finishPost(const QString &link)
{
if (m_settings->copyToClipboard)
QApplication::clipboard()->setText(link);
MessageManager::write(link, m_settings->displayOutput ? Core::MessageManager::ModeSwitch : Core::MessageManager::Silent);
}
// Extract the characters that can be used for a file name from a title
// "CodePaster.com-34" -> "CodePastercom34".
static inline QString filePrefixFromTitle(const QString &title)
{
QString rc;
const int titleSize = title.size();
rc.reserve(titleSize);
for (int i = 0; i < titleSize; i++)
if (title.at(i).isLetterOrNumber())
rc.append(title.at(i));
if (rc.isEmpty()) {
rc = QLatin1String("qtcreator");
} else {
if (rc.size() > 15)
rc.truncate(15);
}
return rc;
}
// Return a temp file pattern with extension or not
static inline QString tempFilePattern(const QString &prefix, const QString &extension)
{
// Get directory
QString pattern = QDir::tempPath();
if (!pattern.endsWith(QDir::separator()))
pattern.append(QDir::separator());
// Prefix, placeholder, extension
pattern += prefix;
pattern += QLatin1String("_XXXXXX.");
pattern += extension;
return pattern;
}
void CodepasterPlugin::finishFetch(const QString &titleDescription,
const QString &content,
bool error)
{
// Failure?
if (error) {
MessageManager::write(content);
return;
}
if (content.isEmpty()) {
MessageManager::write(tr("Empty snippet received for \"%1\".").arg(titleDescription));
return;
}
// If the mime type has a preferred suffix (cpp/h/patch...), use that for
// the temporary file. This is to make it more convenient to "Save as"
// for the user and also to be able to tell a patch or diff in the VCS plugins
// by looking at the file name of DocumentManager::currentFile() without expensive checking.
// Default to "txt".
QByteArray byteContent = content.toUtf8();
QString suffix;
if (const MimeType mimeType = MimeDatabase::findByData(byteContent))
suffix = mimeType.preferredSuffix();
if (suffix.isEmpty())
suffix = QLatin1String("txt");
const QString filePrefix = filePrefixFromTitle(titleDescription);
Utils::TempFileSaver saver(tempFilePattern(filePrefix, suffix));
saver.setAutoRemove(false);
saver.write(byteContent);
if (!saver.finalize()) {
MessageManager::write(saver.errorString());
return;
}
const QString fileName = saver.fileName();
m_fetchedSnippets.push_back(fileName);
// Open editor with title.
Core::IEditor *editor = EditorManager::openEditor(fileName);
QTC_ASSERT(editor, return);
editor->document()->setDisplayName(titleDescription);
}
CodepasterPlugin *CodepasterPlugin::instance()
{
return m_instance;
}
} // namespace CodePaster
Q_EXPORT_PLUGIN(CodePaster::CodepasterPlugin)
<|endoftext|> |
<commit_before>///
/// @file ParallelPrimeSieve.cpp
/// @brief Sieve primes in parallel using OpenMP.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <cstddef>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include <primesieve/ParallelPrimeSieve-lock.hpp>
#endif
using namespace std;
namespace primesieve {
ParallelPrimeSieve::ParallelPrimeSieve() :
lock_(NULL),
shm_(NULL),
numThreads_(IDEAL_NUM_THREADS)
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == IDEAL_NUM_THREADS)
return idealNumThreads();
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = threads;
if (numThreads_ != IDEAL_NUM_THREADS)
numThreads_ = getInBetween(1, numThreads_, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load
/// balance when using multiple threads.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
if (n == start_)
return start_;
uint64_t n32 = add_overflow_safe(n, 32);
if (n32 >= stop_)
return stop_;
n = n32 - n % 30;
return min(n, stop_);
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
uint64_t threadInterval = getInterval() / threads;
return (threads > 1 && threadInterval < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
double ParallelPrimeSieve::getWallTime() const
{
return omp_get_wtime();
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using OpenMP multi-threading.
///
void ParallelPrimeSieve::sieve()
{
reset();
if (start_ > stop_)
return;
OmpInitLock ompInit(&lock_);
int threads = getNumThreads();
if (tooMany(threads))
threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
uint64_t threadInterval = getThreadInterval(threads);
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
int64_t iters = 1 + (getInterval() - 1) / threadInterval;
double t1 = getWallTime();
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5)
for (int64_t i = 0; i < iters; i++)
{
uint64_t n = start_ + i * threadInterval;
uint64_t threadStart = align(n);
uint64_t threadStop = add_overflow_safe(n, threadInterval);
threadStop = align(threadStop);
PrimeSieve ps(*this, omp_get_thread_num());
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
}
seconds_ = getWallTime() - t1;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status.
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet())
{
PrimeSieve::updateStatus(processed, false);
if (shm_)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is disabled then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
if (shm_)
{
// communicate the sieving results to the
// primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
double ParallelPrimeSieve::getWallTime() const
{
return PrimeSieve::getWallTime();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
bool isUpdate = PrimeSieve::updateStatus(processed, waitForLock);
if (shm_)
shm_->status = getStatus();
return isUpdate;
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
} // namespace
<commit_msg>Fix integer overflow<commit_after>///
/// @file ParallelPrimeSieve.cpp
/// @brief Sieve primes in parallel using OpenMP.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/ParallelPrimeSieve.hpp>
#include <primesieve/PrimeSieve.hpp>
#include <primesieve/pmath.hpp>
#include <stdint.h>
#include <cstddef>
#include <cassert>
#include <algorithm>
#ifdef _OPENMP
#include <omp.h>
#include <primesieve/ParallelPrimeSieve-lock.hpp>
#endif
using namespace std;
namespace primesieve {
ParallelPrimeSieve::ParallelPrimeSieve() :
lock_(NULL),
shm_(NULL),
numThreads_(IDEAL_NUM_THREADS)
{ }
void ParallelPrimeSieve::init(SharedMemory& shm)
{
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
int ParallelPrimeSieve::getNumThreads() const
{
if (numThreads_ == IDEAL_NUM_THREADS)
return idealNumThreads();
return numThreads_;
}
void ParallelPrimeSieve::setNumThreads(int threads)
{
numThreads_ = threads;
if (numThreads_ != IDEAL_NUM_THREADS)
numThreads_ = getInBetween(1, numThreads_, getMaxThreads());
}
/// Get an ideal number of threads for the current
/// set start_ and stop_ numbers.
///
int ParallelPrimeSieve::idealNumThreads() const
{
if (start_ > stop_)
return 1;
uint64_t threshold = max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load
/// balance when using multiple threads.
///
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const
{
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = max(config::MIN_THREAD_INTERVAL, unbalanced);
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
/// Align n to modulo 30 + 2 to prevent prime k-tuplet
/// (twin primes, prime triplets, ...) gaps.
///
uint64_t ParallelPrimeSieve::align(uint64_t n) const
{
uint64_t n32 = add_overflow_safe(n, 32);
if (n32 >= stop_)
return stop_;
n = n32 - n % 30;
return min(n, stop_);
}
bool ParallelPrimeSieve::tooMany(int threads) const
{
uint64_t threadInterval = getInterval() / threads;
return (threads > 1 && threadInterval < config::MIN_THREAD_INTERVAL);
}
#ifdef _OPENMP
int ParallelPrimeSieve::getMaxThreads()
{
return omp_get_max_threads();
}
double ParallelPrimeSieve::getWallTime() const
{
return omp_get_wtime();
}
/// Sieve the primes and prime k-tuplets within [start_, stop_]
/// in parallel using OpenMP multi-threading.
///
void ParallelPrimeSieve::sieve()
{
reset();
if (start_ > stop_)
return;
OmpInitLock ompInit(&lock_);
int threads = getNumThreads();
if (tooMany(threads))
threads = idealNumThreads();
if (threads == 1)
PrimeSieve::sieve();
else
{
uint64_t threadInterval = getThreadInterval(threads);
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
int64_t iters = 1 + (getInterval() - 1) / threadInterval;
double t1 = getWallTime();
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5)
for (int64_t i = 0; i < iters; i++)
{
uint64_t threadStart = start_ + i * threadInterval;
uint64_t threadStop = add_overflow_safe(threadStart, threadInterval);
if (i > 0) threadStart = align(threadStart) + 1;
threadStop = align(threadStop);
PrimeSieve ps(*this, omp_get_thread_num());
ps.sieve(threadStart, threadStop);
count0 += ps.getCount(0);
count1 += ps.getCount(1);
count2 += ps.getCount(2);
count3 += ps.getCount(3);
count4 += ps.getCount(4);
count5 += ps.getCount(5);
}
seconds_ = getWallTime() - t1;
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
}
if (shm_)
{
// communicate the sieving results to
// the primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
/// Calculate the sieving status.
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
OmpLockGuard lock(getLock<omp_lock_t*>(), waitForLock);
if (lock.isSet())
{
PrimeSieve::updateStatus(processed, false);
if (shm_)
shm_->status = getStatus();
}
return lock.isSet();
}
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_set_lock(lock);
}
void ParallelPrimeSieve::unsetLock()
{
omp_lock_t* lock = getLock<omp_lock_t*>();
omp_unset_lock(lock);
}
#endif /* _OPENMP */
/// If OpenMP is disabled then ParallelPrimeSieve behaves like
/// the single threaded PrimeSieve.
///
#if !defined(_OPENMP)
int ParallelPrimeSieve::getMaxThreads()
{
return 1;
}
void ParallelPrimeSieve::sieve()
{
PrimeSieve::sieve();
if (shm_)
{
// communicate the sieving results to the
// primesieve GUI application
copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
double ParallelPrimeSieve::getWallTime() const
{
return PrimeSieve::getWallTime();
}
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock)
{
bool isUpdate = PrimeSieve::updateStatus(processed, waitForLock);
if (shm_)
shm_->status = getStatus();
return isUpdate;
}
void ParallelPrimeSieve::setLock() { }
void ParallelPrimeSieve::unsetLock() { }
#endif
} // namespace
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/properties/stringlistproperty.h>
#include <ghoul/lua/ghoul_lua.h>
#include <ghoul/misc/misc.h>
#include <numeric>
namespace {
std::vector<std::string> fromLuaConversion(lua_State* state, bool& success) {
if (!lua_istable(state, -1)) {
success = false;
return {};
}
std::vector<std::string> result;
lua_pushnil(state);
while (lua_next(state, -2) != 0) {
if (lua_isstring(state, -1)) {
result.push_back(lua_tostring(state, -1));
}
else {
success = false;
return {};
}
lua_pop(state, 1);
}
success = true;
return result;
}
bool toLuaConversion(lua_State* state, std::vector<std::string> val) {
lua_createtable(state, static_cast<int>(val.size()), 0);
int i = 1;
for (std::string& v : val) {
lua_pushstring(state, std::to_string(i).c_str());
lua_pushstring(state, v.c_str());
lua_settable(state, -3);
}
return true;
}
std::vector<std::string> fromStringConversion(std::string val, bool& success) {
std::vector<std::string> tokens = ghoul::tokenizeString(val, ',');
for (std::string& token : tokens) {
// Each incoming string is of the form "value"
// so we want to remove the leading and trailing " characters
if (token.size() > 2 && (token[0] == '"' && token[token.size() - 1] == '"')) {
token = token.substr(1, token.size() - 2);
}
}
success = true;
return tokens;
}
bool toStringConversion(std::string& outValue, std::vector<std::string> inValue) {
outValue = "";
for (const std::string& v : inValue) {
if (&v != &*inValue.cbegin()) {
outValue += ", " + v;
}
else {
outValue += v;
}
}
// outValue = std::accumulate(
// inValue.begin(),
// inValue.end(),
// std::string(""),
// [](std::string lhs, std::string rhs) {
// return lhs + "," + "\"" + rhs + "\"";
// }
// );
return true;
}
} // namespace
namespace openspace::properties {
REGISTER_TEMPLATEPROPERTY_SOURCE(
StringListProperty,
std::vector<std::string>,
std::vector<std::string>(),
fromLuaConversion,
toLuaConversion,
fromStringConversion,
toStringConversion,
LUA_TTABLE
)
} // namespace openspace::properties
<commit_msg>Fix error in Lua-serialization of StringListProperty<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2017 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/properties/stringlistproperty.h>
#include <ghoul/lua/ghoul_lua.h>
#include <ghoul/misc/misc.h>
#include <numeric>
namespace {
std::vector<std::string> fromLuaConversion(lua_State* state, bool& success) {
if (!lua_istable(state, -1)) {
success = false;
return {};
}
std::vector<std::string> result;
lua_pushnil(state);
while (lua_next(state, -2) != 0) {
if (lua_isstring(state, -1)) {
result.push_back(lua_tostring(state, -1));
}
else {
success = false;
return {};
}
lua_pop(state, 1);
}
success = true;
return result;
}
bool toLuaConversion(lua_State* state, std::vector<std::string> val) {
lua_createtable(state, static_cast<int>(val.size()), 0);
int i = 1;
for (std::string& v : val) {
lua_pushstring(state, std::to_string(i).c_str());
lua_pushstring(state, v.c_str());
lua_settable(state, -3);
++i;
}
return true;
}
std::vector<std::string> fromStringConversion(std::string val, bool& success) {
std::vector<std::string> tokens = ghoul::tokenizeString(val, ',');
for (std::string& token : tokens) {
// Each incoming string is of the form "value"
// so we want to remove the leading and trailing " characters
if (token.size() > 2 && (token[0] == '"' && token[token.size() - 1] == '"')) {
token = token.substr(1, token.size() - 2);
}
}
success = true;
return tokens;
}
bool toStringConversion(std::string& outValue, std::vector<std::string> inValue) {
outValue = "";
for (const std::string& v : inValue) {
if (&v != &*inValue.cbegin()) {
outValue += ", " + v;
}
else {
outValue += v;
}
}
// outValue = std::accumulate(
// inValue.begin(),
// inValue.end(),
// std::string(""),
// [](std::string lhs, std::string rhs) {
// return lhs + "," + "\"" + rhs + "\"";
// }
// );
return true;
}
} // namespace
namespace openspace::properties {
REGISTER_TEMPLATEPROPERTY_SOURCE(
StringListProperty,
std::vector<std::string>,
std::vector<std::string>(),
fromLuaConversion,
toLuaConversion,
fromStringConversion,
toStringConversion,
LUA_TTABLE
)
} // namespace openspace::properties
<|endoftext|> |
<commit_before>// ----------------------------------------------------------------------------
// ------------- AI Battleground, Copyright(C) Maciej Pryc, 2016 --------------
// ----------------------------------------------------------------------------
#include <iostream>
#include "LevelInfo.h"
#include "Actor.h"
#include "TextureManager.h"
LevelInfo::LevelInfo(class TextureManager* TexManager, const sf::FloatRect& LevelBoundaries) :
Boundaries(LevelBoundaries), RightBottomEdge(LevelBoundaries.left + LevelBoundaries.width, LevelBoundaries.top + LevelBoundaries.height)
{
const float InitialRectSize = 0.15f;
ETeam InitialTeam = ETeam::TEAM_A;
std::string TexName("RobotA");
Actor** ArrayToPopulate = ActorsTeamA;
sf::FloatRect RectToSpawnIn(Boundaries.left, Boundaries.top, Boundaries.width * InitialRectSize, Boundaries.height);
for (int i = 0; i < ACTORS_AMOUNT; ++i)
{
if (i == ACTORS_PER_TEAM_AMOUNT)
{
InitialTeam = ETeam::TEAM_B;
TexName = "RobotB";
ArrayToPopulate = ActorsTeamB;
RectToSpawnIn = sf::FloatRect(Boundaries.left + Boundaries.width * (1.0f - InitialRectSize), Boundaries.top, Boundaries.width * InitialRectSize, Boundaries.height);
}
Actors[i] = new Actor(this, TexManager, TexName, InitialTeam, GetRandomPointInRect(RectToSpawnIn));
ArrayToPopulate[i % ACTORS_PER_TEAM_AMOUNT] = Actors[i];
}
TexManager->InitTexture(&BackgroundSprite, "Background256", true);
BackgroundSprite.setTextureRect(sf::IntRect(0, 0, (int)Boundaries.width, (int)Boundaries.height));
BackgroundSprite.setPosition(sf::Vector2f(Boundaries.left, Boundaries.top));
}
LevelInfo::~LevelInfo()
{
for (int i = 0; i < ACTORS_AMOUNT; ++i)
delete Actors[i];
}
sf::Vector2f LevelInfo::GetRandomPointInRect(const sf::FloatRect& Rect)
{
return sf::Vector2f(Rect.left + GetRandomFloat(Rect.width), Rect.top + GetRandomFloat(Rect.height));
}
void LevelInfo::Draw(sf::RenderWindow* Window) const
{
Window->draw(BackgroundSprite);
for (const Actor* CurrActor : Actors)
CurrActor->Draw(Window);
}
void LevelInfo::Update(const float DeltaTime, const sf::Time MainTimeCounter)
{
static int LastIndex = 0;
int NewIndex = (int)(MainTimeCounter.asSeconds() * ACTORS_AMOUNT);
if (NewIndex < LastIndex)
NewIndex = ACTORS_AMOUNT;
for (int i = LastIndex; i < NewIndex; ++i)
{
Actor* CurrActor = Actors[i];
Actor* NearestOtherActor = nullptr;
float MinSquaredDist = 9999999.0f;
Actor** EnemyActors = CurrActor->GetTeam() == ETeam::TEAM_A ? ActorsTeamA : ActorsTeamB;
for (int j = 0; j < ACTORS_PER_TEAM_AMOUNT; ++j)
{
Actor* CurrEnemyActor = EnemyActors[j];
if (CurrEnemyActor != CurrActor)
{
const float SquaredDist = GetSquaredDist(CurrActor->GetPosition(), CurrEnemyActor->GetPosition());
if (SquaredDist < MinSquaredDist)
{
MinSquaredDist = SquaredDist;
NearestOtherActor = CurrEnemyActor;
}
}
}
if (NearestOtherActor)
CurrActor->SetNearestEnemy(NearestOtherActor);
}
LastIndex = NewIndex != ACTORS_AMOUNT ? NewIndex: 0;
for (Actor* CurrActor : Actors)
CurrActor->Update(DeltaTime);
}
<commit_msg>Fix, use actual opponents array.<commit_after>// ----------------------------------------------------------------------------
// ------------- AI Battleground, Copyright(C) Maciej Pryc, 2016 --------------
// ----------------------------------------------------------------------------
#include <iostream>
#include "LevelInfo.h"
#include "Actor.h"
#include "TextureManager.h"
LevelInfo::LevelInfo(class TextureManager* TexManager, const sf::FloatRect& LevelBoundaries) :
Boundaries(LevelBoundaries), RightBottomEdge(LevelBoundaries.left + LevelBoundaries.width, LevelBoundaries.top + LevelBoundaries.height)
{
const float InitialRectSize = 0.15f;
ETeam InitialTeam = ETeam::TEAM_A;
std::string TexName("RobotA");
Actor** ArrayToPopulate = ActorsTeamA;
sf::FloatRect RectToSpawnIn(Boundaries.left, Boundaries.top, Boundaries.width * InitialRectSize, Boundaries.height);
for (int i = 0; i < ACTORS_AMOUNT; ++i)
{
if (i == ACTORS_PER_TEAM_AMOUNT)
{
InitialTeam = ETeam::TEAM_B;
TexName = "RobotB";
ArrayToPopulate = ActorsTeamB;
RectToSpawnIn = sf::FloatRect(Boundaries.left + Boundaries.width * (1.0f - InitialRectSize), Boundaries.top, Boundaries.width * InitialRectSize, Boundaries.height);
}
Actors[i] = new Actor(this, TexManager, TexName, InitialTeam, GetRandomPointInRect(RectToSpawnIn));
ArrayToPopulate[i % ACTORS_PER_TEAM_AMOUNT] = Actors[i];
}
TexManager->InitTexture(&BackgroundSprite, "Background256", true);
BackgroundSprite.setTextureRect(sf::IntRect(0, 0, (int)Boundaries.width, (int)Boundaries.height));
BackgroundSprite.setPosition(sf::Vector2f(Boundaries.left, Boundaries.top));
}
LevelInfo::~LevelInfo()
{
for (int i = 0; i < ACTORS_AMOUNT; ++i)
delete Actors[i];
}
sf::Vector2f LevelInfo::GetRandomPointInRect(const sf::FloatRect& Rect)
{
return sf::Vector2f(Rect.left + GetRandomFloat(Rect.width), Rect.top + GetRandomFloat(Rect.height));
}
void LevelInfo::Draw(sf::RenderWindow* Window) const
{
Window->draw(BackgroundSprite);
for (const Actor* CurrActor : Actors)
CurrActor->Draw(Window);
}
void LevelInfo::Update(const float DeltaTime, const sf::Time MainTimeCounter)
{
static int LastIndex = 0;
int NewIndex = (int)(MainTimeCounter.asSeconds() * ACTORS_AMOUNT);
if (NewIndex < LastIndex)
NewIndex = ACTORS_AMOUNT;
for (int i = LastIndex; i < NewIndex; ++i)
{
Actor* CurrActor = Actors[i];
Actor* NearestOtherActor = nullptr;
float MinSquaredDist = 9999999.0f;
Actor** EnemyActors = CurrActor->GetTeam() == ETeam::TEAM_A ? ActorsTeamB : ActorsTeamA;
for (int j = 0; j < ACTORS_PER_TEAM_AMOUNT; ++j)
{
Actor* CurrEnemyActor = EnemyActors[j];
if (CurrEnemyActor != CurrActor)
{
const float SquaredDist = GetSquaredDist(CurrActor->GetPosition(), CurrEnemyActor->GetPosition());
if (SquaredDist < MinSquaredDist)
{
MinSquaredDist = SquaredDist;
NearestOtherActor = CurrEnemyActor;
}
}
}
if (NearestOtherActor)
CurrActor->SetNearestEnemy(NearestOtherActor);
}
LastIndex = NewIndex != ACTORS_AMOUNT ? NewIndex: 0;
for (Actor* CurrActor : Actors)
CurrActor->Update(DeltaTime);
}
<|endoftext|> |
<commit_before>// QS4 Algorithm for Milloion Queen Problem
// Created by Shengjia Yan@2016-5-23
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
#define TIMES 10 // 运行次数
#define ll long long int
#define LOCATION 0 // 输出 N 皇后的位置
#define CODE 0 // 输出 N 皇后的编码
const int C[]={30,50,80,100};
ll n = 10000; // 皇后数量
#if LOCATION
FILE *out0=fopen("million_queen_location.txt","w"); // 保存符合条件的 N 皇后的位置
#endif
#if CODE
FILE *out1=fopen("million_queen_code.txt","w"); // 保存符合条件的 N 皇后的编码
#endif
ll m; // 不冲突的皇后数量
int step; // 步数
clock_t start, finish; // 计时
// 冲突的皇后数量
int conflict(ll n)
{
if(n<=10) return (n>8) ? 8 : n;
else if (n<100) return n;
else if (n<1000) return C[0];
else if (n<10000) return C[1];
else if (n<100000) return C[2];
else return C[3];
}
int main()
{
cout<<"Enter the number of queens: ";
cin>>n;
double totaltime, sumtime = 0;
void QS4();
m = n - conflict(n); // m 是不冲突的皇后数
for(int run = 0; run < TIMES; run++)
{
#if LOCATION
fprintf(out0, "%d\n", run+1);
#endif
#if CODE
fprintf(out1, "%d\n", run+1);
#endif
start = clock(); // 计时开始
cout<<"Round: "<<run+1<<" n = "<<n<<" m = "<<m<<endl;
QS4();
finish = clock();
totaltime = (double)(finish - start)/CLOCKS_PER_SEC;
sumtime += totaltime;
cout<<"Total Time: "<<totaltime<<endl;
cout<<"Total Step: "<<step<<endl<<endl;
}
cout<<"Average Time:"<<sumtime/TIMES<<endl;
#if LOCATION
fclose(out0);
#endif
#if CODE
fclose(out1);
#endif
}
unsigned ll RandSeed = (unsigned)time(NULL);
unsigned ll BRandom(ll max)
{
unsigned ll x ;
double i ;
x = 0x7fffffff;
x += 1;
RandSeed *= ((unsigned ll)134775813);
RandSeed += 1;
RandSeed = RandSeed % x;
i = ((double)RandSeed) / (double)0x7fffffff;
return (unsigned ll)(max * i);
}
void swap(ll &a, ll &b)
{
if (a!=b)
{
ll t;
t = a;
a = b;
b = t;
}
}
// 皇后的初始化
void init_4(ll queen[], ll n, ll m, ll b[], ll c[])
{
ll i, last;
ll z;
bool *bb = (bool*)malloc(sizeof(bool) * (n+n)); // 维护对角线上的冲突情况
bool *cc = (bool*)malloc(sizeof(bool) * (n+n)); // 维护对角线上的冲突情况
for( i = 0; i < n; i++ )
{
b[i] = 0;
c[i] = 0;
bb[i] = false;
cc[i] = false;
queen[i] = i;
}
for( i = n; i < n+n; i++ )
{
b[i] = 0;
c[i] = 0;
bb[i] = false;
cc[i] = false;
}
for( i = 0,last = n; i < m; i++,last--)
{
do
{
z = i + BRandom(last); //BRandom: an random integer in [0,last)
}
while ( bb[i-queen[z]+n-1] || cc[i+queen[z]] );
swap(queen[i], queen[z]);
b[i-queen[i]+n-1]++;
c[i+queen[i]]++;
bb[i-queen[i]+n-1] = true;
cc[i+queen[i]] = true;
}
for( i = m, last = n-m; i < n; i++, last--)
{
z = i + BRandom(last);
swap(queen[i], queen[z]);
b[i-queen[i]+n-1]++;
c[i+queen[i]]++;
}
free(bb);
free(cc);
}
ll sum(const ll queen[], const ll n, const ll b[], const ll c[])
{
ll ans = 0;
ll i;
for (i = 0; i < n+n; i++)
{
if (b[i] > 1)
ans += b[i] * (b[i]-1)/2;
if (c[i] > 1)
ans += c[i] * (c[i]-1)/2;
}
return ans;
}
ll delta(ll i, ll j, ll b[], ll c[], const ll q[]/*queen*/, ll n)
{
ll ans = 0;
ans += 1 - b[i-q[i]+n-1];
ans += 1 - c[i+q[i]];
ans += 1 - b[j-q[j]+n-1];
ans += 1 - c[j+q[j]];
ans += b[j-q[i]+n-1];
ans += c[j+q[i]];
ans += b[i-q[j]+n-1];
ans += c[i+q[j]];
if ( (i+q[i]==j+q[j]) || (i-q[i]==j-q[j]) ) // 在同一斜线上
ans += 2;
return ans;
}
// Queen Search 4 Algorithm
void QS4()
{
ll t; //current conflicts
ll temp; //delta conflicts
ll i,j;
ll* queen = (ll*)malloc( sizeof(ll) * n); // 皇后的解
ll* b = (ll*)malloc( sizeof(ll) * (n+n) ); // 维护对角线上的冲突数
ll* c = (ll*)malloc( sizeof(ll) * (n+n) ); // 维护对角线上的冲突数
init_4(queen,n,m,b,c);
finish = clock();
cout<<"Init Time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
t = sum(queen,n,b,c);
step = 0;
cout<<"Confilicts: "<<t<<endl;
while (t>0)
{
temp = 0;
for (i = m; i < n; i++)
if ((b[i-queen[i]+n-1]==1) && (c[i+queen[i]]==1)) continue;
else
{
for (j = 0; j < n; j++)
if(i!=j)
{
temp = delta(i,j,b,c,queen,n);
if (temp < 0) break;
}
if (temp < 0) break;
}
if (temp < 0)
{
step++;
b[i-queen[i]+n-1]--;
c[i+queen[i]]--;
b[j-queen[j]+n-1]--;
c[j+queen[j]]--;
swap(queen[i], queen[j]);
b[i-queen[i]+n-1]++;
c[i+queen[i]]++;
b[j-queen[j]+n-1]++;
c[j+queen[j]]++;
t += temp;
}
else
{
finish = clock();
cout<<"Time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
cout<<"Reinitialize..."<<endl;
init_4(queen,n,m,b,c);
finish = clock();
cout<<"Init Time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
t = sum(queen,n,b,c);
cout<<"Confilicts: "<<t<<endl;
}
}
#if LOCATION
// 将符合条件 N 皇后的位置输出到文件
for (i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(j == queen[i]) fprintf(out0, "Q\t");
else fprintf(out0, ".\t");
}
fprintf(out0, "\n");
}
fprintf(out0, "\n\n");
#endif
#if CODE
// 将符合条件 N 皇后的编码输出到文件
for (i = 0; i < n; i++) fprintf(out1, "%lld\t", queen[i]);
fprintf(out1, "\n\n");
#endif
free(queen);
free(b);
free(c);
}
<commit_msg>Update<commit_after>// QS4 Algorithm for Milloion Queen Problem
// Created by Shengjia Yan@2016-5-23
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
#define TIMES 10 // 运行次数
#define ll long long int
#define LOCATION 0 // 输出 N 皇后的位置
#define CODE 0 // 输出 N 皇后的编码
const int C[]={30,50,80,100};
ll n = 3000000; // 皇后数量
#if LOCATION
FILE *out0=fopen("million_queen_location.txt","w"); // 保存符合条件的 N 皇后的位置
#endif
#if CODE
FILE *out1=fopen("million_queen_code.txt","w"); // 保存符合条件的 N 皇后的编码
#endif
ll m; // 不冲突的皇后数量
int step; // 步数
clock_t start, finish; // 计时
// 冲突的皇后数量
int conflict(ll n)
{
if(n<=10) return (n>8) ? 8 : n;
else if (n<100) return n;
else if (n<1000) return C[0];
else if (n<10000) return C[1];
else if (n<100000) return C[2];
else return C[3];
}
int main()
{
cout<<"Enter the number of queens: ";
cin>>n;
double totaltime, sumtime = 0;
void QS4();
m = n - conflict(n); // m 是不冲突的皇后数
for(int run = 0; run < TIMES; run++)
{
#if LOCATION
fprintf(out0, "%d\n", run+1);
#endif
#if CODE
fprintf(out1, "%d\n", run+1);
#endif
start = clock(); // 计时开始
cout<<"Round: "<<run+1<<" n = "<<n<<" m = "<<m<<endl;
QS4();
finish = clock();
totaltime = (double)(finish - start)/CLOCKS_PER_SEC;
sumtime += totaltime;
cout<<"Total Time: "<<totaltime<<endl;
cout<<"Total Step: "<<step<<endl<<endl;
}
cout<<"Average Time:"<<sumtime/TIMES<<endl;
#if LOCATION
fclose(out0);
#endif
#if CODE
fclose(out1);
#endif
}
unsigned ll RandSeed = (unsigned)time(NULL);
unsigned ll BRandom(ll max)
{
unsigned ll x ;
double i ;
x = 0x7fffffff;
x += 1;
RandSeed *= ((unsigned ll)134775813);
RandSeed += 1;
RandSeed = RandSeed % x;
i = ((double)RandSeed) / (double)0x7fffffff;
return (unsigned ll)(max * i);
}
void swap(ll &a, ll &b)
{
if (a!=b)
{
ll t;
t = a;
a = b;
b = t;
}
}
// 皇后的初始化
void init_4(ll queen[], ll n, ll m, ll b[], ll c[])
{
ll i, last;
ll z;
bool *bb = (bool*)malloc(sizeof(bool) * (n+n)); // 维护对角线上的冲突情况
bool *cc = (bool*)malloc(sizeof(bool) * (n+n)); // 维护对角线上的冲突情况
for( i = 0; i < n; i++ )
{
b[i] = 0;
c[i] = 0;
bb[i] = false;
cc[i] = false;
queen[i] = i;
}
for( i = n; i < n+n; i++ )
{
b[i] = 0;
c[i] = 0;
bb[i] = false;
cc[i] = false;
}
for( i = 0,last = n; i < m; i++,last--)
{
do
{
z = i + BRandom(last); //BRandom: an random integer in [0,last)
}
while ( bb[i-queen[z]+n-1] || cc[i+queen[z]] );
swap(queen[i], queen[z]);
b[i-queen[i]+n-1]++;
c[i+queen[i]]++;
bb[i-queen[i]+n-1] = true;
cc[i+queen[i]] = true;
}
for( i = m, last = n-m; i < n; i++, last--)
{
z = i + BRandom(last);
swap(queen[i], queen[z]);
b[i-queen[i]+n-1]++;
c[i+queen[i]]++;
}
free(bb);
free(cc);
}
ll sum(const ll queen[], const ll n, const ll b[], const ll c[])
{
ll ans = 0;
ll i;
for (i = 0; i < n+n; i++)
{
if (b[i] > 1)
ans += b[i] * (b[i]-1)/2;
if (c[i] > 1)
ans += c[i] * (c[i]-1)/2;
}
return ans;
}
ll delta(ll i, ll j, ll b[], ll c[], const ll q[]/*queen*/, ll n)
{
ll ans = 0;
ans += 1 - b[i-q[i]+n-1];
ans += 1 - c[i+q[i]];
ans += 1 - b[j-q[j]+n-1];
ans += 1 - c[j+q[j]];
ans += b[j-q[i]+n-1];
ans += c[j+q[i]];
ans += b[i-q[j]+n-1];
ans += c[i+q[j]];
if ( (i+q[i]==j+q[j]) || (i-q[i]==j-q[j]) ) // 在同一斜线上
ans += 2;
return ans;
}
// Queen Search 4 Algorithm
void QS4()
{
ll t; //current conflicts
ll temp; //delta conflicts
ll i,j;
ll* queen = (ll*)malloc( sizeof(ll) * n); // 皇后的解
ll* b = (ll*)malloc( sizeof(ll) * (n+n) ); // 维护对角线上的冲突数
ll* c = (ll*)malloc( sizeof(ll) * (n+n) ); // 维护对角线上的冲突数
init_4(queen,n,m,b,c);
finish = clock();
cout<<"Init Time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
t = sum(queen,n,b,c);
step = 0;
cout<<"Confilicts: "<<t<<endl;
while (t>0)
{
temp = 0;
for (i = m; i < n; i++)
if ((b[i-queen[i]+n-1]==1) && (c[i+queen[i]]==1)) continue;
else
{
for (j = 0; j < n; j++)
if(i!=j)
{
temp = delta(i,j,b,c,queen,n);
if (temp < 0) break;
}
if (temp < 0) break;
}
if (temp < 0)
{
step++;
b[i-queen[i]+n-1]--;
c[i+queen[i]]--;
b[j-queen[j]+n-1]--;
c[j+queen[j]]--;
swap(queen[i], queen[j]);
b[i-queen[i]+n-1]++;
c[i+queen[i]]++;
b[j-queen[j]+n-1]++;
c[j+queen[j]]++;
t += temp;
}
else
{
finish = clock();
cout<<"Time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
cout<<"Reinitialize..."<<endl;
init_4(queen,n,m,b,c);
finish = clock();
cout<<"Init Time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
t = sum(queen,n,b,c);
cout<<"Confilicts: "<<t<<endl;
}
}
#if LOCATION
// 将符合条件 N 皇后的位置输出到文件
for (i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(j == queen[i]) fprintf(out0, "Q\t");
else fprintf(out0, ".\t");
}
fprintf(out0, "\n");
}
fprintf(out0, "\n\n");
#endif
#if CODE
// 将符合条件 N 皇后的编码输出到文件
for (i = 0; i < n; i++) fprintf(out1, "%lld\t", queen[i]);
fprintf(out1, "\n\n");
#endif
free(queen);
free(b);
free(c);
}
<|endoftext|> |
<commit_before>#include "common.th"
_start:
prologue
#define DATA_LEN (.L_data_end - .L_data_start)
#define ELT_LEN (.L_data_elt_end - .L_data_elt_start)
c <- rel(key) // needle
d <- rel(data_start) // haystack
e <- (DATA_LEN / ELT_LEN) // number of elements
f <- ELT_LEN // size of each element
g <- rel(inteq) // comparator
call(bsearch)
c <- b == 0
jnzrel(c,notfound)
c <- [b + 1]
c <- c - (. + 1) + p // relocate string address argument
goto(done)
notfound:
c <- rel(error_msg)
done:
call(puts)
c <- rel(nl)
call(puts)
illegal
error_msg:
.utf32 "error : not found" ; .word 0
nl: .word '\n', 0
key: .word 55
// c <- key
// d <- base
// e <- number of elements
// f <- size of element
// g <- comparator
// b -> pointer or null
bsearch:
pushall(h,i,j) // callee-save temps
bsearch_loop:
// c is the key ptr
// d is the first element to consider
// e is the number of elements to consider after d
i <- e == 0
jnzrel(i,bsearch_notfound)
pushall(c,d,e,f)
// consider element halfway between (d) and (d + e)
i <- e >> 1
i <- i * f
d <- d + i
push(d) // save testpointer
callr(g)
i <- b // copy result to temp
pop(b) // restore testpointer to b in case of match
popall(c,d,e,f)
j <- i == 0
jnzrel(j,bsearch_done)
j <- i < 0
jnzrel(j,bsearch_less)
e <- e + 1
e <- e >> 1
j <- e * f
d <- d + j
goto(bsearch_loop)
bsearch_less:
e <- e >> 1
goto(bsearch_loop)
bsearch_notfound:
b <- 0
goto(bsearch_done)
bsearch_done:
popall(h,i,j)
ret
// c <- pointer to key
// d <- pointer to element
// b -> < 0, 0, > 0
inteq:
c <- [c]
d <- [d]
b <- c - d
ret
data_start:
.L_data_start:
.L_data_elt_start:
.word 1, @L_1
.L_data_elt_end:
.word 2, @L_2
.word 3, @L_3
.word 5, @L_5
.word 8, @L_8
.word 13, @L_13
.word 21, @L_21
.word 34, @L_34
.word 55, @L_55
.word 89, @L_89
.word 144, @L_144
.L_data_end:
.word 0
L_1 : .utf32 "one" ; .word 0
L_2 : .utf32 "two" ; .word 0
L_3 : .utf32 "three" ; .word 0
L_5 : .utf32 "five" ; .word 0
L_8 : .utf32 "eight" ; .word 0
L_13 : .utf32 "thirteen" ; .word 0
L_21 : .utf32 "twenty-one" ; .word 0
L_34 : .utf32 "thirty-four" ; .word 0
L_55 : .utf32 "fifty-five" ; .word 0
L_89 : .utf32 "eighty-nine" ; .word 0
L_144: .utf32 "one hundred forty-four" ; .word 0
<commit_msg>Put data at end of object<commit_after>#include "common.th"
_start:
prologue
#define DATA_LEN (.L_data_end - .L_data_start)
#define ELT_LEN (.L_data_elt_end - .L_data_elt_start)
c <- rel(key) // needle
d <- rel(data_start) // haystack
e <- (DATA_LEN / ELT_LEN) // number of elements
f <- ELT_LEN // size of each element
g <- rel(inteq) // comparator
call(bsearch)
c <- b == 0
jnzrel(c,notfound)
c <- [b + 1]
c <- c - (. + 1) + p // relocate string address argument
goto(done)
notfound:
c <- rel(error_msg)
done:
call(puts)
c <- rel(nl)
call(puts)
illegal
// c <- key
// d <- base
// e <- number of elements
// f <- size of element
// g <- comparator
// b -> pointer or null
bsearch:
pushall(h,i,j) // callee-save temps
bsearch_loop:
// c is the key ptr
// d is the first element to consider
// e is the number of elements to consider after d
i <- e == 0
jnzrel(i,bsearch_notfound)
pushall(c,d,e,f)
// consider element halfway between (d) and (d + e)
i <- e >> 1
i <- i * f
d <- d + i
push(d) // save testpointer
callr(g)
i <- b // copy result to temp
pop(b) // restore testpointer to b in case of match
popall(c,d,e,f)
j <- i == 0
jnzrel(j,bsearch_done)
j <- i < 0
jnzrel(j,bsearch_less)
e <- e + 1
e <- e >> 1
j <- e * f
d <- d + j
goto(bsearch_loop)
bsearch_less:
e <- e >> 1
goto(bsearch_loop)
bsearch_notfound:
b <- 0
goto(bsearch_done)
bsearch_done:
popall(h,i,j)
ret
// c <- pointer to key
// d <- pointer to element
// b -> < 0, 0, > 0
inteq:
c <- [c]
d <- [d]
b <- c - d
ret
error_msg:
.utf32 "error : not found" ; .word 0
nl: .word '\n', 0
key: .word 55
data_start:
.L_data_start:
.L_data_elt_start:
.word 1, @L_1
.L_data_elt_end:
.word 2, @L_2
.word 3, @L_3
.word 5, @L_5
.word 8, @L_8
.word 13, @L_13
.word 21, @L_21
.word 34, @L_34
.word 55, @L_55
.word 89, @L_89
.word 144, @L_144
.L_data_end:
.word 0
L_1 : .utf32 "one" ; .word 0
L_2 : .utf32 "two" ; .word 0
L_3 : .utf32 "three" ; .word 0
L_5 : .utf32 "five" ; .word 0
L_8 : .utf32 "eight" ; .word 0
L_13 : .utf32 "thirteen" ; .word 0
L_21 : .utf32 "twenty-one" ; .word 0
L_34 : .utf32 "thirty-four" ; .word 0
L_55 : .utf32 "fifty-five" ; .word 0
L_89 : .utf32 "eighty-nine" ; .word 0
L_144: .utf32 "one hundred forty-four" ; .word 0
<|endoftext|> |
<commit_before>/** -*- c++ -*-
*
* \file pool_layer.cpp
* \date Sat May 14 11:35:13 2016
*
* \copyright
* Copyright (c) 2016 Liangfu Chen <liangfu.chen@nlpr.ia.ac.cn>.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the Brainnetome Center & NLPR at Institute of Automation, CAS. The
* name of the Brainnetome Center & NLPR at Institute of Automation, CAS
* may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* \brief max-pooling layer
*/
#include "_dnn.h"
/*************************************************************************/
ML_IMPL CvCNNLayer* cvCreateCNNSubSamplingLayer(
const int dtype, const char * name, const int visualize,
int n_input_planes, int input_height, int input_width,
int sub_samp_scale,
float init_learn_rate, int learn_rate_decrease_type, CvMat* weights )
{
CvCNNSubSamplingLayer* layer = 0;
CV_FUNCNAME("cvCreateCNNSubSamplingLayer");
__BEGIN__;
const int output_height = input_height/sub_samp_scale;
const int output_width = input_width/sub_samp_scale;
const int n_output_planes = n_input_planes;
fprintf(stderr,"SubSamplingLayer(%s): input (%d@%dx%d), output (%d@%dx%d)\n", name,
n_input_planes,input_width,input_height,n_output_planes,output_width,output_height);
if ( sub_samp_scale < 1 )
CV_ERROR( CV_StsBadArg, "Incorrect parameters" );
CV_CALL(layer = (CvCNNSubSamplingLayer*)icvCreateCNNLayer(
ICV_CNN_SUBSAMPLING_LAYER, dtype, name, sizeof(CvCNNSubSamplingLayer),
n_input_planes, input_height, input_width,
n_output_planes, output_height, output_width,
init_learn_rate, learn_rate_decrease_type,
icvCNNSubSamplingRelease, icvCNNSubSamplingForward, icvCNNSubSamplingBackward ));
layer->sub_samp_scale = sub_samp_scale;
layer->visualize = visualize;
layer->mask = 0;
CV_CALL(layer->sumX =
cvCreateMat( n_output_planes*output_width*output_height, 1, CV_32FC1 ));
CV_CALL(layer->WX =
cvCreateMat( n_output_planes*output_width*output_height, 1, CV_32FC1 ));
cvZero( layer->sumX );
cvZero( layer->WX );
CV_CALL(layer->weights = cvCreateMat( n_output_planes, 2, CV_32FC1 ));
if ( weights )
{
if ( !ICV_IS_MAT_OF_TYPE( weights, CV_32FC1 ) )
CV_ERROR( CV_StsBadSize, "Type of initial weights matrix must be CV_32FC1" );
if ( !CV_ARE_SIZES_EQ( weights, layer->weights ) )
CV_ERROR( CV_StsBadSize, "Invalid size of initial weights matrix" );
CV_CALL(cvCopy( weights, layer->weights ));
}
else
{
CvRNG rng = cvRNG( 0xFFFFFFFF );
cvRandArr( &rng, layer->weights, CV_RAND_UNI, cvRealScalar(-1), cvRealScalar(1) );
}
__END__;
if ( cvGetErrStatus() < 0 && layer )
{
cvReleaseMat( &layer->WX );
cvFree( &layer );
}
return (CvCNNLayer*)layer;
}
void icvCNNSubSamplingForward( CvCNNLayer* _layer, const CvMat* X, CvMat* Y )
{
CV_FUNCNAME("icvCNNSubSamplingForward");
if ( !icvIsCNNSubSamplingLayer(_layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
__BEGIN__;
CvCNNSubSamplingLayer * layer = (CvCNNSubSamplingLayer*) _layer;
CvMat * Xt = 0;
CvMat * Yt = 0;
const int stride_size = layer->sub_samp_scale;
const int nsamples = X->cols; // batch size for training
const int nplanes = layer->n_input_planes;
const int Xheight = layer->input_height;
const int Xwidth = layer->input_width ;
const int Xsize = Xwidth*Xheight;
const int Yheight = layer->output_height;
const int Ywidth = layer->output_width;
const int Ysize = Ywidth*Yheight;
const int batch_size = X->cols;
int xx, yy, ni, kx, ky;
float* sumX_data = 0, *w = 0;
CvMat sumX_sub_col, WX_sub_col;
CV_ASSERT(X->rows == nplanes*Xsize && X->cols == nsamples);
CV_ASSERT(Y->cols == nsamples);
CV_ASSERT((layer->WX->cols == 1) &&
(layer->WX->rows == nplanes*Ysize));
CV_CALL(layer->mask = cvCreateMat(Ysize*nplanes, batch_size, CV_32S));
// update inner variable used in back-propagation
cvZero( layer->sumX );
cvZero( layer->WX );
cvZero( layer->mask );
int * mptr = layer->mask->data.i;
CV_ASSERT(Xheight==Yheight*stride_size && Xwidth ==Ywidth *stride_size);
CV_ASSERT(Y->rows==layer->mask->rows && Y->cols==layer->mask->cols);
CV_ASSERT(CV_MAT_TYPE(layer->mask->type)==CV_32S);
Xt = cvCreateMat(X->cols,X->rows,CV_32F); cvTranspose(X,Xt);
Yt = cvCreateMat(Y->cols,Y->rows,CV_32F); cvTranspose(Y,Yt);
for ( int si = 0; si < nsamples; si++ ){
float * xptr = Xt->data.fl+Xsize*nplanes*si;
float * yptr = Yt->data.fl+Ysize*nplanes*si;
for ( ni = 0; ni < nplanes; ni++ ){
for ( yy = 0; yy < Yheight; yy++ ){
for ( xx = 0; xx < Ywidth; xx++ ){
float maxval = *xptr;
int maxloc = 0;
for ( ky = 0; ky < stride_size; ky++ ){
for ( kx = 0; kx < stride_size; kx++ ){
if ((xptr+stride_size*xx+Xwidth*ky)[kx]>maxval) {
maxval = (xptr+stride_size*xx+Xwidth*ky)[kx];
maxloc = ky*stride_size + kx;
}
} // kx
} // ky
yptr[xx] = maxval;
mptr[xx] = maxloc;
} // xx
xptr += Xwidth*stride_size;
yptr += Ywidth;
mptr += Ywidth;
} // yy
} // ni
} // si
cvTranspose(Yt,Y);
cvReleaseMat(&Xt);
cvReleaseMat(&Yt);
if (layer->Y){cvCopy(Y,layer->Y);}else{layer->Y=cvCloneMat(Y);}
if (layer->visualize){icvVisualizeCNNLayer((CvCNNLayer*)layer,Y);}
__END__;
}
void icvCNNSubSamplingBackward(
CvCNNLayer* _layer, int t, const CvMat* X, const CvMat* dE_dY, CvMat* dE_dX )
{
// derivative of activation function
CvMat* dY_dX_elems = 0; // elements of matrix dY_dX
CvMat* dY_dW_elems = 0; // elements of matrix dY_dW
CvMat* dE_dW = 0;
CV_FUNCNAME("icvCNNSubSamplingBackward");
if ( !icvIsCNNSubSamplingLayer(_layer) ) {
CV_ERROR( CV_StsBadArg, "Invalid layer" );
}
__BEGIN__;
CvCNNSubSamplingLayer* layer = (CvCNNSubSamplingLayer*) _layer;
const int Xwidth = layer->input_width;
const int Xheight = layer->input_height;
const int Ywidth = layer->output_width;
const int Yheight = layer->output_height;
const int Xsize = Xwidth * Xheight;
const int Ysize = Ywidth * Yheight;
const int scale = layer->sub_samp_scale;
const int k_max = layer->n_output_planes * Yheight;
int k, i, j, m;
CV_ASSERT(CV_MAT_TYPE(layer->mask->type)==CV_32S);
CV_ASSERT(dE_dX->rows*dE_dX->cols==X->rows*X->cols);
int nplanes = layer->n_output_planes;
int nsamples = X->cols;
int stride_size = layer->sub_samp_scale;
CvMat * maskT = cvCreateMat(dE_dY->rows,dE_dY->cols,CV_32S);
cvTranspose(layer->mask,maskT);
cvZero(dE_dX);
for ( int si = 0; si < nsamples; si++ ){
float * dxptr = dE_dX->data.fl+dE_dX->cols*si;
float * dyptr = dE_dY->data.fl+dE_dY->cols*si;
int * mptr = maskT->data.i;
for ( int ni = 0; ni < nplanes; ni++ ){
for ( int yy = 0; yy < Yheight; yy++ ){
for ( int xx = 0; xx < Ywidth; xx++ ){
int maxloc = mptr[xx];
int ky = maxloc / stride_size;
int kx = maxloc % stride_size;
(dxptr+stride_size*xx+Xwidth*ky)[kx]=dyptr[xx];
}
dxptr += Xwidth*stride_size;
dyptr += Ywidth;
mptr += Ywidth;
}
}
}
cvReleaseMat(&maskT);
if (layer->mask){cvReleaseMat(&layer->mask);layer->mask=0;}
__END__;
if (dY_dX_elems){cvReleaseMat( &dY_dX_elems );dY_dX_elems=0;}
if (dY_dW_elems){cvReleaseMat( &dY_dW_elems );dY_dW_elems=0;}
if (dE_dW ){cvReleaseMat( &dE_dW );dE_dW =0;}
}
void icvCNNSubSamplingRelease( CvCNNLayer** p_layer )
{
CV_FUNCNAME("icvCNNSubSamplingRelease");
__BEGIN__;
CvCNNSubSamplingLayer* layer = 0;
if ( !p_layer )
CV_ERROR( CV_StsNullPtr, "Null double pointer" );
layer = *(CvCNNSubSamplingLayer**)p_layer;
if ( !layer )
return;
if ( !icvIsCNNSubSamplingLayer((CvCNNLayer*)layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
if (layer->mask ){cvReleaseMat( &layer->mask ); layer->mask =0;}
if (layer->WX){cvReleaseMat( &layer->WX ); layer->WX=0;}
if (layer->weights ){cvReleaseMat( &layer->weights ); layer->weights =0;}
cvFree( p_layer );
__END__;
}
<commit_msg>bug fix in computing first maxval;<commit_after>/** -*- c++ -*-
*
* \file pool_layer.cpp
* \date Sat May 14 11:35:13 2016
*
* \copyright
* Copyright (c) 2016 Liangfu Chen <liangfu.chen@nlpr.ia.ac.cn>.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the Brainnetome Center & NLPR at Institute of Automation, CAS. The
* name of the Brainnetome Center & NLPR at Institute of Automation, CAS
* may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* \brief max-pooling layer
*/
#include "_dnn.h"
/*************************************************************************/
ML_IMPL CvCNNLayer* cvCreateCNNSubSamplingLayer(
const int dtype, const char * name, const int visualize,
int n_input_planes, int input_height, int input_width,
int sub_samp_scale,
float init_learn_rate, int learn_rate_decrease_type, CvMat* weights )
{
CvCNNSubSamplingLayer* layer = 0;
CV_FUNCNAME("cvCreateCNNSubSamplingLayer");
__BEGIN__;
const int output_height = input_height/sub_samp_scale;
const int output_width = input_width/sub_samp_scale;
const int n_output_planes = n_input_planes;
fprintf(stderr,"SubSamplingLayer(%s): input (%d@%dx%d), output (%d@%dx%d)\n", name,
n_input_planes,input_width,input_height,n_output_planes,output_width,output_height);
if ( sub_samp_scale < 1 )
CV_ERROR( CV_StsBadArg, "Incorrect parameters" );
CV_CALL(layer = (CvCNNSubSamplingLayer*)icvCreateCNNLayer(
ICV_CNN_SUBSAMPLING_LAYER, dtype, name, sizeof(CvCNNSubSamplingLayer),
n_input_planes, input_height, input_width,
n_output_planes, output_height, output_width,
init_learn_rate, learn_rate_decrease_type,
icvCNNSubSamplingRelease, icvCNNSubSamplingForward, icvCNNSubSamplingBackward ));
layer->sub_samp_scale = sub_samp_scale;
layer->visualize = visualize;
layer->mask = 0;
CV_CALL(layer->sumX =
cvCreateMat( n_output_planes*output_width*output_height, 1, CV_32FC1 ));
CV_CALL(layer->WX =
cvCreateMat( n_output_planes*output_width*output_height, 1, CV_32FC1 ));
cvZero( layer->sumX );
cvZero( layer->WX );
CV_CALL(layer->weights = cvCreateMat( n_output_planes, 2, CV_32FC1 ));
if ( weights )
{
if ( !ICV_IS_MAT_OF_TYPE( weights, CV_32FC1 ) )
CV_ERROR( CV_StsBadSize, "Type of initial weights matrix must be CV_32FC1" );
if ( !CV_ARE_SIZES_EQ( weights, layer->weights ) )
CV_ERROR( CV_StsBadSize, "Invalid size of initial weights matrix" );
CV_CALL(cvCopy( weights, layer->weights ));
}
else
{
CvRNG rng = cvRNG( 0xFFFFFFFF );
cvRandArr( &rng, layer->weights, CV_RAND_UNI, cvRealScalar(-1), cvRealScalar(1) );
}
__END__;
if ( cvGetErrStatus() < 0 && layer )
{
cvReleaseMat( &layer->WX );
cvFree( &layer );
}
return (CvCNNLayer*)layer;
}
void icvCNNSubSamplingForward( CvCNNLayer* _layer, const CvMat* X, CvMat* Y )
{
CV_FUNCNAME("icvCNNSubSamplingForward");
if ( !icvIsCNNSubSamplingLayer(_layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
__BEGIN__;
CvCNNSubSamplingLayer * layer = (CvCNNSubSamplingLayer*) _layer;
CvMat * Xt = 0;
CvMat * Yt = 0;
const int stride_size = layer->sub_samp_scale;
const int nsamples = X->cols; // batch size for training
const int nplanes = layer->n_input_planes;
const int Xheight = layer->input_height;
const int Xwidth = layer->input_width ;
const int Xsize = Xwidth*Xheight;
const int Yheight = layer->output_height;
const int Ywidth = layer->output_width;
const int Ysize = Ywidth*Yheight;
const int batch_size = X->cols;
int xx, yy, ni, kx, ky;
float* sumX_data = 0, *w = 0;
CvMat sumX_sub_col, WX_sub_col;
CV_ASSERT(X->rows == nplanes*Xsize && X->cols == nsamples);
CV_ASSERT(Y->cols == nsamples);
CV_ASSERT((layer->WX->cols == 1) &&
(layer->WX->rows == nplanes*Ysize));
CV_CALL(layer->mask = cvCreateMat(Ysize*nplanes, batch_size, CV_32S));
// update inner variable used in back-propagation
cvZero( layer->sumX );
cvZero( layer->WX );
cvZero( layer->mask );
int * mptr = layer->mask->data.i;
CV_ASSERT(Xheight==Yheight*stride_size && Xwidth ==Ywidth *stride_size);
CV_ASSERT(Y->rows==layer->mask->rows && Y->cols==layer->mask->cols);
CV_ASSERT(CV_MAT_TYPE(layer->mask->type)==CV_32S);
Xt = cvCreateMat(X->cols,X->rows,CV_32F); cvTranspose(X,Xt);
Yt = cvCreateMat(Y->cols,Y->rows,CV_32F); cvTranspose(Y,Yt);
for ( int si = 0; si < nsamples; si++ ){
float * xptr = Xt->data.fl+Xsize*nplanes*si;
float * yptr = Yt->data.fl+Ysize*nplanes*si;
for ( ni = 0; ni < nplanes; ni++ ){
for ( yy = 0; yy < Yheight; yy++ ){
for ( xx = 0; xx < Ywidth; xx++ ){
float maxval = (xptr+stride_size*xx+Xwidth*0)[0];//*xptr;
int maxloc = 0;
for ( ky = 0; ky < stride_size; ky++ ){
for ( kx = 0; kx < stride_size; kx++ ){
if ((xptr+stride_size*xx+Xwidth*ky)[kx]>maxval) {
maxval = (xptr+stride_size*xx+Xwidth*ky)[kx];
maxloc = ky*stride_size + kx;
}
} // kx
} // ky
yptr[xx] = maxval;
mptr[xx] = maxloc;
} // xx
xptr += Xwidth*stride_size;
yptr += Ywidth;
mptr += Ywidth;
} // yy
} // ni
} // si
cvTranspose(Yt,Y);
cvReleaseMat(&Xt);
cvReleaseMat(&Yt);
if (layer->Y){cvCopy(Y,layer->Y);}else{layer->Y=cvCloneMat(Y);}
if (layer->visualize){icvVisualizeCNNLayer((CvCNNLayer*)layer,Y);}
__END__;
}
void icvCNNSubSamplingBackward(
CvCNNLayer* _layer, int t, const CvMat* X, const CvMat* dE_dY, CvMat* dE_dX )
{
// derivative of activation function
CvMat* dY_dX_elems = 0; // elements of matrix dY_dX
CvMat* dY_dW_elems = 0; // elements of matrix dY_dW
CvMat* dE_dW = 0;
CV_FUNCNAME("icvCNNSubSamplingBackward");
if ( !icvIsCNNSubSamplingLayer(_layer) ) {
CV_ERROR( CV_StsBadArg, "Invalid layer" );
}
__BEGIN__;
CvCNNSubSamplingLayer* layer = (CvCNNSubSamplingLayer*) _layer;
const int Xwidth = layer->input_width;
const int Xheight = layer->input_height;
const int Ywidth = layer->output_width;
const int Yheight = layer->output_height;
const int Xsize = Xwidth * Xheight;
const int Ysize = Ywidth * Yheight;
const int scale = layer->sub_samp_scale;
const int k_max = layer->n_output_planes * Yheight;
int k, i, j, m;
CV_ASSERT(CV_MAT_TYPE(layer->mask->type)==CV_32S);
CV_ASSERT(dE_dX->rows*dE_dX->cols==X->rows*X->cols);
int nplanes = layer->n_output_planes;
int nsamples = X->cols;
int stride_size = layer->sub_samp_scale;
CvMat * maskT = cvCreateMat(dE_dY->rows,dE_dY->cols,CV_32S);
cvTranspose(layer->mask,maskT);
cvZero(dE_dX);
for ( int si = 0; si < nsamples; si++ ){
float * dxptr = dE_dX->data.fl+dE_dX->cols*si;
float * dyptr = dE_dY->data.fl+dE_dY->cols*si;
int * mptr = maskT->data.i;
for ( int ni = 0; ni < nplanes; ni++ ){
for ( int yy = 0; yy < Yheight; yy++ ){
for ( int xx = 0; xx < Ywidth; xx++ ){
int maxloc = mptr[xx];
int ky = maxloc / stride_size;
int kx = maxloc % stride_size;
(dxptr+stride_size*xx+Xwidth*ky)[kx]=dyptr[xx];
}
dxptr += Xwidth*stride_size;
dyptr += Ywidth;
mptr += Ywidth;
}
}
}
cvReleaseMat(&maskT);
if (layer->mask){cvReleaseMat(&layer->mask);layer->mask=0;}
__END__;
if (dY_dX_elems){cvReleaseMat( &dY_dX_elems );dY_dX_elems=0;}
if (dY_dW_elems){cvReleaseMat( &dY_dW_elems );dY_dW_elems=0;}
if (dE_dW ){cvReleaseMat( &dE_dW );dE_dW =0;}
}
void icvCNNSubSamplingRelease( CvCNNLayer** p_layer )
{
CV_FUNCNAME("icvCNNSubSamplingRelease");
__BEGIN__;
CvCNNSubSamplingLayer* layer = 0;
if ( !p_layer )
CV_ERROR( CV_StsNullPtr, "Null double pointer" );
layer = *(CvCNNSubSamplingLayer**)p_layer;
if ( !layer )
return;
if ( !icvIsCNNSubSamplingLayer((CvCNNLayer*)layer) )
CV_ERROR( CV_StsBadArg, "Invalid layer" );
if (layer->mask ){cvReleaseMat( &layer->mask ); layer->mask =0;}
if (layer->WX){cvReleaseMat( &layer->WX ); layer->WX=0;}
if (layer->weights ){cvReleaseMat( &layer->weights ); layer->weights =0;}
cvFree( p_layer );
__END__;
}
<|endoftext|> |
<commit_before>#include "common.th"
.global isprime
start:
prologue
c <- 12
call(isprime)
illegal
// Checks whether C is prime or not. Returns a truth value in B.
isprime:
pushall(d,e,g,i,j,k,m)
// use e as local copy of c so we don't have to constantly save and restore
// it when calling other functions
e <- c
// 0 and 1 are not prime.
j <- e == 0
k <- e == 1
k <- j | k
jnzrel(k, cleanup0)
// 2 and 3 are prime.
j <- e == 2
k <- e == 3
k <- j | k
jnzrel(k, prime)
// Check for divisibility by 2.
c <- e
d <- 2
call(umod)
k <- b == 0
jnzrel(k, cleanup0)
// Check for divisibility by 3.
c <- e
d <- 3
call(umod)
k <- b == 0
jnzrel(k, cleanup0)
// Compute upper bound and store it in M.
c <- e
call(isqrt)
m <- b
i <- 1
mod_loop:
// Check to see if we're done, i.e. 6*i - 1 > m
g <- i * 6
g <- g - 1
k <- g > m
jnzrel(k, prime)
// Check for divisibility by 6*i - 1.
c <- e
g <- d
call(umod)
k <- b == 0
jnzrel(k, cleanup1)
// Check for divisibility by 6*i + 1.
c <- e
d <- i * 6
d <- d + 1
call(umod)
k <- b == 0
// Increment i and continue.
jnzrel(k, cleanup0)
i <- i + 1
goto(mod_loop)
prime:
b <- -1
goto(done)
cleanup1:
pop(c)
cleanup0:
composite:
b <- 0
done:
popall(d,e,g,i,j,k,m)
ret
<commit_msg>Compute primality of Jenny's phone number<commit_after>#include "common.th"
.global isprime
start:
prologue
c <- [rel(large)]
call(isprime)
illegal
large: .word 8675309
// Checks whether C is prime or not. Returns a truth value in B.
isprime:
pushall(d,e,g,i,j,k,m)
// use e as local copy of c so we don't have to constantly save and restore
// it when calling other functions
e <- c
// 0 and 1 are not prime.
j <- e == 0
k <- e == 1
k <- j | k
jnzrel(k, cleanup0)
// 2 and 3 are prime.
j <- e == 2
k <- e == 3
k <- j | k
jnzrel(k, prime)
// Check for divisibility by 2.
c <- e
d <- 2
call(umod)
k <- b == 0
jnzrel(k, cleanup0)
// Check for divisibility by 3.
c <- e
d <- 3
call(umod)
k <- b == 0
jnzrel(k, cleanup0)
// Compute upper bound and store it in M.
c <- e
call(isqrt)
m <- b
i <- 1
mod_loop:
// Check to see if we're done, i.e. 6*i - 1 > m
g <- i * 6
g <- g - 1
k <- g > m
jnzrel(k, prime)
// Check for divisibility by 6*i - 1.
c <- e
g <- d
call(umod)
k <- b == 0
jnzrel(k, cleanup1)
// Check for divisibility by 6*i + 1.
c <- e
d <- i * 6
d <- d + 1
call(umod)
k <- b == 0
// Increment i and continue.
jnzrel(k, cleanup0)
i <- i + 1
goto(mod_loop)
prime:
b <- -1
goto(done)
cleanup1:
pop(c)
cleanup0:
composite:
b <- 0
done:
popall(d,e,g,i,j,k,m)
ret
<|endoftext|> |
<commit_before>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <utility>
#include <pwd.h>
#include "../protobuf_for_node.h"
#include "service.pb.h"
#include "v8.h"
// For demonstrational purposes, let's pretend that getpwent is
// asynchronous, i.e. calls callbacks with data. Besides returning
// the password data, this demonstrates how to pass on call args as a
// C-style "void* data".
// Imaginary async system call.
void GetpwentAsync(
void (*cb)(struct passwd*, void*),
void (*done)(void*),
void* data) {
struct passwd* pwd;
while (pwd = getpwent()) cb(pwd, data);
setpwent();
done(data);
}
typedef protobuf_for_node::ServiceCall<
const pwd::EntriesRequest, pwd::EntriesResponse> Call;
void OnPasswd(struct passwd* pwd, void* data) {
// One lookup is done.
Call* call = Call::Cast(data);
// Otherwise, add to result.
pwd::Entry* e = call->response->add_entry();
e->set_name(pwd->pw_name);
e->set_uid(pwd->pw_uid);
e->set_gid(pwd->pw_gid);
e->set_home(pwd->pw_dir);
e->set_shell(pwd->pw_shell);
}
void OnDone(void* data) {
Call::Cast(data)->Done();
}
void GetEntries(Call* call) {
GetpwentAsync(OnPasswd, OnDone, call);
}
extern "C" void init(v8::Handle<v8::Object> target) {
// Look Ma - no v8 api!
protobuf_for_node::ExportService(
target, "pwd",
new (class : public pwd::Pwd {
virtual void GetEntries(google::protobuf::RpcController*,
const pwd::EntriesRequest* request,
pwd::EntriesResponse* response,
google::protobuf::Closure* done) {
::GetEntries(new Call(request, response, done));
}
}));
}
<commit_msg>Cosmetic changes.<commit_after>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
#include <pwd.h>
#include "../protobuf_for_node.h"
#include "service.pb.h"
// For demonstrational purposes, let's pretend that getpwent is
// asynchronous, i.e. calls callbacks with data. Besides returning
// the password data, this demonstrates how to pass on call args as a
// C-style "void* data".
// Imaginary interface.
void GetpwentAsync(
void (*cb)(struct passwd*, void*), // called for each entry
void (*done)(void*), // called when done
void* data) { // auxiliary payload
// Pretend for a moment this wasn't synchronous.
struct passwd* pwd;
while (pwd = getpwent()) cb(pwd, data);
setpwent();
done(data);
}
extern "C" void init(v8::Handle<v8::Object> target) {
// Look Ma - no v8 api!
protobuf_for_node::ExportService(
target, "pwd",
new (class : public pwd::Pwd {
// This is equivalent to the service call signature.
typedef protobuf_for_node::ServiceCall<
const pwd::EntriesRequest, pwd::EntriesResponse> Call;
static void OnPasswd(struct passwd* pwd, void* data) {
pwd::Entry* e = Call::Cast(data)->response->add_entry();
e->set_name(pwd->pw_name);
e->set_uid(pwd->pw_uid);
e->set_gid(pwd->pw_gid);
e->set_home(pwd->pw_dir);
e->set_shell(pwd->pw_shell);
}
static void OnDone(void* data) {
Call::Cast(data)->Done();
}
virtual void GetEntries(google::protobuf::RpcController*,
const pwd::EntriesRequest* request,
pwd::EntriesResponse* response,
google::protobuf::Closure* done) {
GetpwentAsync(OnPasswd,
OnDone,
new Call(request, response, done));
}
}));
}
<|endoftext|> |
<commit_before>/* This is a very simple example of the semantics of 'locking_container'. For a
* non-trivial example, see test.cpp.
*
* Compile this program enabling C++11, and linking with libpthread if needed.
* When you run this program, you should see no output or errors. An assertion
* means a bug in the code.
*
* Suggested compilation command:
* c++ -Wall -pedantic -std=c++11 -I../include simple.cpp -o simple -lpthread
*/
#include <stdio.h>
#include <assert.h>
#include "locking-container.hpp"
//(necessary for non-template source)
#include "locking-container.inc"
int main() {
//default: use 'rw_lock'
typedef lc::locking_container <int> protected_int0;
//use 'w_lock' instead
typedef lc::locking_container <int, lc::w_lock> protected_int1;
//the two types above share the same base class because they both protect 'int'
typedef protected_int0::base base;
//protected data
protected_int0 data0;
protected_int1 data1;
//authorization object to prevent deadlocks (one per thread)
//NOTE: this will correspond to 'rw_lock', since that's what 'protected_int0' uses
lc::lock_auth_base::auth_type auth(protected_int0::new_auth());
//make sure an authorization was provided
assert(auth);
//alternatively, you can explicitly specify an authorization type
lc::lock_auth_base::auth_type auth2(new lc::lock_auth <lc::r_lock>);
//proxy objects for accessing the protected data (use them like pointers)
base::write_proxy write;
base::read_proxy read;
//get a proxy, without deadlock prevention
write = data0.get_write();
assert(write); //(just for testing)
//write to the object
*write = 1;
//release the lock
write.clear();
assert(!write);
//get a proxy, with deadlock prevention
write = data0.get_write_auth(auth);
assert(write);
//NOTE: this updates 'auth', since 'get_write_auth' was used!
write.clear();
//get a read-only proxy
read = data0.get_read_auth(auth);
assert(read);
read.clear();
//you can use the same proxy object with containers of the same base type
read = data1.get_read_auth(auth);
assert(read);
{
//'auth' still holds a read lock, but 'data0' isn't in use, so this should succeed
base::write_proxy write2 = data0.get_write_auth(auth);
assert(write2);
//this is a potential deadlock, since 'auth' has a write lock and 'data1' is in use
base::read_proxy read2 = data1.get_read_auth(auth);
assert(!read2);
} //<-- 'write2' goes out of scope, which unlocks 'data0'
{
//copy the proxy object
base::read_proxy read2 = read;
assert(read2);
} //<-- 'read2' goes out of scope, but 'data1' doesn't get unlocked since it's not a new lock
assert(read);
read.clear();
//use 'try_copy_container' to copy containers (attempts to lock both containers)
bool success1 = try_copy_container(data0, data1, auth);
assert(success1);
//use 'try_copy_container' to copy containers, with multi-locking
//NOTE: normally every 'get_write_auth' and 'get_read_auth' above should be
//replaced with 'get_write_multi' and 'get_read_multi' so that 'multi_lock'
//keeps track of all of the locks held on 'data0' and 'data1'. this is so that
//'multi_lock' makes this call block until no other threads are accessing
//'data0' or 'data1'. (see ../test/unit.cpp more a more elaborate example.)
lc::multi_lock multi;
bool success2 = try_copy_container(data0, data1, multi, auth);
assert(success2);
//or, if this thread already holds a write lock on 'multi_lock'...
lc::multi_lock::write_proxy multi_write = multi.get_write_auth(auth);
bool success3 = try_copy_container(data0, data1, multi, auth, true, false);
assert(success3);
}
<commit_msg>fixed another missed reference to test.cpp<commit_after>/* This is a very simple example of the semantics of 'locking_container'. For a
* non-trivial example, see ../test/unit.cpp.
*
* Compile this program enabling C++11, and linking with libpthread if needed.
* When you run this program, you should see no output or errors. An assertion
* means a bug in the code.
*
* Suggested compilation command:
* c++ -Wall -pedantic -std=c++11 -I../include simple.cpp -o simple -lpthread
*/
#include <stdio.h>
#include <assert.h>
#include "locking-container.hpp"
//(necessary for non-template source)
#include "locking-container.inc"
int main() {
//default: use 'rw_lock'
typedef lc::locking_container <int> protected_int0;
//use 'w_lock' instead
typedef lc::locking_container <int, lc::w_lock> protected_int1;
//the two types above share the same base class because they both protect 'int'
typedef protected_int0::base base;
//protected data
protected_int0 data0;
protected_int1 data1;
//authorization object to prevent deadlocks (one per thread)
//NOTE: this will correspond to 'rw_lock', since that's what 'protected_int0' uses
lc::lock_auth_base::auth_type auth(protected_int0::new_auth());
//make sure an authorization was provided
assert(auth);
//alternatively, you can explicitly specify an authorization type
lc::lock_auth_base::auth_type auth2(new lc::lock_auth <lc::r_lock>);
//proxy objects for accessing the protected data (use them like pointers)
base::write_proxy write;
base::read_proxy read;
//get a proxy, without deadlock prevention
write = data0.get_write();
assert(write); //(just for testing)
//write to the object
*write = 1;
//release the lock
write.clear();
assert(!write);
//get a proxy, with deadlock prevention
write = data0.get_write_auth(auth);
assert(write);
//NOTE: this updates 'auth', since 'get_write_auth' was used!
write.clear();
//get a read-only proxy
read = data0.get_read_auth(auth);
assert(read);
read.clear();
//you can use the same proxy object with containers of the same base type
read = data1.get_read_auth(auth);
assert(read);
{
//'auth' still holds a read lock, but 'data0' isn't in use, so this should succeed
base::write_proxy write2 = data0.get_write_auth(auth);
assert(write2);
//this is a potential deadlock, since 'auth' has a write lock and 'data1' is in use
base::read_proxy read2 = data1.get_read_auth(auth);
assert(!read2);
} //<-- 'write2' goes out of scope, which unlocks 'data0'
{
//copy the proxy object
base::read_proxy read2 = read;
assert(read2);
} //<-- 'read2' goes out of scope, but 'data1' doesn't get unlocked since it's not a new lock
assert(read);
read.clear();
//use 'try_copy_container' to copy containers (attempts to lock both containers)
bool success1 = try_copy_container(data0, data1, auth);
assert(success1);
//use 'try_copy_container' to copy containers, with multi-locking
//NOTE: normally every 'get_write_auth' and 'get_read_auth' above should be
//replaced with 'get_write_multi' and 'get_read_multi' so that 'multi_lock'
//keeps track of all of the locks held on 'data0' and 'data1'. this is so that
//'multi_lock' makes this call block until no other threads are accessing
//'data0' or 'data1'. (see ../test/unit.cpp more a more elaborate example.)
lc::multi_lock multi;
bool success2 = try_copy_container(data0, data1, multi, auth);
assert(success2);
//or, if this thread already holds a write lock on 'multi_lock'...
lc::multi_lock::write_proxy multi_write = multi.get_write_auth(auth);
bool success3 = try_copy_container(data0, data1, multi, auth, true, false);
assert(success3);
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qHasFeature_OpenSSL
#include <openssl/evp.h>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/provider.h>
#endif
#endif
#include "../../Debug/Assertions.h"
#include "../../Execution/Exceptions.h"
#include "LibraryContext.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Cryptography;
using namespace Stroika::Foundation::Cryptography::OpenSSL;
#if qHasFeature_OpenSSL && defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#else
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "crypt32.lib")
#endif
#endif
#if qHasFeature_OpenSSL
namespace {
optional<String> GetCiphrName_ (CipherAlgorithm a)
{
if (auto i = ::EVP_CIPHER_name (a)) {
return String::FromASCII (i);
}
return nullopt;
}
}
/*
********************************************************************************
******************* Cryptography::OpenSSL::LibraryContext **********************
********************************************************************************
*/
LibraryContext LibraryContext::sDefault;
namespace {
void f (const EVP_CIPHER* ciph, void* arg) {
Set<String>* ciphers = reinterpret_cast<Set<String>*> (arg);
if (ciph != nullptr) {
#if OPENSSL_VERSION_MAJOR >= 3
DbgTrace (L"cipher: %p (name: %s), provider: %p", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_provider (ciph));
#else
DbgTrace (L"cipher: %p (name: %s), ciph, CipherAlgorithm{ciph}.pName ().c_str ());
#endif
Assert (GetCiphrName_ (ciph));
if (auto cipherName = GetCiphrName_ (ciph)) {
#if OPENSSL_VERSION_MAJOR >= 3
if (auto provider = ::EVP_CIPHER_provider (ciph)) {
DbgTrace ("providername = %s", ::OSSL_PROVIDER_name (provider));
}
#endif
int flags = ::EVP_CIPHER_flags (ciph);
DbgTrace ("flags=%x", flags);
ciphers->Add (*cipherName);
}
}
};
}
LibraryContext::LibraryContext ()
: pAvailableAlgorithms{
[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> ciphers;
#if OPENSSL_VERSION_MAJOR >= 3
::EVP_CIPHER_do_all_provided (
nullptr,
[] (EVP_CIPHER* ciph, void* arg) { f (ciph, arg); },
&ciphers);
#else
::EVP_CIPHER_do_all_sorted (
[] (const EVP_CIPHER* ciph, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { f (ciph, arg); },
&ciphers);
#endif
DbgTrace (L"Found kAllLoadedCiphers=%s", Characters::ToString (ciphers).c_str ());
auto fn = [] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); };
Traversal::Iterable<int> yyy{};
Set<int> resultyyy{yyy};
using namespace Configuration;
static_assert (IsIterable_v<Traversal::Iterable<CipherAlgorithm>>);
using ITERABLE_OF_T = Traversal::Iterable<CipherAlgorithm>;
//Configuration::Private:: IsIterableOfT_Impl2_<set<int>, int> aa;
#if 1
Set<CipherAlgorithm> result{ciphers.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); })};
WeakAssert (result.size () == ciphers.size ());
#endif
return result;
}}
{
LoadProvider (kDefaultProvider);
}
LibraryContext ::~LibraryContext ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
for (auto i : fLoadedProviders_) {
Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1);
}
#endif
}
void LibraryContext::LoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (NULL, providerName.AsNarrowSDKString ().c_str ());
static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv};
Execution::ThrowIfNull (p, kErr_);
if (auto l = fLoadedProviders_.Lookup (providerName)) {
l->second++;
fLoadedProviders_.Add (providerName, *l);
}
else {
fLoadedProviders_.Add (providerName, {p, 1});
}
#else
Require (providerName == kDefaultProvider or providerName == kLegacyProvider);
#endif
}
void LibraryContext ::UnLoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
Require (fLoadedProviders_.ContainsKey (providerName));
auto l = fLoadedProviders_.Lookup (providerName);
Assert (l);
l->second--;
if (l->second == 0) {
fLoadedProviders_.Remove (providerName);
Verify (::OSSL_PROVIDER_unload (l->first) == 1);
}
else {
fLoadedProviders_.Add (providerName, *l);
}
#endif
}
#endif
<commit_msg>fixed typo<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qHasFeature_OpenSSL
#include <openssl/evp.h>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/provider.h>
#endif
#endif
#include "../../Debug/Assertions.h"
#include "../../Execution/Exceptions.h"
#include "LibraryContext.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Cryptography;
using namespace Stroika::Foundation::Cryptography::OpenSSL;
#if qHasFeature_OpenSSL && defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#else
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "crypt32.lib")
#endif
#endif
#if qHasFeature_OpenSSL
namespace {
optional<String> GetCiphrName_ (CipherAlgorithm a)
{
if (auto i = ::EVP_CIPHER_name (a)) {
return String::FromASCII (i);
}
return nullopt;
}
}
/*
********************************************************************************
******************* Cryptography::OpenSSL::LibraryContext **********************
********************************************************************************
*/
LibraryContext LibraryContext::sDefault;
namespace {
void f (const EVP_CIPHER* ciph, void* arg) {
Set<String>* ciphers = reinterpret_cast<Set<String>*> (arg);
if (ciph != nullptr) {
#if OPENSSL_VERSION_MAJOR >= 3
DbgTrace (L"cipher: %p (name: %s), provider: %p", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_provider (ciph));
#else
DbgTrace (L"cipher: %p (name: %s)", ciph, CipherAlgorithm{ciph}.pName ().c_str ());
#endif
Assert (GetCiphrName_ (ciph));
if (auto cipherName = GetCiphrName_ (ciph)) {
#if OPENSSL_VERSION_MAJOR >= 3
if (auto provider = ::EVP_CIPHER_provider (ciph)) {
DbgTrace ("providername = %s", ::OSSL_PROVIDER_name (provider));
}
#endif
int flags = ::EVP_CIPHER_flags (ciph);
DbgTrace ("flags=%x", flags);
ciphers->Add (*cipherName);
}
}
};
}
LibraryContext::LibraryContext ()
: pAvailableAlgorithms{
[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> ciphers;
#if OPENSSL_VERSION_MAJOR >= 3
::EVP_CIPHER_do_all_provided (
nullptr,
[] (EVP_CIPHER* ciph, void* arg) { f (ciph, arg); },
&ciphers);
#else
::EVP_CIPHER_do_all_sorted (
[] (const EVP_CIPHER* ciph, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { f (ciph, arg); },
&ciphers);
#endif
DbgTrace (L"Found kAllLoadedCiphers=%s", Characters::ToString (ciphers).c_str ());
auto fn = [] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); };
Traversal::Iterable<int> yyy{};
Set<int> resultyyy{yyy};
using namespace Configuration;
static_assert (IsIterable_v<Traversal::Iterable<CipherAlgorithm>>);
using ITERABLE_OF_T = Traversal::Iterable<CipherAlgorithm>;
//Configuration::Private:: IsIterableOfT_Impl2_<set<int>, int> aa;
#if 1
Set<CipherAlgorithm> result{ciphers.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); })};
WeakAssert (result.size () == ciphers.size ());
#endif
return result;
}}
{
LoadProvider (kDefaultProvider);
}
LibraryContext ::~LibraryContext ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
for (auto i : fLoadedProviders_) {
Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1);
}
#endif
}
void LibraryContext::LoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (NULL, providerName.AsNarrowSDKString ().c_str ());
static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv};
Execution::ThrowIfNull (p, kErr_);
if (auto l = fLoadedProviders_.Lookup (providerName)) {
l->second++;
fLoadedProviders_.Add (providerName, *l);
}
else {
fLoadedProviders_.Add (providerName, {p, 1});
}
#else
Require (providerName == kDefaultProvider or providerName == kLegacyProvider);
#endif
}
void LibraryContext ::UnLoadProvider (const String& providerName)
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
Require (fLoadedProviders_.ContainsKey (providerName));
auto l = fLoadedProviders_.Lookup (providerName);
Assert (l);
l->second--;
if (l->second == 0) {
fLoadedProviders_.Remove (providerName);
Verify (::OSSL_PROVIDER_unload (l->first) == 1);
}
else {
fLoadedProviders_.Add (providerName, *l);
}
#endif
}
#endif
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDefaultDropTargetListener.h"
#include <QDebug>
#include <QDropEvent>
#include <QStringList>
#include <QUrl>
#include "internal/org_mitk_gui_qt_application_Activator.h"
#include <berryIPreferencesService.h>
#include <berryPlatformUI.h>
#include <ctkServiceTracker.h>
#include <mitkWorkbenchUtil.h>
class QmitkDefaultDropTargetListenerPrivate
{
public:
QmitkDefaultDropTargetListenerPrivate()
: m_PrefServiceTracker(mitk::PluginActivator::GetContext())
{
m_PrefServiceTracker.open();
}
berry::IPreferences::Pointer GetPreferences() const
{
berry::IPreferencesService* prefService = m_PrefServiceTracker.getService();
if (prefService)
{
return prefService->GetSystemPreferences()->Node("/General");
}
return berry::IPreferences::Pointer(0);
}
bool GetOpenEditor() const
{
berry::IPreferences::Pointer prefs = GetPreferences();
if(prefs.IsNotNull())
{
return prefs->GetBool("OpenEditor", true);
}
return true;
}
ctkServiceTracker<berry::IPreferencesService*> m_PrefServiceTracker;
};
QmitkDefaultDropTargetListener::QmitkDefaultDropTargetListener()
: berry::IDropTargetListener(), d(new QmitkDefaultDropTargetListenerPrivate())
{
}
QmitkDefaultDropTargetListener::~QmitkDefaultDropTargetListener()
{
}
berry::IDropTargetListener::Events::Types QmitkDefaultDropTargetListener::GetDropTargetEventTypes() const
{
return Events::DROP;
}
void QmitkDefaultDropTargetListener::DropEvent(QDropEvent *event)
{
qDebug() << event->mimeData()->formats();
qDebug() << event->mimeData()->text();
QList<QUrl> fileNames = event->mimeData()->urls();
if (fileNames.empty())
return;
QStringList fileNames2;
//TODO Qt 4.7 API
//fileNames2.reserve(fileNames.size());
foreach(QUrl url, fileNames)
{
fileNames2.push_back(url.toLocalFile());
}
mitk::WorkbenchUtil::LoadFiles(fileNames2,
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(),
d->GetOpenEditor());
event->accept();
}
<commit_msg>COMP: Use central GetPreferencesService() method.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDefaultDropTargetListener.h"
#include <QDebug>
#include <QDropEvent>
#include <QStringList>
#include <QUrl>
#include "internal/org_mitk_gui_qt_application_Activator.h"
#include <berryIPreferencesService.h>
#include <berryPlatformUI.h>
#include <mitkWorkbenchUtil.h>
class QmitkDefaultDropTargetListenerPrivate
{
public:
berry::IPreferences::Pointer GetPreferences() const
{
berry::IPreferencesService::Pointer prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService();
if (prefService)
{
return prefService->GetSystemPreferences()->Node("/General");
}
return berry::IPreferences::Pointer(0);
}
bool GetOpenEditor() const
{
berry::IPreferences::Pointer prefs = GetPreferences();
if(prefs.IsNotNull())
{
return prefs->GetBool("OpenEditor", true);
}
return true;
}
};
QmitkDefaultDropTargetListener::QmitkDefaultDropTargetListener()
: berry::IDropTargetListener(), d(new QmitkDefaultDropTargetListenerPrivate())
{
}
QmitkDefaultDropTargetListener::~QmitkDefaultDropTargetListener()
{
}
berry::IDropTargetListener::Events::Types QmitkDefaultDropTargetListener::GetDropTargetEventTypes() const
{
return Events::DROP;
}
void QmitkDefaultDropTargetListener::DropEvent(QDropEvent *event)
{
qDebug() << event->mimeData()->formats();
qDebug() << event->mimeData()->text();
QList<QUrl> fileNames = event->mimeData()->urls();
if (fileNames.empty())
return;
QStringList fileNames2;
//TODO Qt 4.7 API
//fileNames2.reserve(fileNames.size());
foreach(QUrl url, fileNames)
{
fileNames2.push_back(url.toLocalFile());
}
mitk::WorkbenchUtil::LoadFiles(fileNames2,
berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(),
d->GetOpenEditor());
event->accept();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <chrono>
#include <random>
#include <set>
#include <map>
#include <list>
#include <forward_list>
#include "Allocator.h"
const std::size_t growSize = 1024;
const int numberOfIterations = 1024;
const int randomRange = 1024;
template <typename Container>
class PerformanceTest
{
virtual void testIteration(int newSize) = 0;
protected:
Container container;
std::default_random_engine randomNumberGenerator;
std::uniform_int_distribution<int> randomNumberDistribution;
public:
PerformanceTest() :
randomNumberGenerator(0),
randomNumberDistribution(0, randomRange)
{
}
double run()
{
auto from = std::chrono::high_resolution_clock::now();
for (int i = 0; i < numberOfIterations; i++)
testIteration(randomNumberDistribution(randomNumberGenerator));
auto to = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double>>(to - from).count();
}
};
template <typename Container>
class PushFrontTest : public PerformanceTest<Container>
{
virtual void testIteration(int newSize)
{
int size = 0;
while (size < newSize)
this->container.push_front(size++);
for (; size > newSize; size--)
this->container.pop_front();
}
};
template <typename Container>
class PushBackTest : public PerformanceTest<Container>
{
virtual void testIteration(int newSize)
{
int size = 0;
while (size < newSize)
this->container.push_back(size++);
for (; size > newSize; size--)
this->container.pop_back();
}
};
template <typename Container>
class MapTest : public PerformanceTest<Container>
{
virtual void testIteration(int newSize)
{
int size = 0;
while (size < newSize)
this->container.insert(std::pair<char, int>(size++, size));
while (size > newSize)
this->container.erase(--size);
}
};
template <typename Container>
class SetTest : public PerformanceTest<Container>
{
virtual void testIteration(int newSize)
{
int size = 0;
while (size < newSize)
this->container.insert(size++);
while (size > newSize)
this->container.erase(--size);
}
};
template <typename StlContainer, typename FastContainer>
void printTestStatus(const char *name, StlContainer &stlContainer, FastContainer &fastContainer)
{
std::cout << std::fixed;
std::cout << name << " - Default STL Allocator : " << stlContainer.run() << " seconds." << std::endl;
std::cout << name << " - Memory Pool Allocator : " << fastContainer.run() << " seconds." << std::endl;
std::cout << std::endl;
}
int main()
{
typedef int DataType;
typedef Moya::Allocator<DataType, growSize> MemoryPoolAllocator;
std::cout << "Allocator performance measurement example" << std::endl;
std::cout << "Version: 1.0" << std::endl << std::endl;
PushFrontTest<std::forward_list<DataType>> pushFrontForwardListTestStl;
PushFrontTest<std::forward_list<DataType, MemoryPoolAllocator>> pushFrontForwardListTestFast;
printTestStatus("ForwardList PushFront", pushFrontForwardListTestStl, pushFrontForwardListTestFast);
PushFrontTest<std::list<DataType>> pushFrontListTestStl;
PushFrontTest<std::list<DataType, MemoryPoolAllocator>> pushFrontListTestFast;
printTestStatus("List PushFront", pushFrontListTestStl, pushFrontListTestFast);
PushBackTest<std::list<DataType>> pushBackListTestStl;
PushBackTest<std::list<DataType, MemoryPoolAllocator>> pushBackListTestFast;
printTestStatus("List PushBack", pushBackListTestStl, pushBackListTestFast);
MapTest<std::map<DataType, DataType, std::less<DataType>>> mapTestStl;
MapTest<std::map<DataType, DataType, std::less<DataType>, MemoryPoolAllocator>> mapTestFast;
printTestStatus("Map", mapTestStl, mapTestFast);
SetTest<std::set<DataType, std::less<DataType>>> setTestStl;
SetTest<std::set<DataType, std::less<DataType>, MemoryPoolAllocator>> setTestFast;
printTestStatus("Set", setTestStl, setTestFast);
return 0;
}
<commit_msg>Fixed test for std::map on C++17 and newer<commit_after>#include <iostream>
#include <chrono>
#include <random>
#include <set>
#include <map>
#include <list>
#include <forward_list>
#include "Allocator.h"
const size_t growSize = 1024;
const size_t numberOfIterations = 1024;
const size_t randomRange = 1024;
template <typename Container>
class PerformanceTest
{
virtual void testIteration(size_t newSize) = 0;
protected:
Container container;
std::default_random_engine randomNumberGenerator;
std::uniform_int_distribution<size_t> randomNumberDistribution;
public:
PerformanceTest() :
randomNumberGenerator(0),
randomNumberDistribution(0, randomRange)
{
}
virtual ~PerformanceTest()
{
}
double run()
{
auto from = std::chrono::high_resolution_clock::now();
for (size_t i = 0; i < numberOfIterations; i++)
testIteration(randomNumberDistribution(randomNumberGenerator));
auto to = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double>>(to - from).count();
}
};
template <typename Container>
class PushFrontTest : public PerformanceTest<Container>
{
virtual void testIteration(size_t newSize)
{
size_t size = 0;
while (size < newSize)
this->container.push_front(size++);
for (; size > newSize; size--)
this->container.pop_front();
}
};
template <typename Container>
class PushBackTest : public PerformanceTest<Container>
{
virtual void testIteration(size_t newSize)
{
size_t size = 0;
while (size < newSize)
this->container.push_back(size++);
for (; size > newSize; size--)
this->container.pop_back();
}
};
template <typename Container>
class MapTest : public PerformanceTest<Container>
{
virtual void testIteration(size_t newSize)
{
size_t size = 0;
for (; size < newSize; size++)
this->container.insert(Container::value_type(size, size));
while (size > newSize)
this->container.erase(--size);
}
};
template <typename Container>
class SetTest : public PerformanceTest<Container>
{
virtual void testIteration(size_t newSize)
{
size_t size = 0;
while (size < newSize)
this->container.insert(size++);
while (size > newSize)
this->container.erase(--size);
}
};
template <typename StlAllocatorContainer, typename MoyaAllocatorContainer>
void printTestStatus(const char *name, StlAllocatorContainer &stlContainer, MoyaAllocatorContainer &fastContainer)
{
double stlRunTime = stlContainer.run();
double moyaRunTime = fastContainer.run();
std::cout << std::fixed;
std::cout << name << " - Default STL Allocator : " << stlRunTime << " seconds." << std::endl;
std::cout << name << " - Memory Pool Allocator : " << moyaRunTime << " seconds." << std::endl;
std::cout << name << " - Gain : x" << stlRunTime / moyaRunTime << "." << std::endl;
std::cout << std::endl;
}
int main()
{
typedef size_t DataType;
typedef Moya::Allocator<DataType, growSize> MemoryPoolAllocator;
typedef Moya::Allocator<std::map<DataType, DataType>::value_type, growSize> MapMemoryPoolAllocator;
std::cout << "Allocator performance measurement example" << std::endl;
std::cout << "Version: 1.0" << std::endl << std::endl;
PushFrontTest<std::forward_list<DataType>> pushFrontForwardListTestStl;
PushFrontTest<std::forward_list<DataType, MemoryPoolAllocator>> pushFrontForwardListTestFast;
printTestStatus("ForwardList PushFront", pushFrontForwardListTestStl, pushFrontForwardListTestFast);
PushFrontTest<std::list<DataType>> pushFrontListTestStl;
PushFrontTest<std::list<DataType, MemoryPoolAllocator>> pushFrontListTestFast;
printTestStatus("List PushFront", pushFrontListTestStl, pushFrontListTestFast);
PushBackTest<std::list<DataType>> pushBackListTestStl;
PushBackTest<std::list<DataType, MemoryPoolAllocator>> pushBackListTestFast;
printTestStatus("List PushBack", pushBackListTestStl, pushBackListTestFast);
MapTest<std::map<DataType, DataType, std::less<DataType>>> mapTestStl;
MapTest<std::map<DataType, DataType, std::less<DataType>, MapMemoryPoolAllocator>> mapTestFast;
printTestStatus("Map", mapTestStl, mapTestFast);
SetTest<std::set<DataType, std::less<DataType>>> setTestStl;
SetTest<std::set<DataType, std::less<DataType>, MemoryPoolAllocator>> setTestFast;
printTestStatus("Set", setTestStl, setTestFast);
return 0;
}
<|endoftext|> |
<commit_before>#include "MyModel.h"
namespace Perceptron
{
const DNest4::Cauchy MyModel::cauchy(0.0, 5.0);
MyModel::MyModel()
:input_locations(Data::get_instance().get_dim_inputs())
,output_locations(Data::get_instance().get_dim_outputs())
,input_scales(Data::get_instance().get_dim_inputs())
,output_scales(Data::get_instance().get_dim_outputs())
,weights(1,
Data::get_instance().get_dim_outputs()*
Data::get_instance().get_dim_inputs(),
true,
MyConditionalPrior())
,weights_matrix(Data::get_instance().get_dim_outputs(),
Data::get_instance().get_dim_inputs())
{
}
void MyModel::from_prior(DNest4::RNG& rng)
{
for(auto& x: input_locations)
x.from_prior(rng);
for(auto& x: output_locations)
x.from_prior(rng);
for(auto& x: input_scales)
x.from_prior(rng);
for(auto& x: output_scales)
x.from_prior(rng);
weights.from_prior(rng);
make_weights_matrix();
sigma = exp(cauchy.generate(rng));
}
double MyModel::perturb(DNest4::RNG& rng)
{
double logH = 0.0;
int which = rng.rand_int(6);
if(which == 0)
{
logH += input_locations[rng.rand_int(input_locations.size())]
.perturb(rng);
}
else if(which == 1)
{
logH += output_locations[rng.rand_int(output_locations.size())]
.perturb(rng);
}
if(which == 2)
{
logH += input_scales[rng.rand_int(input_scales.size())].perturb(rng);
}
else if(which == 3)
{
logH += output_scales[rng.rand_int(output_scales.size())].perturb(rng);
}
else if(which == 4)
{
logH += weights.perturb(rng);
make_weights_matrix();
}
else
{
sigma = log(sigma);
logH += cauchy.perturb(sigma, rng);
sigma = exp(sigma);
}
return logH;
}
void MyModel::make_weights_matrix()
{
// Put weights in a matrix
const auto& components = weights.get_components();
int k = 0;
for(int i=0; i<Data::get_instance().get_dim_outputs(); ++i)
for(int j=0; j<Data::get_instance().get_dim_inputs(); ++j)
weights_matrix(i, j) = components[k++][0];
}
double MyModel::log_likelihood() const
{
double logL = 0.0;
const auto& inputs = Data::get_instance().get_inputs();
const auto& outputs = Data::get_instance().get_outputs();
for(size_t i=0; i<inputs.size(); ++i)
{
// Predict the output
Vector result = calculate_output(inputs[i]);
for(int j=0; j<result.size(); ++j)
{
double var = pow(sigma*output_scales[j].get_magnitude(), 2);
logL += -0.5*log(2*M_PI*var)
-0.5*pow(outputs[i][j] - result[j], 2)/var;
}
}
return logL;
}
void MyModel::print(std::ostream& out) const
{
for(const auto& x: input_locations)
out<<x.get_value()<<' ';
for(const auto& x: output_locations)
out<<x.get_value()<<' ';
for(const auto& x: input_scales)
out<<x.get_magnitude()<<' ';
for(const auto& x: output_scales)
out<<x.get_magnitude()<<' ';
weights.print(out);
out<<sigma<<' ';
}
Vector MyModel::calculate_output(const Vector& input) const
{
// Standardize the input of the example
Vector standardized_input = input;
for(int j=0; j<standardized_input.size(); ++j)
{
standardized_input[j] -= input_locations[j].get_value();
standardized_input[j] /= input_scales[j].get_magnitude();
}
// Run the neural net on the standardized input
Vector result = weights_matrix*input;
for(int i=0; i<result.size(); ++i)
result[i] = nonlinear_function(result[i]);
// De-standardize the output
for(int j=0; j<result.size(); ++j)
{
result[j] *= output_scales[j].get_magnitude();
result[j] += output_locations[j].get_value();
}
return result;
}
std::string MyModel::description() const
{
return std::string("");
}
double MyModel::nonlinear_function(double x)
{
if(x < -1.0)
return -1.0;
if(x > 1.0)
return 1.0;
return x;
}
} // namespace Perceptron
<commit_msg>Plot predictions<commit_after>#include "MyModel.h"
namespace Perceptron
{
const DNest4::Cauchy MyModel::cauchy(0.0, 5.0);
MyModel::MyModel()
:input_locations(Data::get_instance().get_dim_inputs())
,output_locations(Data::get_instance().get_dim_outputs())
,input_scales(Data::get_instance().get_dim_inputs())
,output_scales(Data::get_instance().get_dim_outputs())
,weights(1,
Data::get_instance().get_dim_outputs()*
Data::get_instance().get_dim_inputs(),
true,
MyConditionalPrior())
,weights_matrix(Data::get_instance().get_dim_outputs(),
Data::get_instance().get_dim_inputs())
{
}
void MyModel::from_prior(DNest4::RNG& rng)
{
for(auto& x: input_locations)
x.from_prior(rng);
for(auto& x: output_locations)
x.from_prior(rng);
for(auto& x: input_scales)
x.from_prior(rng);
for(auto& x: output_scales)
x.from_prior(rng);
weights.from_prior(rng);
make_weights_matrix();
sigma = exp(cauchy.generate(rng));
}
double MyModel::perturb(DNest4::RNG& rng)
{
double logH = 0.0;
int which = rng.rand_int(6);
if(which == 0)
{
logH += input_locations[rng.rand_int(input_locations.size())]
.perturb(rng);
}
else if(which == 1)
{
logH += output_locations[rng.rand_int(output_locations.size())]
.perturb(rng);
}
if(which == 2)
{
logH += input_scales[rng.rand_int(input_scales.size())].perturb(rng);
}
else if(which == 3)
{
logH += output_scales[rng.rand_int(output_scales.size())].perturb(rng);
}
else if(which == 4)
{
logH += weights.perturb(rng);
make_weights_matrix();
}
else
{
sigma = log(sigma);
logH += cauchy.perturb(sigma, rng);
sigma = exp(sigma);
}
return logH;
}
void MyModel::make_weights_matrix()
{
// Put weights in a matrix
const auto& components = weights.get_components();
int k = 0;
for(int i=0; i<Data::get_instance().get_dim_outputs(); ++i)
for(int j=0; j<Data::get_instance().get_dim_inputs(); ++j)
weights_matrix(i, j) = components[k++][0];
}
double MyModel::log_likelihood() const
{
double logL = 0.0;
const auto& inputs = Data::get_instance().get_inputs();
const auto& outputs = Data::get_instance().get_outputs();
for(size_t i=0; i<inputs.size(); ++i)
{
// Predict the output
Vector result = calculate_output(inputs[i]);
for(int j=0; j<result.size(); ++j)
{
double var = pow(sigma*output_scales[j].get_magnitude(), 2);
logL += -0.5*log(2*M_PI*var)
-0.5*pow(outputs[i][j] - result[j], 2)/var;
}
}
return logL;
}
void MyModel::print(std::ostream& out) const
{
// for(const auto& x: input_locations)
// out<<x.get_value()<<' ';
// for(const auto& x: output_locations)
// out<<x.get_value()<<' ';
// for(const auto& x: input_scales)
// out<<x.get_magnitude()<<' ';
// for(const auto& x: output_scales)
// out<<x.get_magnitude()<<' ';
// weights.print(out);
// out<<sigma<<' ';
Vector input(2);
for(int i=50; i<250; ++i)
{
input[0] = i;
input[1] = 10.0;
auto output = calculate_output(input);
out<<output(0)<<' ';
}
}
Vector MyModel::calculate_output(const Vector& input) const
{
// Standardize the input of the example
Vector standardized_input = input;
for(int j=0; j<standardized_input.size(); ++j)
{
standardized_input[j] -= input_locations[j].get_value();
standardized_input[j] /= input_scales[j].get_magnitude();
}
// Run the neural net on the standardized input
Vector result = weights_matrix*input;
for(int i=0; i<result.size(); ++i)
result[i] = nonlinear_function(result[i]);
// De-standardize the output
for(int j=0; j<result.size(); ++j)
{
result[j] *= output_scales[j].get_magnitude();
result[j] += output_locations[j].get_value();
}
return result;
}
std::string MyModel::description() const
{
return std::string("");
}
double MyModel::nonlinear_function(double x)
{
if(x < -1.0)
return -1.0;
if(x > 1.0)
return 1.0;
return x;
}
} // namespace Perceptron
<|endoftext|> |
<commit_before>#include "mpi.h"
#include <Python.h>
#include <string>
#include <iostream>
#include <cstring>
#include <cmath>
// just include parquet reader on Windows since the GCC ABI change issue
// doesn't exist, and VC linker removes unused lib symbols
#if defined(_MSC_VER) || defined(BUILTIN_PARQUET_READER)
#include <parquet_reader/hpat_parquet_reader.cpp>
#else
// parquet type sizes (NOT arrow)
// boolean, int32, int64, int96, float, double
int pq_type_sizes[] = {1, 4, 8, 12, 4, 8};
extern "C" {
int64_t pq_get_size_single_file(const char* file_name, int64_t column_idx);
int64_t pq_read_single_file(const char* file_name, int64_t column_idx, uint8_t *out,
int out_dtype);
int pq_read_parallel_single_file(const char* file_name, int64_t column_idx,
uint8_t* out_data, int out_dtype, int64_t start, int64_t count);
int64_t pq_read_string_single_file(const char* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data,
std::vector<uint32_t> *offset_vec=NULL, std::vector<uint8_t> *data_vec=NULL);
int pq_read_string_parallel_single_file(const char* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data, int64_t start, int64_t count,
std::vector<uint32_t> *offset_vec=NULL, std::vector<uint8_t> *data_vec=NULL);
} // extern "C"
#endif // _MSC_VER
int64_t pq_get_size(std::string* file_name, int64_t column_idx);
int64_t pq_read(std::string* file_name, int64_t column_idx,
uint8_t *out_data, int out_dtype);
int pq_read_parallel(std::string* file_name, int64_t column_idx,
uint8_t* out_data, int out_dtype, int64_t start, int64_t count);
int pq_read_string(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data);
int pq_read_string_parallel(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data, int64_t start, int64_t count);
PyMODINIT_FUNC PyInit_parquet_cpp(void) {
PyObject *m;
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT, "parquet_cpp", "No docs", -1, NULL, };
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
PyObject_SetAttrString(m, "read",
PyLong_FromVoidPtr((void*)(&pq_read)));
PyObject_SetAttrString(m, "read_parallel",
PyLong_FromVoidPtr((void*)(&pq_read_parallel)));
PyObject_SetAttrString(m, "get_size",
PyLong_FromVoidPtr((void*)(&pq_get_size)));
PyObject_SetAttrString(m, "read_string",
PyLong_FromVoidPtr((void*)(&pq_read_string)));
PyObject_SetAttrString(m, "read_string_parallel",
PyLong_FromVoidPtr((void*)(&pq_read_string_parallel)));
return m;
}
std::vector<std::string> get_pq_pieces(std::string* file_name)
{
#define CHECK(expr, msg) if(!(expr)){std::cerr << msg << std::endl; PyGILState_Release(gilstate); return std::vector<std::string>();}
std::vector<std::string> paths;
auto gilstate = PyGILState_Ensure();
// import pyarrow.parquet, FIXME: is this import reliable?
PyObject* pq_mod = PyImport_ImportModule("pyarrow.parquet");
// ds = pq.ParquetDataset(file_name)
PyObject* ds = PyObject_CallMethod(pq_mod, "ParquetDataset", "s", file_name->c_str());
CHECK(!PyErr_Occurred(), "Python error during Parquet dataset metadata")
Py_DECREF(pq_mod);
// all_peices = ds.pieces
PyObject* all_peices = PyObject_GetAttrString(ds, "pieces");
Py_DECREF(ds);
// paths.append(piece.path) for piece in all peices
PyObject *iterator = PyObject_GetIter(all_peices);
Py_DECREF(all_peices);
PyObject *piece;
if (iterator == NULL) {
// printf("empty\n");
PyGILState_Release(gilstate);
Py_DECREF(iterator);
return paths;
}
while (piece = PyIter_Next(iterator)) {
PyObject* p = PyObject_GetAttrString(piece, "path");
const char *c_path = PyUnicode_AsUTF8(p);
// printf("piece %s\n", c_path);
paths.push_back(std::string(c_path));
Py_DECREF(piece);
Py_DECREF(p);
}
Py_DECREF(iterator);
CHECK(!PyErr_Occurred(), "Python error during Parquet dataset metadata")
PyGILState_Release(gilstate);
return paths;
#undef CHECK
}
int64_t pq_get_size(std::string* file_name, int64_t column_idx)
{
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
int64_t ret = 0;
std::vector<std::string> all_files = get_pq_pieces(file_name);
for (const auto& inner_file : all_files)
{
ret += pq_get_size_single_file(inner_file.c_str(), column_idx);
}
// std::cout << "total pq dir size: " << ret << '\n';
return ret;
}
else
{
return pq_get_size_single_file(file_name->c_str(), column_idx);
}
return 0;
}
int64_t pq_read(std::string* file_name, int64_t column_idx,
uint8_t *out_data, int out_dtype)
{
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
std::vector<std::string> all_files = get_pq_pieces(file_name);
int64_t byte_offset = 0;
for (const auto& inner_file : all_files)
{
byte_offset += pq_read_single_file(inner_file.c_str(), column_idx, out_data+byte_offset, out_dtype);
}
// std::cout << "total pq dir size: " << byte_offset << '\n';
return byte_offset;
}
else
{
return pq_read_single_file(file_name->c_str(), column_idx, out_data, out_dtype);
}
return 0;
}
int pq_read_parallel(std::string* file_name, int64_t column_idx,
uint8_t* out_data, int out_dtype, int64_t start, int64_t count)
{
// printf("read parquet parallel column: %lld start: %lld count: %lld\n",
// column_idx, start, count);
if (count==0) {
return 0;
}
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
// TODO: get file sizes on root rank only
std::vector<std::string> all_files = get_pq_pieces(file_name);
// skip whole files if no need to read any rows
int file_ind = 0;
int64_t file_size = pq_get_size_single_file(all_files[0].c_str(), column_idx);
while (start >= file_size)
{
start -= file_size;
file_ind++;
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
int dtype_size = pq_type_sizes[out_dtype];
// std::cout << "dtype_size: " << dtype_size << '\n';
// read data
int64_t read_rows = 0;
while (read_rows<count)
{
int64_t rows_to_read = std::min(count-read_rows, file_size-start);
pq_read_parallel_single_file(all_files[file_ind].c_str(), column_idx,
out_data+read_rows*dtype_size, out_dtype, start, rows_to_read);
read_rows += rows_to_read;
start = 0; // start becomes 0 after reading non-empty first chunk
file_ind++;
// std::cout << "next file: " << all_files[file_ind] << '\n';
if (read_rows<count)
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
return 0;
// std::cout << "total pq dir size: " << byte_offset << '\n';
}
else
{
return pq_read_parallel_single_file(file_name->c_str(), column_idx,
out_data, out_dtype, start, count);
}
return 0;
}
int pq_read_string(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data)
{
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
std::vector<std::string> all_files = get_pq_pieces(file_name);
std::vector<uint32_t> offset_vec;
std::vector<uint8_t> data_vec;
int32_t last_offset = 0;
int64_t res = 0;
for (const auto& inner_file : all_files)
{
int64_t n_vals = pq_read_string_single_file(inner_file.c_str(), column_idx, NULL, NULL, &offset_vec, &data_vec);
if (n_vals==-1)
continue;
int size = offset_vec.size();
for(int64_t i=1; i<=n_vals+1; i++)
offset_vec[size-i] += last_offset;
last_offset = offset_vec[size-1];
offset_vec.pop_back();
res += n_vals;
}
offset_vec.push_back(last_offset);
*out_offsets = new uint32_t[offset_vec.size()];
*out_data = new uint8_t[data_vec.size()];
memcpy(*out_offsets, offset_vec.data(), offset_vec.size()*sizeof(uint32_t));
memcpy(*out_data, data_vec.data(), data_vec.size());
// for(int i=0; i<offset_vec.size(); i++)
// std::cout << (*out_offsets)[i] << ' ';
// std::cout << '\n';
// std::cout << "string dir read done" << '\n';
return res;
}
else
{
return pq_read_string_single_file(file_name->c_str(), column_idx, out_offsets, out_data);
}
return 0;
}
int pq_read_string_parallel(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data, int64_t start, int64_t count)
{
// printf("read parquet parallel str file: %s column: %lld start: %lld count: %lld\n",
// file_name->c_str(), column_idx, start, count);
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
std::vector<std::string> all_files = get_pq_pieces(file_name);
// skip whole files if no need to read any rows
int file_ind = 0;
int64_t file_size = pq_get_size_single_file(all_files[0].c_str(), column_idx);
while (start >= file_size)
{
start -= file_size;
file_ind++;
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
int64_t res = 0;
std::vector<uint32_t> offset_vec;
std::vector<uint8_t> data_vec;
// read data
int64_t last_offset = 0;
int64_t read_rows = 0;
while (read_rows<count)
{
int64_t rows_to_read = std::min(count-read_rows, file_size-start);
if (rows_to_read>0)
{
pq_read_string_parallel_single_file(all_files[file_ind].c_str(), column_idx,
NULL, NULL, start, rows_to_read, &offset_vec, &data_vec);
int size = offset_vec.size();
for(int64_t i=1; i<=rows_to_read+1; i++)
offset_vec[size-i] += last_offset;
last_offset = offset_vec[size-1];
offset_vec.pop_back();
res += rows_to_read;
}
read_rows += rows_to_read;
start = 0; // start becomes 0 after reading non-empty first chunk
file_ind++;
if (read_rows<count)
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
offset_vec.push_back(last_offset);
*out_offsets = new uint32_t[offset_vec.size()];
*out_data = new uint8_t[data_vec.size()];
memcpy(*out_offsets, offset_vec.data(), offset_vec.size()*sizeof(uint32_t));
memcpy(*out_data, data_vec.data(), data_vec.size());
return res;
}
else
{
return pq_read_string_parallel_single_file(file_name->c_str(), column_idx,
out_offsets, out_data, start, count);
}
return 0;
}
<commit_msg>parquet pieces handle single piece, no piece checking<commit_after>#include "mpi.h"
#include <Python.h>
#include <string>
#include <iostream>
#include <cstring>
#include <cmath>
// just include parquet reader on Windows since the GCC ABI change issue
// doesn't exist, and VC linker removes unused lib symbols
#if defined(_MSC_VER) || defined(BUILTIN_PARQUET_READER)
#include <parquet_reader/hpat_parquet_reader.cpp>
#else
// parquet type sizes (NOT arrow)
// boolean, int32, int64, int96, float, double
int pq_type_sizes[] = {1, 4, 8, 12, 4, 8};
extern "C" {
int64_t pq_get_size_single_file(const char* file_name, int64_t column_idx);
int64_t pq_read_single_file(const char* file_name, int64_t column_idx, uint8_t *out,
int out_dtype);
int pq_read_parallel_single_file(const char* file_name, int64_t column_idx,
uint8_t* out_data, int out_dtype, int64_t start, int64_t count);
int64_t pq_read_string_single_file(const char* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data,
std::vector<uint32_t> *offset_vec=NULL, std::vector<uint8_t> *data_vec=NULL);
int pq_read_string_parallel_single_file(const char* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data, int64_t start, int64_t count,
std::vector<uint32_t> *offset_vec=NULL, std::vector<uint8_t> *data_vec=NULL);
} // extern "C"
#endif // _MSC_VER
int64_t pq_get_size(std::string* file_name, int64_t column_idx);
int64_t pq_read(std::string* file_name, int64_t column_idx,
uint8_t *out_data, int out_dtype);
int pq_read_parallel(std::string* file_name, int64_t column_idx,
uint8_t* out_data, int out_dtype, int64_t start, int64_t count);
int pq_read_string(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data);
int pq_read_string_parallel(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data, int64_t start, int64_t count);
PyMODINIT_FUNC PyInit_parquet_cpp(void) {
PyObject *m;
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT, "parquet_cpp", "No docs", -1, NULL, };
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
PyObject_SetAttrString(m, "read",
PyLong_FromVoidPtr((void*)(&pq_read)));
PyObject_SetAttrString(m, "read_parallel",
PyLong_FromVoidPtr((void*)(&pq_read_parallel)));
PyObject_SetAttrString(m, "get_size",
PyLong_FromVoidPtr((void*)(&pq_get_size)));
PyObject_SetAttrString(m, "read_string",
PyLong_FromVoidPtr((void*)(&pq_read_string)));
PyObject_SetAttrString(m, "read_string_parallel",
PyLong_FromVoidPtr((void*)(&pq_read_string_parallel)));
return m;
}
std::vector<std::string> get_pq_pieces(std::string* file_name)
{
#define CHECK(expr, msg) if(!(expr)){std::cerr << msg << std::endl; PyGILState_Release(gilstate); return std::vector<std::string>();}
std::vector<std::string> paths;
auto gilstate = PyGILState_Ensure();
// import pyarrow.parquet, FIXME: is this import reliable?
PyObject* pq_mod = PyImport_ImportModule("pyarrow.parquet");
// ds = pq.ParquetDataset(file_name)
PyObject* ds = PyObject_CallMethod(pq_mod, "ParquetDataset", "s", file_name->c_str());
CHECK(!PyErr_Occurred(), "Python error during Parquet dataset metadata")
Py_DECREF(pq_mod);
// all_peices = ds.pieces
PyObject* all_peices = PyObject_GetAttrString(ds, "pieces");
Py_DECREF(ds);
// paths.append(piece.path) for piece in all peices
PyObject *iterator = PyObject_GetIter(all_peices);
Py_DECREF(all_peices);
PyObject *piece;
if (iterator == NULL) {
// printf("empty\n");
PyGILState_Release(gilstate);
Py_DECREF(iterator);
return paths;
}
while (piece = PyIter_Next(iterator)) {
PyObject* p = PyObject_GetAttrString(piece, "path");
const char *c_path = PyUnicode_AsUTF8(p);
// printf("piece %s\n", c_path);
paths.push_back(std::string(c_path));
Py_DECREF(piece);
Py_DECREF(p);
}
Py_DECREF(iterator);
CHECK(!PyErr_Occurred(), "Python error during Parquet dataset metadata")
PyGILState_Release(gilstate);
return paths;
#undef CHECK
}
int64_t pq_get_size(std::string* file_name, int64_t column_idx)
{
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() == 0) {
printf("empty parquet dataset\n");
return 0;
}
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
int64_t ret = 0;
std::vector<std::string> all_files = get_pq_pieces(file_name);
for (const auto& inner_file : all_files)
{
ret += pq_get_size_single_file(inner_file.c_str(), column_idx);
}
// std::cout << "total pq dir size: " << ret << '\n';
return ret;
}
else
{
return pq_get_size_single_file(all_files[0].c_str(), column_idx);
}
return 0;
}
int64_t pq_read(std::string* file_name, int64_t column_idx,
uint8_t *out_data, int out_dtype)
{
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() == 0) {
printf("empty parquet dataset\n");
return 0;
}
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
std::vector<std::string> all_files = get_pq_pieces(file_name);
int64_t byte_offset = 0;
for (const auto& inner_file : all_files)
{
byte_offset += pq_read_single_file(inner_file.c_str(), column_idx, out_data+byte_offset, out_dtype);
}
// std::cout << "total pq dir size: " << byte_offset << '\n';
return byte_offset;
}
else
{
return pq_read_single_file(all_files[0].c_str(), column_idx, out_data, out_dtype);
}
return 0;
}
int pq_read_parallel(std::string* file_name, int64_t column_idx,
uint8_t* out_data, int out_dtype, int64_t start, int64_t count)
{
// printf("read parquet parallel column: %lld start: %lld count: %lld\n",
// column_idx, start, count);
if (count==0) {
return 0;
}
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() == 0) {
printf("empty parquet dataset\n");
return 0;
}
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
// TODO: get file sizes on root rank only
std::vector<std::string> all_files = get_pq_pieces(file_name);
// skip whole files if no need to read any rows
int file_ind = 0;
int64_t file_size = pq_get_size_single_file(all_files[0].c_str(), column_idx);
while (start >= file_size)
{
start -= file_size;
file_ind++;
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
int dtype_size = pq_type_sizes[out_dtype];
// std::cout << "dtype_size: " << dtype_size << '\n';
// read data
int64_t read_rows = 0;
while (read_rows<count)
{
int64_t rows_to_read = std::min(count-read_rows, file_size-start);
pq_read_parallel_single_file(all_files[file_ind].c_str(), column_idx,
out_data+read_rows*dtype_size, out_dtype, start, rows_to_read);
read_rows += rows_to_read;
start = 0; // start becomes 0 after reading non-empty first chunk
file_ind++;
// std::cout << "next file: " << all_files[file_ind] << '\n';
if (read_rows<count)
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
return 0;
// std::cout << "total pq dir size: " << byte_offset << '\n';
}
else
{
return pq_read_parallel_single_file(all_files[0].c_str(), column_idx,
out_data, out_dtype, start, count);
}
return 0;
}
int pq_read_string(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data)
{
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() == 0) {
printf("empty parquet dataset\n");
return 0;
}
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
std::vector<std::string> all_files = get_pq_pieces(file_name);
std::vector<uint32_t> offset_vec;
std::vector<uint8_t> data_vec;
int32_t last_offset = 0;
int64_t res = 0;
for (const auto& inner_file : all_files)
{
int64_t n_vals = pq_read_string_single_file(inner_file.c_str(), column_idx, NULL, NULL, &offset_vec, &data_vec);
if (n_vals==-1)
continue;
int size = offset_vec.size();
for(int64_t i=1; i<=n_vals+1; i++)
offset_vec[size-i] += last_offset;
last_offset = offset_vec[size-1];
offset_vec.pop_back();
res += n_vals;
}
offset_vec.push_back(last_offset);
*out_offsets = new uint32_t[offset_vec.size()];
*out_data = new uint8_t[data_vec.size()];
memcpy(*out_offsets, offset_vec.data(), offset_vec.size()*sizeof(uint32_t));
memcpy(*out_data, data_vec.data(), data_vec.size());
// for(int i=0; i<offset_vec.size(); i++)
// std::cout << (*out_offsets)[i] << ' ';
// std::cout << '\n';
// std::cout << "string dir read done" << '\n';
return res;
}
else
{
return pq_read_string_single_file(all_files[0].c_str(), column_idx, out_offsets, out_data);
}
return 0;
}
int pq_read_string_parallel(std::string* file_name, int64_t column_idx,
uint32_t **out_offsets, uint8_t **out_data, int64_t start, int64_t count)
{
// printf("read parquet parallel str file: %s column: %lld start: %lld count: %lld\n",
// file_name->c_str(), column_idx, start, count);
std::vector<std::string> all_files = get_pq_pieces(file_name);
if (all_files.size() == 0) {
printf("empty parquet dataset\n");
return 0;
}
if (all_files.size() > 1)
{
// std::cout << "pq path is dir" << '\n';
std::vector<std::string> all_files = get_pq_pieces(file_name);
// skip whole files if no need to read any rows
int file_ind = 0;
int64_t file_size = pq_get_size_single_file(all_files[0].c_str(), column_idx);
while (start >= file_size)
{
start -= file_size;
file_ind++;
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
int64_t res = 0;
std::vector<uint32_t> offset_vec;
std::vector<uint8_t> data_vec;
// read data
int64_t last_offset = 0;
int64_t read_rows = 0;
while (read_rows<count)
{
int64_t rows_to_read = std::min(count-read_rows, file_size-start);
if (rows_to_read>0)
{
pq_read_string_parallel_single_file(all_files[file_ind].c_str(), column_idx,
NULL, NULL, start, rows_to_read, &offset_vec, &data_vec);
int size = offset_vec.size();
for(int64_t i=1; i<=rows_to_read+1; i++)
offset_vec[size-i] += last_offset;
last_offset = offset_vec[size-1];
offset_vec.pop_back();
res += rows_to_read;
}
read_rows += rows_to_read;
start = 0; // start becomes 0 after reading non-empty first chunk
file_ind++;
if (read_rows<count)
file_size = pq_get_size_single_file(all_files[file_ind].c_str(), column_idx);
}
offset_vec.push_back(last_offset);
*out_offsets = new uint32_t[offset_vec.size()];
*out_data = new uint8_t[data_vec.size()];
memcpy(*out_offsets, offset_vec.data(), offset_vec.size()*sizeof(uint32_t));
memcpy(*out_data, data_vec.data(), data_vec.size());
return res;
}
else
{
return pq_read_string_parallel_single_file(all_files[0].c_str(), column_idx,
out_offsets, out_data, start, count);
}
return 0;
}
<|endoftext|> |
<commit_before>// MFEM Example 1 - Parallel NURBS Version
//
// Compile with: make ex1p
//
// Sample runs: mpirun -np 4 ex1p -m ../../data/square-disc.mesh
// mpirun -np 4 ex1p -m ../../data/star.mesh
// mpirun -np 4 ex1p -m ../../data/escher.mesh
// mpirun -np 4 ex1p -m ../../data/fichera.mesh
// mpirun -np 4 ex1p -m ../../data/square-disc-p2.vtk -o 2
// mpirun -np 4 ex1p -m ../../data/square-disc-p3.mesh -o 3
// mpirun -np 4 ex1p -m ../../data/square-disc-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../../data/disc-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../../data/pipe-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../../data/ball-nurbs.mesh -o 2
// mpirun -np 4 ex1p -m ../../data/star-surf.mesh
// mpirun -np 4 ex1p -m ../../data/square-disc-surf.mesh
// mpirun -np 4 ex1p -m ../../data/inline-segment.mesh
// mpirun -np 4 ex1p -m ../../data/amr-quad.mesh
// mpirun -np 4 ex1p -m ../../data/amr-hex.mesh
// mpirun -np 4 ex1p -m ../../data/mobius-strip.mesh
// mpirun -np 4 ex1p -m ../../data/mobius-strip.mesh -o -1 -sc
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../../data/star.mesh";
Array<int> order(1);
order[0] = 1;
bool static_cond = false;
bool visualization = 1;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 3. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 4. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels =
(int)floor(log(10000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 5. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
if (!pmesh->NURBSext) {
int par_ref_levels = 2;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh->UniformRefinement();
}
}
// 6. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
NURBSExtension *NURBSext = NULL;
int own_fec = 0;
if (order[0] == -1) // Isoparametric
{
if (pmesh->GetNodes())
{
fec = pmesh->GetNodes()->OwnFEC();
own_fec = 0;
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
cout <<"Mesh does not have FEs --> Assume order 1.\n";
fec = new H1_FECollection(1, dim);
own_fec = 1;
}
}
else if (pmesh->NURBSext && (order[0] > 0) ) // Subparametric NURBS
{
fec = new NURBSFECollection(order[0]);
own_fec = 1;
int nkv = pmesh->NURBSext->GetNKV();
if (order.Size() == 1)
{
int tmp = order[0];
order.SetSize(nkv);
order = tmp;
}
if (order.Size() != nkv ) { mfem_error("Wrong number of orders set."); }
NURBSext = new NURBSExtension(pmesh->NURBSext, order);
}
else
{
if (order.Size() > 1) { cout <<"Wrong number of orders set, needs one.\n"; }
fec = new H1_FECollection(abs(order[0]), dim);
own_fec = 1;
}
ParFiniteElementSpace *fespace = new ParFiniteElementSpace(pmesh,NURBSext,fec);
HYPRE_Int size = fespace->GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
// 7. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh->bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh->bdr_attributes.Max());
ess_bdr = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 8. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm *b = new ParLinearForm(fespace);
ConstantCoefficient one(1.0);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
b->Assemble();
// 9. Define the solution vector x as a parallel finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
ParGridFunction x(fespace);
x = 0.0;
// 10. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
ParBilinearForm *a = new ParBilinearForm(fespace);
a->AddDomainIntegrator(new DiffusionIntegrator(one));
// 11. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
HypreParMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
}
// 12. Define and apply a parallel PCG solver for AX=B with the BoomerAMG
// preconditioner from hypre.
HypreSolver *amg = new HypreBoomerAMG(A);
HyprePCG *pcg = new HyprePCG(A);
pcg->SetTol(1e-12);
pcg->SetMaxIter(200);
pcg->SetPrintLevel(2);
pcg->SetPreconditioner(*amg);
pcg->Mult(B, X);
// 13. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a->RecoverFEMSolution(X, *b, x);
// 14. Save the refined mesh and the solution in parallel. This output can
// be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 15. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << *pmesh << x << flush;
}
// 16. Save data in the VisIt format
VisItDataCollection visit_dc("Example1-Parallel", pmesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 17. Free the used memory.
delete pcg;
delete amg;
delete a;
delete b;
delete fespace;
if (own_fec) { delete fec; }
delete pmesh;
MPI_Finalize();
return 0;
}
<commit_msg>make style<commit_after>// MFEM Example 1 - Parallel NURBS Version
//
// Compile with: make nurbs_ex1p
//
// Sample runs: mpirun -np 4 nurbs_ex1p -m ../../data/square-disc.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/star.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/escher.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/fichera.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-p2.vtk -o 2
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-p3.mesh -o 3
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/disc-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/pipe-nurbs.mesh -o -1
// mpirun -np 4 nurbs_ex1p -m ../../data/ball-nurbs.mesh -o 2
// mpirun -np 4 nurbs_ex1p -m ../../data/star-surf.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/square-disc-surf.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/inline-segment.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/amr-quad.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/amr-hex.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/mobius-strip.mesh
// mpirun -np 4 nurbs_ex1p -m ../../data/mobius-strip.mesh -o -1 -sc
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options.
const char *mesh_file = "../../data/star.mesh";
Array<int> order(1);
order[0] = 1;
bool static_cond = false;
bool visualization = 1;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 3. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 4. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels =
(int)floor(log(10000./mesh->GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh->UniformRefinement();
}
}
// 5. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
if (!pmesh->NURBSext)
{
int par_ref_levels = 2;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh->UniformRefinement();
}
}
// 6. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
NURBSExtension *NURBSext = NULL;
int own_fec = 0;
if (order[0] == -1) // Isoparametric
{
if (pmesh->GetNodes())
{
fec = pmesh->GetNodes()->OwnFEC();
own_fec = 0;
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
else
{
cout <<"Mesh does not have FEs --> Assume order 1.\n";
fec = new H1_FECollection(1, dim);
own_fec = 1;
}
}
else if (pmesh->NURBSext && (order[0] > 0) ) // Subparametric NURBS
{
fec = new NURBSFECollection(order[0]);
own_fec = 1;
int nkv = pmesh->NURBSext->GetNKV();
if (order.Size() == 1)
{
int tmp = order[0];
order.SetSize(nkv);
order = tmp;
}
if (order.Size() != nkv ) { mfem_error("Wrong number of orders set."); }
NURBSext = new NURBSExtension(pmesh->NURBSext, order);
}
else
{
if (order.Size() > 1) { cout <<"Wrong number of orders set, needs one.\n"; }
fec = new H1_FECollection(abs(order[0]), dim);
own_fec = 1;
}
ParFiniteElementSpace *fespace = new ParFiniteElementSpace(pmesh,NURBSext,fec);
HYPRE_Int size = fespace->GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
// 7. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh->bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh->bdr_attributes.Max());
ess_bdr = 1;
fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 8. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm *b = new ParLinearForm(fespace);
ConstantCoefficient one(1.0);
b->AddDomainIntegrator(new DomainLFIntegrator(one));
b->Assemble();
// 9. Define the solution vector x as a parallel finite element grid function
// corresponding to fespace. Initialize x with initial guess of zero,
// which satisfies the boundary conditions.
ParGridFunction x(fespace);
x = 0.0;
// 10. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the Diffusion
// domain integrator.
ParBilinearForm *a = new ParBilinearForm(fespace);
a->AddDomainIntegrator(new DiffusionIntegrator(one));
// 11. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (static_cond) { a->EnableStaticCondensation(); }
a->Assemble();
HypreParMatrix A;
Vector B, X;
a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
if (myid == 0)
{
cout << "Size of linear system: " << A.GetGlobalNumRows() << endl;
}
// 12. Define and apply a parallel PCG solver for AX=B with the BoomerAMG
// preconditioner from hypre.
HypreSolver *amg = new HypreBoomerAMG(A);
HyprePCG *pcg = new HyprePCG(A);
pcg->SetTol(1e-12);
pcg->SetMaxIter(200);
pcg->SetPrintLevel(2);
pcg->SetPreconditioner(*amg);
pcg->Mult(B, X);
// 13. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a->RecoverFEMSolution(X, *b, x);
// 14. Save the refined mesh and the solution in parallel. This output can
// be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 15. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << *pmesh << x << flush;
}
// 16. Save data in the VisIt format
VisItDataCollection visit_dc("Example1-Parallel", pmesh);
visit_dc.RegisterField("solution", &x);
visit_dc.Save();
// 17. Free the used memory.
delete pcg;
delete amg;
delete a;
delete b;
delete fespace;
if (own_fec) { delete fec; }
delete pmesh;
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* qt4.cpp : QT4 interface
****************************************************************************
* Copyright (C) 2006-2007 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <zorglub@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include <QApplication>
#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "input_manager.hpp"
#include "main_interface.hpp"
#include "../../../share/vlc32x32.xpm"
/*****************************************************************************
* Local prototypes.
*****************************************************************************/
static int Open ( vlc_object_t * );
static void Close ( vlc_object_t * );
static int OpenDialogs ( vlc_object_t * );
static void Run ( intf_thread_t * );
static void Init ( intf_thread_t * );
static void ShowDialog ( intf_thread_t *, int, int, intf_dialog_args_t * );
/*****************************************************************************
* Module descriptor
*****************************************************************************/
#define ALWAYS_VIDEO_TEXT N_("Always show a video screen, with a cone " \
"when there is audio only.")
#define ALWAYS_VIDEO_LONGTEXT N_("Start VLC with a cone image, and display it" \
" when there is no video track. " \
"Visualisations are enabled." )
#define ADVANCED_PREFS_TEXT N_("Show advanced prefs over simple")
#define ADVANCED_PREFS_LONGTEXT N_("Show advanced preferences and not simple" \
"preferences when opening the preferences " \
"dialog.")
#define SYSTRAY_TEXT N_("Show a systray icon to control VLC")
#define SYSTRAY_LONGTEXT N_("Show in the taskbar, a systray icon" \
"in order to control VLC media player" \
"for basic actions")
#define MINIMIZED_TEXT N_("Start VLC only with a systray icon")
#define MINIMIZED_LONGTEXT N_("When you launch VLC with that option" \
"VLC will start just with an icon in" \
"your taskbar")
#define TITLE_TEXT N_("Show playing item name in window title")
#define TITLE_LONGTEXT N_("Show the name of the song or video in the " \
"controler window title")
#define FILEDIALOG_PATH_TEXT N_("path to use in file dialog")
#define FILEDIALOG_PATH_LONGTEXT N_("path to use in file dialog")
#define ADVANCED_OPTIONS_TEXT N_("Advanced options")
#define ADVANCED_OPTIONS_LONGTEXT N_("Activate by default all the" \
"Advanced options for geeks")
#define SHOWFLAGS_TEXT N_("Define what columns to show in playlist window")
#define SHOWFLAGS_LONGTEXT N_("Enter the sum of the options that you want:\n" \
"Title: 1\nDuration: 2\nArtist: 4\nGenre: 8\nCopyright: 10\n" \
"Collection/album: 20\nRating: 100\n")
vlc_module_begin();
set_shortname( (char *)"Qt" );
set_description( (char*)_("Qt interface") );
set_category( CAT_INTERFACE ) ;
set_subcategory( SUBCAT_INTERFACE_MAIN );
set_capability( "interface", 151 );
set_callbacks( Open, Close );
set_program( "qvlc" );
add_shortcut("qt");
add_submodule();
set_description( "Dialogs provider" );
set_capability( "dialogs provider", 51 );
add_bool( "qt-always-video", VLC_FALSE, NULL, ALWAYS_VIDEO_TEXT,
ALWAYS_VIDEO_LONGTEXT, VLC_TRUE );
add_bool( "qt-advanced-pref", VLC_FALSE, NULL, ADVANCED_PREFS_TEXT,
ADVANCED_PREFS_LONGTEXT, VLC_FALSE );
add_bool( "qt-system-tray", VLC_TRUE, NULL, SYSTRAY_TEXT,
SYSTRAY_LONGTEXT, VLC_FALSE);
add_bool( "qt-start-minimized", VLC_FALSE, NULL, MINIMIZED_TEXT,
MINIMIZED_LONGTEXT, VLC_TRUE);
add_bool( "qt-name-in-title", VLC_TRUE, NULL, TITLE_TEXT,
TITLE_LONGTEXT, VLC_FALSE );
add_string( "qt-filedialog-path", NULL, NULL, FILEDIALOG_PATH_TEXT,
FILEDIALOG_PATH_LONGTEXT, VLC_TRUE);
change_autosave();
change_internal();
add_bool( "qt-adv-options", VLC_FALSE, NULL, ADVANCED_OPTIONS_TEXT,
ADVANCED_OPTIONS_LONGTEXT, VLC_TRUE );
add_integer( "qt-pl-showflags",
VLC_META_ENGINE_ARTIST|VLC_META_ENGINE_TITLE|
VLC_META_ENGINE_DURATION|VLC_META_ENGINE_COLLECTION,
NULL, SHOWFLAGS_TEXT,
SHOWFLAGS_LONGTEXT, VLC_TRUE );
set_callbacks( OpenDialogs, Close );
vlc_module_end();
/*****************************************************************************
* Module callbacks
*****************************************************************************/
static int Open( vlc_object_t *p_this )
{
intf_thread_t *p_intf = (intf_thread_t *)p_this;
p_intf->pf_run = Run;
#if defined HAVE_GETENV && defined Q_WS_X11
if( !getenv( "DISPLAY" ) )
{
msg_Err(p_intf, "no X server");
return VLC_EGENERIC;
}
#endif
p_intf->p_sys = (intf_sys_t *)malloc(sizeof( intf_sys_t ) );
if( !p_intf->p_sys )
{
msg_Err(p_intf, "Out of memory");
return VLC_ENOMEM;
}
memset( p_intf->p_sys, 0, sizeof( intf_sys_t ) );
p_intf->p_sys->p_playlist = pl_Yield( p_intf );
p_intf->p_sys->p_sub = msg_Subscribe( p_intf, MSG_QUEUE_NORMAL );
p_intf->b_play = VLC_TRUE;
return VLC_SUCCESS;
}
static int OpenDialogs( vlc_object_t *p_this )
{
intf_thread_t *p_intf = (intf_thread_t *)p_this;
int val = Open( p_this );
if( val )
return val;
p_intf->pf_show_dialog = ShowDialog;
return VLC_SUCCESS;
}
static void Close( vlc_object_t *p_this )
{
intf_thread_t *p_intf = (intf_thread_t *)p_this;
vlc_mutex_lock( &p_intf->object_lock );
p_intf->b_dead = VLC_TRUE;
vlc_mutex_unlock( &p_intf->object_lock );
vlc_object_release( p_intf->p_sys->p_playlist );
msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
free( p_intf->p_sys );
}
/*****************************************************************************
* Initialize the interface or the dialogs provider
*****************************************************************************/
static void Run( intf_thread_t *p_intf )
{
if( p_intf->pf_show_dialog )
{
if( vlc_thread_create( p_intf, "Qt dialogs", Init, 0, VLC_TRUE ) )
msg_Err( p_intf, "failed to create Qt dialogs thread" );
}
else
Init( p_intf );
}
static void Init( intf_thread_t *p_intf )
{
char dummy[] = "";
char *argv[] = { dummy };
int argc = 1;
Q_INIT_RESOURCE( vlc );
QApplication *app = new QApplication( argc, argv , true );
app->setWindowIcon( QIcon( QPixmap(vlc_xpm) ) );
p_intf->p_sys->p_app = app;
// Initialize timers
DialogsProvider::getInstance( p_intf );
// Normal interface
if( !p_intf->pf_show_dialog )
{
MainInterface *p_mi = new MainInterface( p_intf );
p_intf->p_sys->p_mi = p_mi;
p_mi->show();
}
if( p_intf->pf_show_dialog )
vlc_thread_ready( p_intf );
/* Start playing if needed */
if( !p_intf->pf_show_dialog && p_intf->b_play )
{
playlist_Control( THEPL, PLAYLIST_AUTOPLAY, VLC_FALSE );
}
p_intf->pf_show_dialog = ShowDialog;
app->setQuitOnLastWindowClosed( false );
app->exec();
MainInputManager::killInstance();
DialogsProvider::killInstance();
delete p_intf->p_sys->p_mi;
}
/*****************************************************************************
* Callback to show a dialog
*****************************************************************************/
static void ShowDialog( intf_thread_t *p_intf, int i_dialog_event, int i_arg,
intf_dialog_args_t *p_arg )
{
DialogEvent *event = new DialogEvent( i_dialog_event, i_arg, p_arg );
QApplication::postEvent( THEDP, static_cast<QEvent*>(event) );
}
/*****************************************************************************
* PopupMenuCB: callback to show the popupmenu.
* We don't show the menu directly here because we don't want the
* caller to block for a too long time.
*****************************************************************************/
static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable,
vlc_value_t old_val, vlc_value_t new_val, void *param )
{
intf_thread_t *p_intf = (intf_thread_t *)param;
ShowDialog( p_intf, INTF_DIALOG_POPUPMENU, new_val.b_bool, 0 );
return VLC_SUCCESS;
}
<commit_msg>Fix the qt-pl-showflags tooltip Hide the qt-adv-option as it is doing nothing<commit_after>/*****************************************************************************
* qt4.cpp : QT4 interface
****************************************************************************
* Copyright (C) 2006-2007 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <zorglub@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include <QApplication>
#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "input_manager.hpp"
#include "main_interface.hpp"
#include "../../../share/vlc32x32.xpm"
/*****************************************************************************
* Local prototypes.
*****************************************************************************/
static int Open ( vlc_object_t * );
static void Close ( vlc_object_t * );
static int OpenDialogs ( vlc_object_t * );
static void Run ( intf_thread_t * );
static void Init ( intf_thread_t * );
static void ShowDialog ( intf_thread_t *, int, int, intf_dialog_args_t * );
/*****************************************************************************
* Module descriptor
*****************************************************************************/
#define ALWAYS_VIDEO_TEXT N_("Always show a video screen, with a cone " \
"when there is audio only.")
#define ALWAYS_VIDEO_LONGTEXT N_("Start VLC with a cone image, and display it" \
" when there is no video track. " \
"Visualisations are enabled." )
#define ADVANCED_PREFS_TEXT N_("Show advanced prefs over simple")
#define ADVANCED_PREFS_LONGTEXT N_("Show advanced preferences and not simple" \
"preferences when opening the preferences " \
"dialog.")
#define SYSTRAY_TEXT N_("Show a systray icon to control VLC")
#define SYSTRAY_LONGTEXT N_("Show in the taskbar, a systray icon" \
"in order to control VLC media player" \
"for basic actions")
#define MINIMIZED_TEXT N_("Start VLC only with a systray icon")
#define MINIMIZED_LONGTEXT N_("When you launch VLC with that option" \
"VLC will start just with an icon in" \
"your taskbar")
#define TITLE_TEXT N_("Show playing item name in window title")
#define TITLE_LONGTEXT N_("Show the name of the song or video in the " \
"controler window title")
#define FILEDIALOG_PATH_TEXT N_("Path to use in file dialog")
#define FILEDIALOG_PATH_LONGTEXT N_("path to use in file dialog")
/*#define ADVANCED_OPTIONS_TEXT N_("Advanced options")
#define ADVANCED_OPTIONS_LONGTEXT N_("Activate by default all the" \
"advanced options for geeks")*/
#define SHOWFLAGS_TEXT N_("Define what columns to show in playlist window")
#define SHOWFLAGS_LONGTEXT N_("Enter the sum of the options that you want: \n" \
"Title: 1; Duration: 2; Artist: 4; Genre: 8; " \
"Copyright: 16; Collection/album: 32; Rating: 256." )
vlc_module_begin();
set_shortname( (char *)"Qt" );
set_description( (char*)_("Qt interface") );
set_category( CAT_INTERFACE ) ;
set_subcategory( SUBCAT_INTERFACE_MAIN );
set_capability( "interface", 151 );
set_callbacks( Open, Close );
set_program( "qvlc" );
add_shortcut("qt");
add_submodule();
set_description( "Dialogs provider" );
set_capability( "dialogs provider", 51 );
add_bool( "qt-always-video", VLC_FALSE, NULL, ALWAYS_VIDEO_TEXT,
ALWAYS_VIDEO_LONGTEXT, VLC_TRUE );
add_bool( "qt-advanced-pref", VLC_FALSE, NULL, ADVANCED_PREFS_TEXT,
ADVANCED_PREFS_LONGTEXT, VLC_FALSE );
add_bool( "qt-system-tray", VLC_TRUE, NULL, SYSTRAY_TEXT,
SYSTRAY_LONGTEXT, VLC_FALSE);
add_bool( "qt-start-minimized", VLC_FALSE, NULL, MINIMIZED_TEXT,
MINIMIZED_LONGTEXT, VLC_TRUE);
add_bool( "qt-name-in-title", VLC_TRUE, NULL, TITLE_TEXT,
TITLE_LONGTEXT, VLC_FALSE );
add_string( "qt-filedialog-path", NULL, NULL, FILEDIALOG_PATH_TEXT,
FILEDIALOG_PATH_LONGTEXT, VLC_TRUE);
change_autosave();
change_internal();
/* add_bool( "qt-adv-options", VLC_FALSE, NULL, ADVANCED_OPTIONS_TEXT,
ADVANCED_OPTIONS_LONGTEXT, VLC_TRUE );*/
add_integer( "qt-pl-showflags",
VLC_META_ENGINE_ARTIST|VLC_META_ENGINE_TITLE|
VLC_META_ENGINE_DURATION|VLC_META_ENGINE_COLLECTION,
NULL, SHOWFLAGS_TEXT,
SHOWFLAGS_LONGTEXT, VLC_TRUE );
set_callbacks( OpenDialogs, Close );
vlc_module_end();
/*****************************************************************************
* Module callbacks
*****************************************************************************/
static int Open( vlc_object_t *p_this )
{
intf_thread_t *p_intf = (intf_thread_t *)p_this;
p_intf->pf_run = Run;
#if defined HAVE_GETENV && defined Q_WS_X11
if( !getenv( "DISPLAY" ) )
{
msg_Err(p_intf, "no X server");
return VLC_EGENERIC;
}
#endif
p_intf->p_sys = (intf_sys_t *)malloc(sizeof( intf_sys_t ) );
if( !p_intf->p_sys )
{
msg_Err(p_intf, "Out of memory");
return VLC_ENOMEM;
}
memset( p_intf->p_sys, 0, sizeof( intf_sys_t ) );
p_intf->p_sys->p_playlist = pl_Yield( p_intf );
p_intf->p_sys->p_sub = msg_Subscribe( p_intf, MSG_QUEUE_NORMAL );
p_intf->b_play = VLC_TRUE;
return VLC_SUCCESS;
}
static int OpenDialogs( vlc_object_t *p_this )
{
intf_thread_t *p_intf = (intf_thread_t *)p_this;
int val = Open( p_this );
if( val )
return val;
p_intf->pf_show_dialog = ShowDialog;
return VLC_SUCCESS;
}
static void Close( vlc_object_t *p_this )
{
intf_thread_t *p_intf = (intf_thread_t *)p_this;
vlc_mutex_lock( &p_intf->object_lock );
p_intf->b_dead = VLC_TRUE;
vlc_mutex_unlock( &p_intf->object_lock );
vlc_object_release( p_intf->p_sys->p_playlist );
msg_Unsubscribe( p_intf, p_intf->p_sys->p_sub );
free( p_intf->p_sys );
}
/*****************************************************************************
* Initialize the interface or the dialogs provider
*****************************************************************************/
static void Run( intf_thread_t *p_intf )
{
if( p_intf->pf_show_dialog )
{
if( vlc_thread_create( p_intf, "Qt dialogs", Init, 0, VLC_TRUE ) )
msg_Err( p_intf, "failed to create Qt dialogs thread" );
}
else
Init( p_intf );
}
static void Init( intf_thread_t *p_intf )
{
char dummy[] = "";
char *argv[] = { dummy };
int argc = 1;
Q_INIT_RESOURCE( vlc );
QApplication *app = new QApplication( argc, argv , true );
app->setWindowIcon( QIcon( QPixmap(vlc_xpm) ) );
p_intf->p_sys->p_app = app;
// Initialize timers
DialogsProvider::getInstance( p_intf );
// Normal interface
if( !p_intf->pf_show_dialog )
{
MainInterface *p_mi = new MainInterface( p_intf );
p_intf->p_sys->p_mi = p_mi;
p_mi->show();
}
if( p_intf->pf_show_dialog )
vlc_thread_ready( p_intf );
/* Start playing if needed */
if( !p_intf->pf_show_dialog && p_intf->b_play )
{
playlist_Control( THEPL, PLAYLIST_AUTOPLAY, VLC_FALSE );
}
p_intf->pf_show_dialog = ShowDialog;
app->setQuitOnLastWindowClosed( false );
app->exec();
MainInputManager::killInstance();
DialogsProvider::killInstance();
delete p_intf->p_sys->p_mi;
}
/*****************************************************************************
* Callback to show a dialog
*****************************************************************************/
static void ShowDialog( intf_thread_t *p_intf, int i_dialog_event, int i_arg,
intf_dialog_args_t *p_arg )
{
DialogEvent *event = new DialogEvent( i_dialog_event, i_arg, p_arg );
QApplication::postEvent( THEDP, static_cast<QEvent*>(event) );
}
/*****************************************************************************
* PopupMenuCB: callback to show the popupmenu.
* We don't show the menu directly here because we don't want the
* caller to block for a too long time.
*****************************************************************************/
static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable,
vlc_value_t old_val, vlc_value_t new_val, void *param )
{
intf_thread_t *p_intf = (intf_thread_t *)param;
ShowDialog( p_intf, INTF_DIALOG_POPUPMENU, new_val.b_bool, 0 );
return VLC_SUCCESS;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>
#include <TChain.h>
#include <TFile.h>
#include <TList.h>
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliAODEvent.h"
#include "AliAODHeader.h"
#include "AliAODTracklets.h"
#include "AliVEvent.h"
#include "AliAODHandler.h"
#include "AliAODInputHandler.h"
#include "AliMCEventHandler.h"
#include "AliInputEventHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
#include "AliLog.h"
ClassImp(AliAnalysisTaskSE)
////////////////////////////////////////////////////////////////////////
AliAODHeader* AliAnalysisTaskSE::fgAODHeader = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODTracks = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODVertices = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODV0s = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODPMDClusters = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODJets = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODFMDClusters = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODCaloClusters = NULL;
AliAODTracklets* AliAnalysisTaskSE::fgAODTracklets = NULL;
AliAnalysisTaskSE::AliAnalysisTaskSE():
AliAnalysisTask(),
fDebug(0),
fEntry(0),
fInputEvent(0x0),
fInputHandler(0x0),
fOutputAOD(0x0),
fMCEvent(0x0),
fTreeA(0x0)
{
// Default constructor
}
AliAnalysisTaskSE::AliAnalysisTaskSE(const char* name):
AliAnalysisTask(name, "AnalysisTaskSE"),
fDebug(0),
fEntry(0),
fInputEvent(0x0),
fInputHandler(0x0),
fOutputAOD(0x0),
fMCEvent(0x0),
fTreeA(0x0)
{
// Default constructor
DefineInput (0, TChain::Class());
DefineOutput(0, TTree::Class());
}
AliAnalysisTaskSE::AliAnalysisTaskSE(const AliAnalysisTaskSE& obj):
AliAnalysisTask(obj),
fDebug(0),
fEntry(0),
fInputEvent(0x0),
fInputHandler(0x0),
fOutputAOD(0x0),
fMCEvent(0x0),
fTreeA(0x0)
{
// Copy constructor
fDebug = obj.fDebug;
fEntry = obj.fEntry;
fInputEvent = obj.fInputEvent;
fInputHandler = obj.fInputHandler;
fOutputAOD = obj.fOutputAOD;
fMCEvent = obj.fMCEvent;
fTreeA = obj.fTreeA;
printf("Constructor (3) \n");
}
AliAnalysisTaskSE& AliAnalysisTaskSE::operator=(const AliAnalysisTaskSE& other)
{
// Assignment
AliAnalysisTask::operator=(other);
fDebug = other.fDebug;
fEntry = other.fEntry;
fInputEvent = other.fInputEvent;
fInputHandler = other.fInputHandler;
fOutputAOD = other.fOutputAOD;
fMCEvent = other.fMCEvent;
fTreeA = other.fTreeA;
return *this;
}
void AliAnalysisTaskSE::ConnectInputData(Option_t* /*option*/)
{
// Connect the input data
if (fDebug > 1) printf("AnalysisTaskSE::ConnectInputData() \n");
//
// ESD
//
fInputHandler = (AliInputEventHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
//
// Monte Carlo
//
AliMCEventHandler* mcH = 0;
mcH = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler());
if (mcH) fMCEvent = mcH->MCEvent();
if (fInputHandler) {
fInputEvent = fInputHandler->GetEvent();
} else if( fMCEvent ) {
AliWarning("No Input Event Handler connected, only MC Truth Event Handler") ;
} else {
AliError("No Input Event Handler connected") ;
return ;
}
}
void AliAnalysisTaskSE::CreateOutputObjects()
{
// Create the output container
//
// Default AOD
if (fDebug > 1) printf("AnalysisTaskSE::CreateOutPutData() \n");
AliAODHandler* handler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
// Check if AOD replication has been required
if (handler) {
fOutputAOD = handler->GetAOD();
fTreeA = handler->GetTree();
if (!(handler->IsStandard())) {
if ((handler->NeedsHeaderReplication()) && !(fgAODHeader))
{
if (fDebug > 1) AliInfo("Replicating header");
fgAODHeader = new AliAODHeader;
handler->AddBranch("AliAODHeader", &fgAODHeader);
}
if ((handler->NeedsTracksBranchReplication()) && !(fgAODTracks))
{
if (fDebug > 1) AliInfo("Replicating track branch\n");
fgAODTracks = new TClonesArray("AliAODTrack",500);
fgAODTracks->SetName("tracks");
handler->AddBranch("TClonesArray", &fgAODTracks);
}
if ((handler->NeedsVerticesBranchReplication()) && !(fgAODVertices))
{
if (fDebug > 1) AliInfo("Replicating vertices branch\n");
fgAODVertices = new TClonesArray("AliAODVertex",500);
fgAODVertices->SetName("vertices");
handler->AddBranch("TClonesArray", &fgAODVertices);
}
if ((handler->NeedsV0sBranchReplication()) && !(fgAODV0s))
{
if (fDebug > 1) AliInfo("Replicating V0s branch\n");
fgAODV0s = new TClonesArray("AliAODv0",500);
fgAODV0s->SetName("v0s");
handler->AddBranch("TClonesArray", &fgAODV0s);
}
if ((handler->NeedsTrackletsBranchReplication()) && !(fgAODTracklets))
{
if (fDebug > 1) AliInfo("Replicating Tracklets branch\n");
fgAODTracklets = new AliAODTracklets("tracklets","tracklets");
handler->AddBranch("AliAODTracklets", &fgAODTracklets);
}
if ((handler->NeedsPMDClustersBranchReplication()) && !(fgAODPMDClusters))
{
if (fDebug > 1) AliInfo("Replicating PMDClusters branch\n");
fgAODPMDClusters = new TClonesArray("AliAODPmdCluster",500);
fgAODPMDClusters->SetName("pmdClusters");
handler->AddBranch("TClonesArray", &fgAODPMDClusters);
}
if ((handler->NeedsJetsBranchReplication()) && !(fgAODJets))
{
if (fDebug > 1) AliInfo("Replicating Jets branch\n");
fgAODJets = new TClonesArray("AliAODJet",500);
fgAODJets->SetName("jets");
handler->AddBranch("TClonesArray", &fgAODJets);
}
if ((handler->NeedsFMDClustersBranchReplication()) && !(fgAODFMDClusters))
{
AliInfo("Replicating FMDClusters branch\n");
fgAODFMDClusters = new TClonesArray("AliAODFmdCluster",500);
fgAODFMDClusters->SetName("fmdClusters");
handler->AddBranch("TClonesArray", &fgAODFMDClusters);
}
if ((handler->NeedsCaloClustersBranchReplication()) && !(fgAODCaloClusters))
{
if (fDebug > 1) AliInfo("Replicating CaloClusters branch\n");
fgAODCaloClusters = new TClonesArray("AliAODCaloCluster",500);
fgAODCaloClusters->SetName("caloClusters");
handler->AddBranch("TClonesArray", &fgAODCaloClusters);
}
}
} else {
AliWarning("No AOD Event Handler connected.") ;
}
UserCreateOutputObjects();
}
void AliAnalysisTaskSE::Exec(Option_t* option)
{
//
// Exec analysis of one event
if (fDebug > 1) AliInfo("AliAnalysisTaskSE::Exec() \n");
if( fInputHandler )
fEntry = fInputHandler->GetReadEntry();
else if( fMCEvent )
fEntry = fMCEvent->Header()->GetEvent();
if ( !((Entry()-1)%100) && fDebug > 0)
AliInfo(Form("%s ----> Processing event # %lld", CurrentFileName(), Entry()));
AliAODHandler* handler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
AliAODInputHandler* aodH = dynamic_cast<AliAODInputHandler*>(fInputHandler);
if (handler && aodH) {
if (!(handler->IsStandard()) && !(handler->AODIsReplicated())) {
if ((handler->NeedsHeaderReplication()) && (fgAODHeader))
{
fgAODHeader = dynamic_cast<AliAODHeader*>(InputEvent()->GetHeader());
}
if ((handler->NeedsTracksBranchReplication()) && (fgAODTracks))
{
TClonesArray* tracks = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetTracks();
new (fgAODTracks) TClonesArray(*tracks);
}
if ((handler->NeedsVerticesBranchReplication()) && (fgAODVertices))
{
TClonesArray* vertices = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetVertices();
new (fgAODVertices) TClonesArray(*vertices);
}
if ((handler->NeedsV0sBranchReplication()) && (fgAODV0s))
{
TClonesArray* V0s = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetV0s();
new (fgAODV0s) TClonesArray(*V0s);
}
if ((handler->NeedsTrackletsBranchReplication()) && (fgAODTracklets))
{
fgAODTracklets = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetTracklets();
}
if ((handler->NeedsPMDClustersBranchReplication()) && (fgAODPMDClusters))
{
TClonesArray* PMDClusters = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetPmdClusters();
new (fgAODPMDClusters) TClonesArray(*PMDClusters);
}
if ((handler->NeedsJetsBranchReplication()) && (fgAODJets))
{
TClonesArray* Jets = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetJets();
new (fgAODJets) TClonesArray(*Jets);
}
if ((handler->NeedsFMDClustersBranchReplication()) && (fgAODFMDClusters))
{
TClonesArray* FMDClusters = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetFmdClusters();
new (fgAODFMDClusters) TClonesArray(*FMDClusters);
}
if ((handler->NeedsCaloClustersBranchReplication()) && (fgAODCaloClusters))
{
TClonesArray* CaloClusters = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetCaloClusters();
new (fgAODCaloClusters) TClonesArray(*CaloClusters);
}
//
handler->SetAODIsReplicated();
}
}
// Call the user analysis
UserExec(option);
PostData(0, fTreeA);
}
const char* AliAnalysisTaskSE::CurrentFileName()
{
// Returns the current file name
if( fInputHandler )
return fInputHandler->GetTree()->GetCurrentFile()->GetName();
else if( fMCEvent )
return ((AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()))->TreeK()->GetCurrentFile()->GetName();
else return "";
}
void AliAnalysisTaskSE::AddAODBranch(const char* cname, void* addobj)
{
// Add a new branch to the aod tree
AliAODHandler* handler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
if (handler) {
handler->AddBranch(cname, addobj);
}
}
<commit_msg>For branch replication copy the content of simple objects header and tracklets, not the pointers.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>
#include <TChain.h>
#include <TFile.h>
#include <TList.h>
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliAODEvent.h"
#include "AliAODHeader.h"
#include "AliAODTracklets.h"
#include "AliVEvent.h"
#include "AliAODHandler.h"
#include "AliAODInputHandler.h"
#include "AliMCEventHandler.h"
#include "AliInputEventHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
#include "AliLog.h"
ClassImp(AliAnalysisTaskSE)
////////////////////////////////////////////////////////////////////////
AliAODHeader* AliAnalysisTaskSE::fgAODHeader = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODTracks = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODVertices = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODV0s = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODPMDClusters = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODJets = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODFMDClusters = NULL;
TClonesArray* AliAnalysisTaskSE::fgAODCaloClusters = NULL;
AliAODTracklets* AliAnalysisTaskSE::fgAODTracklets = NULL;
AliAnalysisTaskSE::AliAnalysisTaskSE():
AliAnalysisTask(),
fDebug(0),
fEntry(0),
fInputEvent(0x0),
fInputHandler(0x0),
fOutputAOD(0x0),
fMCEvent(0x0),
fTreeA(0x0)
{
// Default constructor
}
AliAnalysisTaskSE::AliAnalysisTaskSE(const char* name):
AliAnalysisTask(name, "AnalysisTaskSE"),
fDebug(0),
fEntry(0),
fInputEvent(0x0),
fInputHandler(0x0),
fOutputAOD(0x0),
fMCEvent(0x0),
fTreeA(0x0)
{
// Default constructor
DefineInput (0, TChain::Class());
DefineOutput(0, TTree::Class());
}
AliAnalysisTaskSE::AliAnalysisTaskSE(const AliAnalysisTaskSE& obj):
AliAnalysisTask(obj),
fDebug(0),
fEntry(0),
fInputEvent(0x0),
fInputHandler(0x0),
fOutputAOD(0x0),
fMCEvent(0x0),
fTreeA(0x0)
{
// Copy constructor
fDebug = obj.fDebug;
fEntry = obj.fEntry;
fInputEvent = obj.fInputEvent;
fInputHandler = obj.fInputHandler;
fOutputAOD = obj.fOutputAOD;
fMCEvent = obj.fMCEvent;
fTreeA = obj.fTreeA;
printf("Constructor (3) \n");
}
AliAnalysisTaskSE& AliAnalysisTaskSE::operator=(const AliAnalysisTaskSE& other)
{
// Assignment
AliAnalysisTask::operator=(other);
fDebug = other.fDebug;
fEntry = other.fEntry;
fInputEvent = other.fInputEvent;
fInputHandler = other.fInputHandler;
fOutputAOD = other.fOutputAOD;
fMCEvent = other.fMCEvent;
fTreeA = other.fTreeA;
return *this;
}
void AliAnalysisTaskSE::ConnectInputData(Option_t* /*option*/)
{
// Connect the input data
if (fDebug > 1) printf("AnalysisTaskSE::ConnectInputData() \n");
//
// ESD
//
fInputHandler = (AliInputEventHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetInputEventHandler());
//
// Monte Carlo
//
AliMCEventHandler* mcH = 0;
mcH = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler());
if (mcH) fMCEvent = mcH->MCEvent();
if (fInputHandler) {
fInputEvent = fInputHandler->GetEvent();
} else if( fMCEvent ) {
AliWarning("No Input Event Handler connected, only MC Truth Event Handler") ;
} else {
AliError("No Input Event Handler connected") ;
return ;
}
}
void AliAnalysisTaskSE::CreateOutputObjects()
{
// Create the output container
//
// Default AOD
if (fDebug > 1) printf("AnalysisTaskSE::CreateOutPutData() \n");
AliAODHandler* handler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
// Check if AOD replication has been required
if (handler) {
fOutputAOD = handler->GetAOD();
fTreeA = handler->GetTree();
if (!(handler->IsStandard())) {
if ((handler->NeedsHeaderReplication()) && !(fgAODHeader))
{
if (fDebug > 1) AliInfo("Replicating header");
fgAODHeader = new AliAODHeader;
handler->AddBranch("AliAODHeader", &fgAODHeader);
}
if ((handler->NeedsTracksBranchReplication()) && !(fgAODTracks))
{
if (fDebug > 1) AliInfo("Replicating track branch\n");
fgAODTracks = new TClonesArray("AliAODTrack",500);
fgAODTracks->SetName("tracks");
handler->AddBranch("TClonesArray", &fgAODTracks);
}
if ((handler->NeedsVerticesBranchReplication()) && !(fgAODVertices))
{
if (fDebug > 1) AliInfo("Replicating vertices branch\n");
fgAODVertices = new TClonesArray("AliAODVertex",500);
fgAODVertices->SetName("vertices");
handler->AddBranch("TClonesArray", &fgAODVertices);
}
if ((handler->NeedsV0sBranchReplication()) && !(fgAODV0s))
{
if (fDebug > 1) AliInfo("Replicating V0s branch\n");
fgAODV0s = new TClonesArray("AliAODv0",500);
fgAODV0s->SetName("v0s");
handler->AddBranch("TClonesArray", &fgAODV0s);
}
if ((handler->NeedsTrackletsBranchReplication()) && !(fgAODTracklets))
{
if (fDebug > 1) AliInfo("Replicating Tracklets branch\n");
fgAODTracklets = new AliAODTracklets("tracklets","tracklets");
handler->AddBranch("AliAODTracklets", &fgAODTracklets);
}
if ((handler->NeedsPMDClustersBranchReplication()) && !(fgAODPMDClusters))
{
if (fDebug > 1) AliInfo("Replicating PMDClusters branch\n");
fgAODPMDClusters = new TClonesArray("AliAODPmdCluster",500);
fgAODPMDClusters->SetName("pmdClusters");
handler->AddBranch("TClonesArray", &fgAODPMDClusters);
}
if ((handler->NeedsJetsBranchReplication()) && !(fgAODJets))
{
if (fDebug > 1) AliInfo("Replicating Jets branch\n");
fgAODJets = new TClonesArray("AliAODJet",500);
fgAODJets->SetName("jets");
handler->AddBranch("TClonesArray", &fgAODJets);
}
if ((handler->NeedsFMDClustersBranchReplication()) && !(fgAODFMDClusters))
{
AliInfo("Replicating FMDClusters branch\n");
fgAODFMDClusters = new TClonesArray("AliAODFmdCluster",500);
fgAODFMDClusters->SetName("fmdClusters");
handler->AddBranch("TClonesArray", &fgAODFMDClusters);
}
if ((handler->NeedsCaloClustersBranchReplication()) && !(fgAODCaloClusters))
{
if (fDebug > 1) AliInfo("Replicating CaloClusters branch\n");
fgAODCaloClusters = new TClonesArray("AliAODCaloCluster",500);
fgAODCaloClusters->SetName("caloClusters");
handler->AddBranch("TClonesArray", &fgAODCaloClusters);
}
}
} else {
AliWarning("No AOD Event Handler connected.") ;
}
UserCreateOutputObjects();
}
void AliAnalysisTaskSE::Exec(Option_t* option)
{
//
// Exec analysis of one event
if (fDebug > 1) AliInfo("AliAnalysisTaskSE::Exec() \n");
if( fInputHandler )
fEntry = fInputHandler->GetReadEntry();
else if( fMCEvent )
fEntry = fMCEvent->Header()->GetEvent();
if ( !((Entry()-1)%100) && fDebug > 0)
AliInfo(Form("%s ----> Processing event # %lld", CurrentFileName(), Entry()));
AliAODHandler* handler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
AliAODInputHandler* aodH = dynamic_cast<AliAODInputHandler*>(fInputHandler);
if (handler && aodH) {
if (!(handler->IsStandard()) && !(handler->AODIsReplicated())) {
if ((handler->NeedsHeaderReplication()) && (fgAODHeader))
{
// copy the contents by assigment
*fgAODHeader = *(dynamic_cast<AliAODHeader*>(InputEvent()->GetHeader()));
}
if ((handler->NeedsTracksBranchReplication()) && (fgAODTracks))
{
TClonesArray* tracks = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetTracks();
new (fgAODTracks) TClonesArray(*tracks);
}
if ((handler->NeedsVerticesBranchReplication()) && (fgAODVertices))
{
TClonesArray* vertices = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetVertices();
new (fgAODVertices) TClonesArray(*vertices);
}
if ((handler->NeedsV0sBranchReplication()) && (fgAODV0s))
{
TClonesArray* V0s = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetV0s();
new (fgAODV0s) TClonesArray(*V0s);
}
if ((handler->NeedsTrackletsBranchReplication()) && (fgAODTracklets))
{
*fgAODTracklets = *(dynamic_cast<AliAODEvent*>(InputEvent()))->GetTracklets();
}
if ((handler->NeedsPMDClustersBranchReplication()) && (fgAODPMDClusters))
{
TClonesArray* PMDClusters = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetPmdClusters();
new (fgAODPMDClusters) TClonesArray(*PMDClusters);
}
if ((handler->NeedsJetsBranchReplication()) && (fgAODJets))
{
TClonesArray* Jets = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetJets();
new (fgAODJets) TClonesArray(*Jets);
}
if ((handler->NeedsFMDClustersBranchReplication()) && (fgAODFMDClusters))
{
TClonesArray* FMDClusters = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetFmdClusters();
new (fgAODFMDClusters) TClonesArray(*FMDClusters);
}
if ((handler->NeedsCaloClustersBranchReplication()) && (fgAODCaloClusters))
{
TClonesArray* CaloClusters = (dynamic_cast<AliAODEvent*>(InputEvent()))->GetCaloClusters();
new (fgAODCaloClusters) TClonesArray(*CaloClusters);
}
//
handler->SetAODIsReplicated();
}
}
// Call the user analysis
UserExec(option);
PostData(0, fTreeA);
}
const char* AliAnalysisTaskSE::CurrentFileName()
{
// Returns the current file name
if( fInputHandler )
return fInputHandler->GetTree()->GetCurrentFile()->GetName();
else if( fMCEvent )
return ((AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()))->TreeK()->GetCurrentFile()->GetName();
else return "";
}
void AliAnalysisTaskSE::AddAODBranch(const char* cname, void* addobj)
{
// Add a new branch to the aod tree
AliAODHandler* handler = (AliAODHandler*)
((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler());
if (handler) {
handler->AddBranch(cname, addobj);
}
}
<|endoftext|> |
<commit_before>// $Id$
// Category: geometry
//
// According to:
// Id: ExN02MagneticField.cc,v 1.1 1999/01/07 16:05:49 gunter Exp
// GEANT4 tag Name: geant4-00-01
#include "AliMagneticField.h"
#include <G4FieldManager.hh>
#include <G4TransportationManager.hh>
// Constructors
AliMagneticField::AliMagneticField()
: G4UniformMagField(G4ThreeVector())
{
//
GetGlobalFieldManager()->CreateChordFinder(this);
}
AliMagneticField::AliMagneticField(G4ThreeVector fieldVector)
: G4UniformMagField(fieldVector)
{
//
GetGlobalFieldManager()->CreateChordFinder(this);
}
AliMagneticField::AliMagneticField(const AliMagneticField& right)
: G4UniformMagField(right)
{
//
GetGlobalFieldManager()->CreateChordFinder(this);
}
AliMagneticField::~AliMagneticField() {
//
}
// operators
AliMagneticField&
AliMagneticField::operator=(const AliMagneticField& right)
{
// check assignement to self
if (this == &right) return *this;
// base class assignement
G4UniformMagField::operator=(right);
return *this;
}
// public methods
void AliMagneticField::SetFieldValue(G4double fieldValue)
{
// Sets the value of the Global Field to fieldValue along Z.
// ---
G4UniformMagField::SetFieldValue(G4ThreeVector(0,0,fieldValue));
}
void AliMagneticField::SetFieldValue(G4ThreeVector fieldVector)
{
// Sets the value of the Global Field.
// ---
// Find the Field Manager for the global field
G4FieldManager* fieldMgr= GetGlobalFieldManager();
if(fieldVector!=G4ThreeVector(0.,0.,0.)) {
G4UniformMagField::SetFieldValue(fieldVector);
fieldMgr->SetDetectorField(this);
}
else {
// If the new field's value is Zero, then it is best to
// insure that it is not used for propagation.
G4MagneticField* magField = NULL;
fieldMgr->SetDetectorField(magField);
}
}
G4FieldManager* AliMagneticField::GetGlobalFieldManager()
{
// Utility method/
// ---
return G4TransportationManager::GetTransportationManager()
->GetFieldManager();
}
<commit_msg>added SetDetectorField(this) to global field manager in constructors<commit_after>// $Id$
// Category: geometry
//
// According to:
// Id: ExN02MagneticField.cc,v 1.1 1999/01/07 16:05:49 gunter Exp
// GEANT4 tag Name: geant4-00-01
#include "AliMagneticField.h"
#include <G4FieldManager.hh>
#include <G4TransportationManager.hh>
// Constructors
AliMagneticField::AliMagneticField()
: G4UniformMagField(G4ThreeVector())
{
//
GetGlobalFieldManager()->SetDetectorField(this);
GetGlobalFieldManager()->CreateChordFinder(this);
}
AliMagneticField::AliMagneticField(G4ThreeVector fieldVector)
: G4UniformMagField(fieldVector)
{
//
GetGlobalFieldManager()->SetDetectorField(this);
GetGlobalFieldManager()->CreateChordFinder(this);
}
AliMagneticField::AliMagneticField(const AliMagneticField& right)
: G4UniformMagField(right)
{
//
GetGlobalFieldManager()->SetDetectorField(this);
GetGlobalFieldManager()->CreateChordFinder(this);
}
AliMagneticField::~AliMagneticField() {
//
}
// operators
AliMagneticField&
AliMagneticField::operator=(const AliMagneticField& right)
{
// check assignement to self
if (this == &right) return *this;
// base class assignement
G4UniformMagField::operator=(right);
return *this;
}
// public methods
void AliMagneticField::SetFieldValue(G4double fieldValue)
{
// Sets the value of the Global Field to fieldValue along Z.
// ---
G4UniformMagField::SetFieldValue(G4ThreeVector(0,0,fieldValue));
}
void AliMagneticField::SetFieldValue(G4ThreeVector fieldVector)
{
// Sets the value of the Global Field.
// ---
// Find the Field Manager for the global field
G4FieldManager* fieldMgr= GetGlobalFieldManager();
if(fieldVector!=G4ThreeVector(0.,0.,0.)) {
G4UniformMagField::SetFieldValue(fieldVector);
fieldMgr->SetDetectorField(this);
}
else {
// If the new field's value is Zero, then it is best to
// insure that it is not used for propagation.
G4MagneticField* magField = 0;
fieldMgr->SetDetectorField(magField);
}
}
G4FieldManager* AliMagneticField::GetGlobalFieldManager()
{
// Utility method/
// ---
return G4TransportationManager::GetTransportationManager()
->GetFieldManager();
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "FactorEncoder.hh"
#include "Unigrams.hh"
#include "io.hh"
using namespace std;
int
Unigrams::read_vocab(string fname,
map<string, flt_type> &vocab,
int &maxlen)
{
ifstream vocabfile(fname);
if (!vocabfile) return -1;
string line;
flt_type count;
maxlen = -1;
while (getline(vocabfile, line)) {
stringstream ss(line);
string word;
ss >> count;
ss >> word;
vocab[word] = count;
maxlen = max(maxlen, int(word.length()));
}
vocabfile.close();
return vocab.size();
}
int
Unigrams::write_vocab(string fname,
const map<string, flt_type> &vocab,
bool count_style,
int num_decimals)
{
ofstream vocabfile(fname);
if (!vocabfile) return -1;
vocabfile << setprecision(num_decimals);
vector<pair<string, flt_type> > sorted_vocab;
sort_vocab(vocab, sorted_vocab);
for (unsigned int i=0; i<sorted_vocab.size(); i++)
if (count_style)
vocabfile << sorted_vocab[i].first << "\t" << sorted_vocab[i].second << endl;
else
vocabfile << sorted_vocab[i].second << " " << sorted_vocab[i].first << endl;
vocabfile.close();
return vocab.size();
}
int
Unigrams::read_sents(string fname,
vector<string> &sents)
{
sents.clear();
io::Stream datafile(fname, "r");
char mystring[MAX_LINE_LEN];
int lc = 0;
while (fgets(mystring, MAX_LINE_LEN, datafile.file)) {
string cppstr(mystring);
trim(cppstr, '\n');
sents.push_back(cppstr);
lc++;
}
datafile.close();
return lc;
}
bool descending_sort(pair<string, flt_type> i,pair<string, flt_type> j) { return (i.second > j.second); }
bool ascending_sort(pair<string, flt_type> i,pair<string, flt_type> j) { return (i.second < j.second); }
void
Unigrams::sort_vocab(const map<string, flt_type> &vocab,
vector<pair<string, flt_type> > &sorted_vocab,
bool descending)
{
sorted_vocab.clear();
for (auto it = vocab.cbegin(); it != vocab.cend(); it++) {
pair<string, flt_type> curr_pair(it->first, it->second);
sorted_vocab.push_back(curr_pair);
}
if (descending)
sort(sorted_vocab.begin(), sorted_vocab.end(), descending_sort);
else
sort(sorted_vocab.begin(), sorted_vocab.end(), ascending_sort);
}
flt_type
Unigrams::iterate(const map<string, flt_type> &words,
map<string, flt_type> &vocab,
unsigned int iterations)
{
map<string, flt_type> freqs;
flt_type ll = 0.0;
for (unsigned int i=0; i<iterations; i++) {
ll = resegment_words(words, vocab, freqs);
vocab = freqs;
freqs_to_logprobs(vocab);
}
return ll;
}
flt_type
Unigrams::iterate(const vector<string> &sents,
map<string, flt_type> &vocab,
unsigned int iterations)
{
map<string, flt_type> freqs;
flt_type ll = 0.0;
for (unsigned int i=0; i<iterations; i++) {
ll = resegment_sents(sents, vocab, freqs);
vocab = freqs;
freqs_to_logprobs(vocab);
}
return ll;
}
flt_type
Unigrams::resegment_words(const map<string, flt_type> &words,
const map<string, flt_type> &vocab,
map<string, flt_type> &new_freqs)
{
StringSet stringset_vocab(vocab);
return resegment_words(words, stringset_vocab, new_freqs);
}
flt_type
Unigrams::resegment_words(const map<string, flt_type> &words,
const StringSet &vocab,
map<string, flt_type> &new_freqs)
{
new_freqs.clear();
flt_type ll = 0.0;
for (auto worditer = words.cbegin(); worditer != words.cend(); ++worditer) {
map<string, flt_type> stats;
ll += worditer->second * segf(vocab, worditer->first, stats);
if (stats.size() == 0) {
cerr << "warning, no segmentation for word: " << worditer->first << endl;
exit(0);
}
// Update statistics
for (auto it = stats.begin(); it != stats.end(); ++it)
new_freqs[it->first] += worditer->second * it->second;
}
return ll;
}
flt_type
Unigrams::resegment_sents(const vector<string> &sents,
const map<string, flt_type> &vocab,
map<string, flt_type> &new_freqs)
{
StringSet stringset_vocab(vocab);
return resegment_sents(sents, stringset_vocab, new_freqs);
}
flt_type
Unigrams::resegment_sents(const vector<string> &sents,
const StringSet &vocab,
map<string, flt_type> &new_freqs)
{
new_freqs.clear();
flt_type ll = 0.0;
for (auto sent = sents.begin(); sent != sents.end(); ++sent) {
map<string, flt_type> stats;
ll += segf(vocab, *sent, stats);
if (stats.size() == 0) {
cerr << "warning, no segmentation for sentence: " << *sent << endl;
exit(0);
}
// Update statistics
for (auto it = stats.begin(); it != stats.end(); ++it)
new_freqs[it->first] += it->second;
}
return ll;
}
flt_type
Unigrams::get_sum(const map<string, flt_type> &freqs)
{
flt_type total = 0.0;
for (auto iter = freqs.cbegin(); iter != freqs.cend(); ++iter)
total += iter->second;
return total;
}
flt_type
Unigrams::get_cost(const map<string, flt_type> &freqs,
flt_type densum)
{
flt_type total = 0.0;
flt_type tmp = 0.0;
densum = log(densum);
for (auto iter = freqs.cbegin(); iter != freqs.cend(); ++iter) {
tmp = iter->second * (log(iter->second)-densum);
if (!std::isnan(tmp)) total += tmp;
}
return total;
}
void
Unigrams::freqs_to_logprobs(map<string, flt_type> &vocab)
{
flt_type densum = Unigrams::get_sum(vocab);
densum = log(densum);
for (auto iter = vocab.begin(); iter != vocab.end(); ++iter)
iter->second = (log(iter->second)-densum);
}
int
Unigrams::cutoff(map<string, flt_type> &vocab,
flt_type limit)
{
// http://stackoverflow.com/questions/8234779/how-to-remove-from-a-map-while-iterating-it
int nremovals = 0;
auto iter = vocab.begin();
while (iter != vocab.end()) {
if (iter->second <= limit && iter->first.length() > 1) {
vocab.erase(iter++);
nremovals++;
}
else ++iter;
}
return nremovals;
}
// Select n_candidates number of subwords in the vocabulary as removal candidates
// running from the least common subword
int
Unigrams::init_candidates(int n_candidates,
const map<string, flt_type> &vocab,
set<string> &candidates)
{
vector<pair<string, flt_type> > sorted_vocab;
sort_vocab(vocab, sorted_vocab, false);
int selected_candidates = 0;
for (auto it = sorted_vocab.cbegin(); it != sorted_vocab.cend(); ++it) {
const string &subword = it->first;
if (subword.length() < 2) continue;
candidates.insert(subword);
selected_candidates++;
if (selected_candidates >= n_candidates) break;
}
return selected_candidates;
}
bool rank_desc_sort(pair<string, flt_type> i,pair<string, flt_type> j) { return (i.second > j.second); }
// Perform each of the removals (independent of others in the list) to get
// initial order for the removals
flt_type
Unigrams::rank_candidates(const map<string, flt_type> &words,
const map<string, flt_type> &vocab,
const set<string> &candidates,
map<string, flt_type> &new_freqs,
vector<pair<string, flt_type> > &removal_scores)
{
new_freqs.clear();
removal_scores.clear();
StringSet ss_vocab(vocab);
map<string, flt_type> diffs;
flt_type curr_ll = 0.0;
for (auto worditer = words.cbegin(); worditer != words.cend(); ++worditer) {
map<string, flt_type> stats;
flt_type orig_score = segf(ss_vocab, worditer->first, stats);
curr_ll += worditer->second * orig_score;
if (stats.size() == 0) {
cerr << "warning, no segmentation for word: " << worditer->first << endl;
exit(0);
}
// Update statistics
for (auto it = stats.cbegin(); it != stats.cend(); ++it)
new_freqs[it->first] += worditer->second * it->second;
// Hypothesize what the segmentation would be if some subword didn't exist
for (auto hypoiter = stats.cbegin(); hypoiter != stats.cend(); ++hypoiter) {
// If wanting to hypothesize removal of this subword
if (candidates.find(hypoiter->first) != candidates.end()) {
flt_type stored_value = ss_vocab.remove(hypoiter->first);
map<string, flt_type> hypo_stats;
flt_type hypo_score = segf(ss_vocab, worditer->first, hypo_stats);
if (hypo_stats.size() == 0) {
cerr << "warning, no hypo segmentation for word: " << worditer->first << endl;
exit(0);
}
diffs[hypoiter->first] += worditer->second * (hypo_score-orig_score);
ss_vocab.add(hypoiter->first, stored_value);
}
}
}
for (auto iter = diffs.begin(); iter != diffs.end(); ++iter) {
pair<string, flt_type> removal_score = make_pair(iter->first, iter->second);
removal_scores.push_back(removal_score);
}
sort(removal_scores.begin(), removal_scores.end(), rank_desc_sort);
return curr_ll;
}
// Perform each of the removals (independent of others in the list) to get
// initial order for the removals
flt_type
Unigrams::rank_candidates(std::vector<std::string> &sents,
const map<string, flt_type> &vocab,
const set<string> &candidates,
map<string, flt_type> &new_freqs,
vector<pair<string, flt_type> > &removal_scores)
{
new_freqs.clear();
removal_scores.clear();
StringSet ss_vocab(vocab);
map<string, flt_type> diffs;
flt_type curr_ll = 0.0;
for (auto sentiter = sents.cbegin(); sentiter != sents.cend(); ++sentiter) {
map<string, flt_type> stats;
flt_type orig_score = segf(ss_vocab, *sentiter, stats);
curr_ll += orig_score;
if (stats.size() == 0) {
cerr << "warning, no segmentation for sentence: " << *sentiter << endl;
exit(0);
}
// Update statistics
for (auto it = stats.cbegin(); it != stats.cend(); ++it)
new_freqs[it->first] += it->second;
// Hypothesize what the segmentation would be if some subword didn't exist
for (auto hypoiter = stats.cbegin(); hypoiter != stats.cend(); ++hypoiter) {
// If wanting to hypothesize removal of this subword
if (candidates.find(hypoiter->first) != candidates.end()) {
flt_type stored_value = ss_vocab.remove(hypoiter->first);
map<string, flt_type> hypo_stats;
flt_type hypo_score = segf(ss_vocab, *sentiter, hypo_stats);
if (hypo_stats.size() == 0) {
cerr << "warning, no hypo segmentation for sentence: " << *sentiter << endl;
exit(0);
}
diffs[hypoiter->first] += (hypo_score-orig_score);
ss_vocab.add(hypoiter->first, stored_value);
}
}
}
for (auto iter = diffs.begin(); iter != diffs.end(); ++iter) {
pair<string, flt_type> removal_score = make_pair(iter->first, iter->second);
removal_scores.push_back(removal_score);
}
sort(removal_scores.begin(), removal_scores.end(), rank_desc_sort);
return curr_ll;
}
<commit_msg>Take renormalization also into account in computing ll diff.<commit_after>#include <algorithm>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "FactorEncoder.hh"
#include "Unigrams.hh"
#include "io.hh"
using namespace std;
int
Unigrams::read_vocab(string fname,
map<string, flt_type> &vocab,
int &maxlen)
{
ifstream vocabfile(fname);
if (!vocabfile) return -1;
string line;
flt_type count;
maxlen = -1;
while (getline(vocabfile, line)) {
stringstream ss(line);
string word;
ss >> count;
ss >> word;
vocab[word] = count;
maxlen = max(maxlen, int(word.length()));
}
vocabfile.close();
return vocab.size();
}
int
Unigrams::write_vocab(string fname,
const map<string, flt_type> &vocab,
bool count_style,
int num_decimals)
{
ofstream vocabfile(fname);
if (!vocabfile) return -1;
vocabfile << setprecision(num_decimals);
vector<pair<string, flt_type> > sorted_vocab;
sort_vocab(vocab, sorted_vocab);
for (unsigned int i=0; i<sorted_vocab.size(); i++)
if (count_style)
vocabfile << sorted_vocab[i].first << "\t" << sorted_vocab[i].second << endl;
else
vocabfile << sorted_vocab[i].second << " " << sorted_vocab[i].first << endl;
vocabfile.close();
return vocab.size();
}
int
Unigrams::read_sents(string fname,
vector<string> &sents)
{
sents.clear();
io::Stream datafile(fname, "r");
char mystring[MAX_LINE_LEN];
int lc = 0;
while (fgets(mystring, MAX_LINE_LEN, datafile.file)) {
string cppstr(mystring);
trim(cppstr, '\n');
sents.push_back(cppstr);
lc++;
}
datafile.close();
return lc;
}
bool descending_sort(pair<string, flt_type> i,pair<string, flt_type> j) { return (i.second > j.second); }
bool ascending_sort(pair<string, flt_type> i,pair<string, flt_type> j) { return (i.second < j.second); }
void
Unigrams::sort_vocab(const map<string, flt_type> &vocab,
vector<pair<string, flt_type> > &sorted_vocab,
bool descending)
{
sorted_vocab.clear();
for (auto it = vocab.cbegin(); it != vocab.cend(); it++) {
pair<string, flt_type> curr_pair(it->first, it->second);
sorted_vocab.push_back(curr_pair);
}
if (descending)
sort(sorted_vocab.begin(), sorted_vocab.end(), descending_sort);
else
sort(sorted_vocab.begin(), sorted_vocab.end(), ascending_sort);
}
flt_type
Unigrams::iterate(const map<string, flt_type> &words,
map<string, flt_type> &vocab,
unsigned int iterations)
{
map<string, flt_type> freqs;
flt_type ll = 0.0;
for (unsigned int i=0; i<iterations; i++) {
ll = resegment_words(words, vocab, freqs);
vocab = freqs;
freqs_to_logprobs(vocab);
}
return ll;
}
flt_type
Unigrams::iterate(const vector<string> &sents,
map<string, flt_type> &vocab,
unsigned int iterations)
{
map<string, flt_type> freqs;
flt_type ll = 0.0;
for (unsigned int i=0; i<iterations; i++) {
ll = resegment_sents(sents, vocab, freqs);
vocab = freqs;
freqs_to_logprobs(vocab);
}
return ll;
}
flt_type
Unigrams::resegment_words(const map<string, flt_type> &words,
const map<string, flt_type> &vocab,
map<string, flt_type> &new_freqs)
{
StringSet stringset_vocab(vocab);
return resegment_words(words, stringset_vocab, new_freqs);
}
flt_type
Unigrams::resegment_words(const map<string, flt_type> &words,
const StringSet &vocab,
map<string, flt_type> &new_freqs)
{
new_freqs.clear();
flt_type ll = 0.0;
for (auto worditer = words.cbegin(); worditer != words.cend(); ++worditer) {
map<string, flt_type> stats;
ll += worditer->second * segf(vocab, worditer->first, stats);
if (stats.size() == 0) {
cerr << "warning, no segmentation for word: " << worditer->first << endl;
exit(0);
}
// Update statistics
for (auto it = stats.begin(); it != stats.end(); ++it)
new_freqs[it->first] += worditer->second * it->second;
}
return ll;
}
flt_type
Unigrams::resegment_sents(const vector<string> &sents,
const map<string, flt_type> &vocab,
map<string, flt_type> &new_freqs)
{
StringSet stringset_vocab(vocab);
return resegment_sents(sents, stringset_vocab, new_freqs);
}
flt_type
Unigrams::resegment_sents(const vector<string> &sents,
const StringSet &vocab,
map<string, flt_type> &new_freqs)
{
new_freqs.clear();
flt_type ll = 0.0;
for (auto sent = sents.begin(); sent != sents.end(); ++sent) {
map<string, flt_type> stats;
ll += segf(vocab, *sent, stats);
if (stats.size() == 0) {
cerr << "warning, no segmentation for sentence: " << *sent << endl;
exit(0);
}
// Update statistics
for (auto it = stats.begin(); it != stats.end(); ++it)
new_freqs[it->first] += it->second;
}
return ll;
}
flt_type
Unigrams::get_sum(const map<string, flt_type> &freqs)
{
flt_type total = 0.0;
for (auto iter = freqs.cbegin(); iter != freqs.cend(); ++iter)
total += iter->second;
return total;
}
flt_type
Unigrams::get_cost(const map<string, flt_type> &freqs,
flt_type densum)
{
flt_type total = 0.0;
flt_type tmp = 0.0;
densum = log(densum);
for (auto iter = freqs.cbegin(); iter != freqs.cend(); ++iter) {
tmp = iter->second * (log(iter->second)-densum);
if (!std::isnan(tmp)) total += tmp;
}
return total;
}
void
Unigrams::freqs_to_logprobs(map<string, flt_type> &vocab)
{
flt_type densum = Unigrams::get_sum(vocab);
densum = log(densum);
for (auto iter = vocab.begin(); iter != vocab.end(); ++iter)
iter->second = (log(iter->second)-densum);
}
int
Unigrams::cutoff(map<string, flt_type> &vocab,
flt_type limit)
{
// http://stackoverflow.com/questions/8234779/how-to-remove-from-a-map-while-iterating-it
int nremovals = 0;
auto iter = vocab.begin();
while (iter != vocab.end()) {
if (iter->second <= limit && iter->first.length() > 1) {
vocab.erase(iter++);
nremovals++;
}
else ++iter;
}
return nremovals;
}
// Select n_candidates number of subwords in the vocabulary as removal candidates
// running from the least common subword
int
Unigrams::init_candidates(int n_candidates,
const map<string, flt_type> &vocab,
set<string> &candidates)
{
vector<pair<string, flt_type> > sorted_vocab;
sort_vocab(vocab, sorted_vocab, false);
int selected_candidates = 0;
for (auto it = sorted_vocab.cbegin(); it != sorted_vocab.cend(); ++it) {
const string &subword = it->first;
if (subword.length() < 2) continue;
candidates.insert(subword);
selected_candidates++;
if (selected_candidates >= n_candidates) break;
}
return selected_candidates;
}
bool rank_desc_sort(pair<string, flt_type> i,pair<string, flt_type> j) { return (i.second > j.second); }
// Perform each of the removals (independent of others in the list) to get
// initial order for the removals
flt_type
Unigrams::rank_candidates(const map<string, flt_type> &words,
const map<string, flt_type> &vocab,
const set<string> &candidates,
map<string, flt_type> &new_freqs,
vector<pair<string, flt_type> > &removal_scores)
{
new_freqs.clear();
removal_scores.clear();
StringSet ss_vocab(vocab);
map<string, flt_type> ll_diffs;
map<string, flt_type> token_diffs;
flt_type curr_ll = 0.0;
flt_type token_count = 0.0;
for (auto worditer = words.cbegin(); worditer != words.cend(); ++worditer) {
map<string, flt_type> stats;
flt_type orig_score = segf(ss_vocab, worditer->first, stats);
curr_ll += worditer->second * orig_score;
token_count += worditer->second * stats.size();
if (stats.size() == 0) {
cerr << "warning, no segmentation for word: " << worditer->first << endl;
exit(0);
}
// Update statistics
for (auto it = stats.cbegin(); it != stats.cend(); ++it)
new_freqs[it->first] += worditer->second * it->second;
// Hypothesize what the segmentation would be if some subword didn't exist
for (auto hypoiter = stats.cbegin(); hypoiter != stats.cend(); ++hypoiter) {
// If wanting to hypothesize removal of this subword
if (candidates.find(hypoiter->first) != candidates.end()) {
flt_type stored_value = ss_vocab.remove(hypoiter->first);
map<string, flt_type> hypo_stats;
flt_type hypo_score = segf(ss_vocab, worditer->first, hypo_stats);
if (hypo_stats.size() == 0) {
cerr << "warning, no hypo segmentation for word: " << worditer->first << endl;
exit(0);
}
ll_diffs[hypoiter->first] += worditer->second * (hypo_score-orig_score);
token_diffs[hypoiter->first] += worditer->second * ((flt_type)(hypo_stats.size())-(flt_type)(stats.size()));
ss_vocab.add(hypoiter->first, stored_value);
}
}
}
for (auto iter = ll_diffs.begin(); iter != ll_diffs.end(); ++iter) {
flt_type renormalizer = sub_log_domain_probs(0, vocab.at(iter->first));
flt_type hypo_token_count = (token_count + token_diffs[iter->first]);
flt_type normalizer_ll_diff = hypo_token_count * -renormalizer;
pair<string, flt_type> removal_score = make_pair(iter->first, iter->second + normalizer_ll_diff);
removal_scores.push_back(removal_score);
}
sort(removal_scores.begin(), removal_scores.end(), rank_desc_sort);
return curr_ll;
}
// Perform each of the removals (independent of others in the list) to get
// initial order for the removals
flt_type
Unigrams::rank_candidates(std::vector<std::string> &sents,
const map<string, flt_type> &vocab,
const set<string> &candidates,
map<string, flt_type> &new_freqs,
vector<pair<string, flt_type> > &removal_scores)
{
new_freqs.clear();
removal_scores.clear();
StringSet ss_vocab(vocab);
map<string, flt_type> ll_diffs;
map<string, flt_type> token_diffs;
flt_type curr_ll = 0.0;
flt_type token_count = 0.0;
for (auto sentiter = sents.cbegin(); sentiter != sents.cend(); ++sentiter) {
map<string, flt_type> stats;
flt_type orig_score = segf(ss_vocab, *sentiter, stats);
curr_ll += orig_score;
token_count += stats.size();
if (stats.size() == 0) {
cerr << "warning, no segmentation for sentence: " << *sentiter << endl;
exit(0);
}
// Update statistics
for (auto it = stats.cbegin(); it != stats.cend(); ++it)
new_freqs[it->first] += it->second;
// Hypothesize what the segmentation would be if some subword didn't exist
for (auto hypoiter = stats.cbegin(); hypoiter != stats.cend(); ++hypoiter) {
// If wanting to hypothesize removal of this subword
if (candidates.find(hypoiter->first) != candidates.end()) {
flt_type stored_value = ss_vocab.remove(hypoiter->first);
map<string, flt_type> hypo_stats;
flt_type hypo_score = segf(ss_vocab, *sentiter, hypo_stats);
if (hypo_stats.size() == 0) {
cerr << "warning, no hypo segmentation for sentence: " << *sentiter << endl;
exit(0);
}
ll_diffs[hypoiter->first] += (hypo_score-orig_score);
token_diffs[hypoiter->first] += (flt_type)(hypo_stats.size())-(flt_type)(stats.size());
ss_vocab.add(hypoiter->first, stored_value);
}
}
}
for (auto iter = ll_diffs.begin(); iter != ll_diffs.end(); ++iter) {
flt_type renormalizer = sub_log_domain_probs(0, vocab.at(iter->first));
flt_type hypo_token_count = (token_count + token_diffs[iter->first]);
flt_type normalizer_ll_diff = hypo_token_count * -renormalizer;
pair<string, flt_type> removal_score = make_pair(iter->first, iter->second);
removal_scores.push_back(removal_score);
}
sort(removal_scores.begin(), removal_scores.end(), rank_desc_sort);
return curr_ll;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <unordered_map>
#define min(x,y) x < y ? x : y
using namespace std;
typedef unsigned long long ullong;
//method used to compute all bit masks that are to be used in computation.
//Returns a single array that contains all M sets that will need to be processed in
//optimal threshold computation. Sets are sorted ascendingly by the number of missmatch.
//Each element (bit) missing from the set is a missmatch.
ullong* computeBitmaskArray(int* binomCoefCount, int k, int s) {
ullong* result = NULL;
ullong resultMask = (1LL << s) - 1;
int total = 0;
for(int i = 0; i < k; i++) {
total += binomCoefCount[i];
}
result = (ullong*) malloc(sizeof(ullong) * total);
ullong bot32Mask = (1LL << 32) - 1;
//in this loop we compute all masks. First we compute all sets
//that have 0 missmatch, then 1 missmatch... and so on, up to k
int c = 0;
for(int i = 0; i < k; i++) {
ullong current = (1LL << i) - 1;
//current = current | (current - 1);
for(int j = 0; j < binomCoefCount[i]; j++) {
//we shift the result by one because sets contain elements [1,s-1], therefore
//we need to shift resut by one to the left in order to have 0-th element not set.
result[c++] = ((~current) << 1) & resultMask;
ullong tmp = current | (current - 1);
int shift = 0;
uint input = (uint) current;
if ((bot32Mask & current) == 0) {
input = (uint) (current >> 32);
shift = 32;
}
shift += __builtin_ctz(input) + 1;
current = (tmp + 1) | (((~tmp & -~tmp) - 1)) >> shift;
}
}
return result;
}
//method used to calculate all (s-1) choose k values needed for the
//computation.
int* calculateBinomCoef(int k, int s) {
int* result = (int*) malloc(sizeof(int) * k);
result[0] = 1;
result[1] = s-1;
int top = s-1;
int bottom = 1;
for(int i = 2; i < k; i++) {
top *= s - i;
bottom *= i;
result[i] = top / bottom;
}
return result;
}
//method used to allocate 2D arrays for data storage.
//total memory usage is O(f(m,k)) as defined in the paper.
int** mallocIntArrays(int* rowSize, int k){
int** result = (int**) malloc(sizeof(int*) * k);
for(int i = 0; i < k; i++) {
result[i] = (int*) malloc(sizeof(int) * rowSize[i]);
}
return result;
}
//free...
void freeIntArrays(int**data, int k) {
for(int i = 0; i < k; i++) {
free(data[i]);
}
}
//fill all elements of 2D array with given value
//@param data 2D array to fill
void fill(int** data, int* rowSize, int k, int value) {
for(int i = 0; i < k; i++) {
for(int j = 0; j < rowSize[i]; j++) {
data[i][j] = value;
}
}
}
void printArray(int* data, int size) {
for(int i = 0; i < size; i++) {
printf("%d, ", data[i]);
}
printf("size: %d\n", size);
}
void print2D(int** data, int* rowSize, int k) {
for(int i = 0; i < k; i++) {
printArray(data[i], rowSize[i]);
}
}
int findThreshold(int* shape, int size, int m, int k) {
if (m > 64 || size > m || k > size) {
fprintf(stderr,"Invalid input arguments. shape size: %d, m: %d, k: %d\n", size, m, k);
exit(-1);
}
//to include k
k++;
int maxInt = 2147483647;
//mask used check whether some other set M is a subset of shape.
ullong shape_mask = 0;
int min = shape[0];
int max = 0;
for(int i = 0; i < size; i++) {
shape_mask |= (1LL << shape[i]);
if (shape[i] > max) {
max = shape[i];
} else {
if(shape[i] < min) {
min = shape[i];
}
}
}
int span = max - min + 1;
ullong lastElemMask = 1LL << (span - 1);
int* binCoef = calculateBinomCoef(k, span);
int binCoefPrefSum[k];
binCoefPrefSum[0] = binCoef[0];
for(int i = 1; i < k; i++) {
binCoefPrefSum[i] = binCoef[i] + binCoefPrefSum[i-1];
}
int arraySize = binCoefPrefSum[k-1];
ullong* bitMaskArray = computeBitmaskArray(binCoef, k, span);
unordered_map<ullong, int> maskToIndex;
for(int i = 0; i < arraySize; i++) {
maskToIndex[bitMaskArray[i]] = i;
}
int **currentResult, **nextResult;
currentResult = mallocIntArrays(binCoefPrefSum, k);
nextResult = mallocIntArrays(binCoefPrefSum, k);
fill(currentResult, binCoefPrefSum, k, 0);
ullong lastElemMaskNot = ~lastElemMask;
//printf("data in map\n");
// for(auto it = maskToIndex.begin(); it != maskToIndex.end(); it++) {
// printf("%lld -> %d\n", it->first, it->second);
// }
for(int i = span; i <= m; i++) {
for(int j = 0; j < k; j++) {
int end = binCoefPrefSum[j];
for(int l = 0; l < end; l++) {
ullong mask = bitMaskArray[l];
int targetJ = j;
if ((mask & lastElemMask) == 0) {
targetJ--;
}
if(targetJ == -1) {
//TODO can be removed this will never happen
continue;
}
ullong targetMask = (mask & lastElemMaskNot) << 1;
ullong targetMask2 = targetMask | 2LL;
int maskInd = maskToIndex[targetMask];
int maskInd2 = maskToIndex[targetMask2];
int hit = ((shape_mask & (mask | 1LL)) != 0 && (mask | 1LL) >= shape_mask) ? 1 : 0;
int nextVal = maxInt;
if(targetMask != 0 && maskInd < binCoefPrefSum[targetJ]){
nextVal = currentResult[targetJ][maskInd];
}
if(targetMask2 != 0 && maskInd2 < binCoefPrefSum[targetJ]) {
int val = currentResult[targetJ][maskInd2];
if(val < nextVal)
nextVal = val;
}
if(nextVal != maxInt){
//printf("update with hit %d\n", hit);
nextResult[j][l] = nextVal + hit;
} else {
//TODO just for debugging. This case should never be triggered
printf("ERROR\n");
exit(-1);
}
}
}
int** tmp = currentResult;
currentResult = nextResult;
nextResult = tmp;
}
int result = currentResult[k-1][0];
for(int i = 1; i < arraySize; i++) {
if(currentResult[k-1][i] < result) {
result = currentResult[k-1][i];
}
}
freeIntArrays(currentResult, k);
freeIntArrays(nextResult, k);
free(bitMaskArray);
free(binCoef);
return result;
}
int main() {
// int shape[12] = {0,2,4,8,14,16,18,22,28,30,32,36};
//
// printf("result: %d\n", findThreshold(shape, 12, 50, 5));
int shape[3] = {0,1,2};
printf("result: %d\n", findThreshold(shape, 3, 8, 1));
return 0;
}
<commit_msg>partialy finished recurrence...<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <unordered_map>
#define min(x,y) x < y ? x : y
using namespace std;
typedef unsigned long long ullong;
//method used to compute all bit masks that are to be used in computation.
//Returns a single array that contains all M sets that will need to be processed in
//optimal threshold computation. Sets are sorted ascendingly by the number of missmatch.
//Each element (bit) missing from the set is a missmatch.
ullong* computeBitmaskArray(int* binomCoefCount, int k, int s) {
ullong* result = NULL;
ullong resultMask = (1LL << s) - 1;
int total = 0;
for(int i = 0; i < k; i++) {
total += binomCoefCount[i];
}
result = (ullong*) malloc(sizeof(ullong) * total);
ullong bot32Mask = (1LL << 32) - 1;
//in this loop we compute all masks. First we compute all sets
//that have 0 missmatch, then 1 missmatch... and so on, up to k
int c = 0;
for(int i = 0; i < k; i++) {
ullong current = (1LL << i) - 1;
//current = current | (current - 1);
for(int j = 0; j < binomCoefCount[i]; j++) {
//we shift the result by one because sets contain elements [1,s-1], therefore
//we need to shift resut by one to the left in order to have 0-th element not set.
result[c++] = ((~current) << 1) & resultMask;
ullong tmp = current | (current - 1);
int shift = 0;
uint input = (uint) current;
if ((bot32Mask & current) == 0) {
input = (uint) (current >> 32);
shift = 32;
}
shift += __builtin_ctz(input) + 1;
current = (tmp + 1) | (((~tmp & -~tmp) - 1)) >> shift;
}
}
return result;
}
//method used to calculate all (s-1) choose k values needed for the
//computation.
int* calculateBinomCoef(int k, int s) {
int* result = (int*) malloc(sizeof(int) * k);
result[0] = 1;
result[1] = s-1;
int top = s-1;
int bottom = 1;
for(int i = 2; i < k; i++) {
top *= s - i;
bottom *= i;
result[i] = top / bottom;
}
return result;
}
//method used to allocate 2D arrays for data storage.
//total memory usage is O(f(m,k)) as defined in the paper.
int** mallocIntArrays(int* rowSize, int k){
int** result = (int**) malloc(sizeof(int*) * k);
for(int i = 0; i < k; i++) {
result[i] = (int*) malloc(sizeof(int) * rowSize[i]);
}
return result;
}
//free...
void freeIntArrays(int**data, int k) {
for(int i = 0; i < k; i++) {
free(data[i]);
}
}
//fill all elements of 2D array with given value
//@param data 2D array to fill
void fill(int** data, int* rowSize, int k, int value) {
for(int i = 0; i < k; i++) {
for(int j = 0; j < rowSize[i]; j++) {
data[i][j] = value;
}
}
}
void printArray(int* data, int size) {
for(int i = 0; i < size; i++) {
printf("%d, ", data[i]);
}
printf("size: %d\n", size);
}
void print2D(int** data, int* rowSize, int k) {
for(int i = 0; i < k; i++) {
printArray(data[i], rowSize[i]);
}
}
int findThreshold(int* shape, int size, int m, int k) {
if (m > 64 || size > m || k > size) {
fprintf(stderr,"Invalid input arguments. shape size: %d, m: %d, k: %d\n", size, m, k);
exit(-1);
}
//to include k
k++;
int maxInt = 2147483647;
//mask used check whether some other set M is a subset of shape.
ullong shape_mask = 0;
int min = shape[0];
int max = 0;
for(int i = 0; i < size; i++) {
shape_mask |= (1LL << shape[i]);
if (shape[i] > max) {
max = shape[i];
} else {
if(shape[i] < min) {
min = shape[i];
}
}
}
int span = max - min + 1;
ullong lastElemMask = 1LL << (span - 1);
int* binCoef = calculateBinomCoef(k, span);
int binCoefPrefSum[k];
binCoefPrefSum[0] = binCoef[0];
for(int i = 1; i < k; i++) {
binCoefPrefSum[i] = binCoef[i] + binCoefPrefSum[i-1];
}
int arraySize = binCoefPrefSum[k-1];
ullong* bitMaskArray = computeBitmaskArray(binCoef, k, span);
unordered_map<ullong, int> maskToIndex;
for(int i = 0; i < arraySize; i++) {
maskToIndex[bitMaskArray[i]] = i;
}
int **currentResult, **nextResult;
currentResult = mallocIntArrays(binCoefPrefSum, k);
nextResult = mallocIntArrays(binCoefPrefSum, k);
fill(currentResult, binCoefPrefSum, k, 0);
ullong lastElemMaskNot = ~lastElemMask;
for(int i = span; i <= m; i++) {
//here we go through all values j and M to compute next iteration
for(int j = 0; j < k; j++) {
//end is the index of last set that has at most j missmatches (all the sets that have at most j bits set to zero)
int end = binCoefPrefSum[j];
for(int l = 0; l < end; l++) {
ullong mask = bitMaskArray[l];
int targetJ = j;
if ((mask & lastElemMask) == 0) {
targetJ--;
}
if(targetJ == -1) {
//TODO can be removed this will never happen
continue;
}
//mask in bottom line in paper recurrence
ullong targetMask = (mask & lastElemMaskNot) << 1;
//mask in top line in paper recurrence
ullong targetMask2 = targetMask | 2LL;
int maskInd = maskToIndex[targetMask];
int maskInd2 = maskToIndex[targetMask2];
int hit = ((shape_mask & (mask | 1LL)) != 0 && (mask | 1LL) >= shape_mask) ? 1 : 0;
int nextVal = maxInt;
//if target mask has more then targetJ missmatches it is invalid
if(targetMask != 0 && maskInd < binCoefPrefSum[targetJ]){
nextVal = currentResult[targetJ][maskInd];
}
if(targetMask2 != 0 && maskInd2 < binCoefPrefSum[targetJ]) {
int val = currentResult[targetJ][maskInd2];
if(val < nextVal)
nextVal = val;
}
if(nextVal != maxInt){
//printf("update with hit %d\n", hit);
nextResult[j][l] = nextVal + hit;
} else {
//TODO just for debugging. This case should never be triggered
printf("ERROR\n");
exit(-1);
}
}
}
int** tmp = currentResult;
currentResult = nextResult;
nextResult = tmp;
}
int result = currentResult[k-1][0];
for(int i = 1; i < arraySize; i++) {
if(currentResult[k-1][i] < result) {
result = currentResult[k-1][i];
}
}
freeIntArrays(currentResult, k);
freeIntArrays(nextResult, k);
free(bitMaskArray);
free(binCoef);
return result;
}
int main() {
// int shape[12] = {0,2,4,8,14,16,18,22,28,30,32,36};
//
// printf("result: %d\n", findThreshold(shape, 12, 50, 5));
int shape[3] = {0,1,2};
printf("result: %d\n", findThreshold(shape, 3, 8, 1));
return 0;
}
<|endoftext|> |
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library 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 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <limits>
#include <iostream>
#include <fstream>
#include "dictionary.h"
#include "n_gram.h"
#include "lmtable.h"
#include "lmmacro.h"
#include "LanguageModelIRST.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
LanguageModelIRST::LanguageModelIRST(bool registerScore, ScoreIndexManager &scoreIndexManager, int dub)
:LanguageModelSingleFactor(registerScore, scoreIndexManager)
,m_lmtb(0),m_lmtb_dub(dub)
{
}
LanguageModelIRST::~LanguageModelIRST()
{
delete m_lmtb;
delete m_lmtb_ng;
}
bool LanguageModelIRST::Load(const std::string &filePath,
FactorType factorType,
float weight,
size_t nGramOrder)
{
char *SepString = " \t\n";
cerr << "In LanguageModelIRST::Load: nGramOrder = " << nGramOrder << "\n";
FactorCollection &factorCollection = FactorCollection::Instance();
m_factorType = factorType;
m_weight = weight;
m_nGramOrder = nGramOrder;
// get name of LM file and, if any, of the micro-macro map file
char *filenames = strdup(filePath.c_str());
m_filePath = strsep(&filenames, SepString);
// Open the input file (possibly gzipped)
InputFileStream inp(m_filePath);
if (filenames) {
// case LMfile + MAPfile: create an object of lmmacro class and load both LM file and map
cerr << "Loading LM file + MAP\n";
m_mapFilePath = strsep(&filenames, SepString);
if (!FileExists(m_mapFilePath)) {
cerr << "ERROR: Map file <" << m_mapFilePath << "> does not exist\n";
return false;
}
InputFileStream inpMap(m_mapFilePath);
m_lmtb = new lmmacro(m_filePath, inp, inpMap);
} else {
// case (standard) LMfile only: create an object of lmtable
cerr << "Loading LM file (no MAP)\n";
m_lmtb = (lmtable *)new lmtable;
// Load the (possibly binary) model
#ifdef WIN32
m_lmtb->load(inp); //don't use memory map
#else
if (m_filePath.compare(m_filePath.size()-3,3,".mm")==0)
m_lmtb->load(inp,m_filePath.c_str(),NULL,1);
else
m_lmtb->load(inp,m_filePath.c_str(),NULL,0);
#endif
}
m_lmtb_ng=new ngram(m_lmtb->getDict()); // ngram of words/micro tags
m_lmtb_size=m_lmtb->maxlevel();
// LM can be ok, just outputs warnings
// Mauro: in the original, the following two instructions are wrongly switched:
m_unknownId = m_lmtb->getDict()->oovcode(); // at the level of micro tags
CreateFactors(factorCollection);
VERBOSE(1, "IRST: m_unknownId=" << m_unknownId << std::endl);
//install caches
m_lmtb->init_probcache();
m_lmtb->init_statecache();
m_lmtb->init_lmtcaches(m_lmtb->maxlevel()>2?m_lmtb->maxlevel()-1:2);
m_lmtb->setlogOOVpenalty(m_lmtb_dub);
return true;
}
void LanguageModelIRST::CreateFactors(FactorCollection &factorCollection)
{ // add factors which have srilm id
// code copied & paste from SRI LM class. should do template function
std::map<size_t, int> lmIdMap;
size_t maxFactorId = 0; // to create lookup vector later on
dict_entry *entry;
dictionary_iter iter(m_lmtb->getDict()); // at the level of micro tags
while ( (entry = iter.next()) != NULL)
{
size_t factorId = factorCollection.AddFactor(Output, m_factorType, entry->word)->GetId();
lmIdMap[factorId] = entry->code;
maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;
}
size_t factorId;
m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
factorId = m_sentenceStart->GetId();
m_lmtb_sentenceStart=lmIdMap[factorId] = GetLmID(BOS_);
maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_);
factorId = m_sentenceEnd->GetId();
m_lmtb_sentenceEnd=lmIdMap[factorId] = GetLmID(EOS_);
maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
// add to lookup vector in object
m_lmIdLookup.resize(maxFactorId+1);
fill(m_lmIdLookup.begin(), m_lmIdLookup.end(), m_unknownId);
map<size_t, int>::iterator iterMap;
for (iterMap = lmIdMap.begin() ; iterMap != lmIdMap.end() ; ++iterMap)
{
m_lmIdLookup[iterMap->first] = iterMap->second;
}
}
int LanguageModelIRST::GetLmID( const std::string &str ) const
{
return m_lmtb->getDict()->encode( str.c_str() ); // at the level of micro tags
}
float LanguageModelIRST::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const
{
unsigned int dummy;
if (!len) { len = &dummy; }
FactorType factorType = GetFactorType();
// set up context
size_t count = contextFactor.size();
m_lmtb_ng->size=0;
if (count< (size_t)(m_lmtb_size-1)) m_lmtb_ng->pushc(m_lmtb_sentenceEnd);
if (count< (size_t)m_lmtb_size) m_lmtb_ng->pushc(m_lmtb_sentenceStart);
for (size_t i = 0 ; i < count ; i++)
{
//int lmId = GetLmID((*contextFactor[i])[factorType]);
#ifdef DEBUG
cout << "i=" << i << " -> " << (*contextFactor[i])[factorType]->GetString() << "\n";
#endif
int lmId = GetLmID((*contextFactor[i])[factorType]->GetString());
// cerr << (*contextFactor[i])[factorType]->GetString() << " = " << lmId;
m_lmtb_ng->pushc(lmId);
}
if (finalState){
*finalState=(State *)m_lmtb->cmaxsuffptr(*m_lmtb_ng);
// back off stats not currently available
*len = 0;
}
float prob = m_lmtb->clprob(*m_lmtb_ng);
//apply OOV penalty if the n-gram starts with an OOV word
//in a following version this will be integrated into the
//irstlm library
if (*m_lmtb_ng->wordp(1) == m_lmtb->dict->oovcode())
prob-=m_lmtb->getlogOOVpenalty();
return TransformIRSTScore(prob);
}
void LanguageModelIRST::CleanUpAfterSentenceProcessing(){
TRACE_ERR( "reset caches\n");
m_lmtb->reset_caches();
#ifndef WIN32
TRACE_ERR( "reset mmap\n");
m_lmtb->reset_mmap();
#endif
}
void LanguageModelIRST::InitializeBeforeSentenceProcessing(){
//nothing to do
#ifdef TRACE_CACHE
m_lmtb->sentence_id++;
#endif
}
<commit_msg>Fixed bug with dub option.<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library 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 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <limits>
#include <iostream>
#include <fstream>
#include "dictionary.h"
#include "n_gram.h"
#include "lmtable.h"
#include "lmmacro.h"
#include "LanguageModelIRST.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
LanguageModelIRST::LanguageModelIRST(bool registerScore, ScoreIndexManager &scoreIndexManager, int dub)
:LanguageModelSingleFactor(registerScore, scoreIndexManager)
,m_lmtb(0),m_lmtb_dub(dub)
{
}
LanguageModelIRST::~LanguageModelIRST()
{
delete m_lmtb;
delete m_lmtb_ng;
}
bool LanguageModelIRST::Load(const std::string &filePath,
FactorType factorType,
float weight,
size_t nGramOrder)
{
char *SepString = " \t\n";
cerr << "In LanguageModelIRST::Load: nGramOrder = " << nGramOrder << "\n";
FactorCollection &factorCollection = FactorCollection::Instance();
m_factorType = factorType;
m_weight = weight;
m_nGramOrder = nGramOrder;
// get name of LM file and, if any, of the micro-macro map file
char *filenames = strdup(filePath.c_str());
m_filePath = strsep(&filenames, SepString);
// Open the input file (possibly gzipped)
InputFileStream inp(m_filePath);
if (filenames) {
// case LMfile + MAPfile: create an object of lmmacro class and load both LM file and map
cerr << "Loading LM file + MAP\n";
m_mapFilePath = strsep(&filenames, SepString);
if (!FileExists(m_mapFilePath)) {
cerr << "ERROR: Map file <" << m_mapFilePath << "> does not exist\n";
return false;
}
InputFileStream inpMap(m_mapFilePath);
m_lmtb = new lmmacro(m_filePath, inp, inpMap);
} else {
// case (standard) LMfile only: create an object of lmtable
cerr << "Loading LM file (no MAP)\n";
m_lmtb = (lmtable *)new lmtable;
// Load the (possibly binary) model
#ifdef WIN32
m_lmtb->load(inp); //don't use memory map
#else
if (m_filePath.compare(m_filePath.size()-3,3,".mm")==0)
m_lmtb->load(inp,m_filePath.c_str(),NULL,1);
else
m_lmtb->load(inp,m_filePath.c_str(),NULL,0);
#endif
}
m_lmtb_ng=new ngram(m_lmtb->getDict()); // ngram of words/micro tags
m_lmtb_size=m_lmtb->maxlevel();
// LM can be ok, just outputs warnings
// Mauro: in the original, the following two instructions are wrongly switched:
m_unknownId = m_lmtb->getDict()->oovcode(); // at the level of micro tags
CreateFactors(factorCollection);
VERBOSE(1, "IRST: m_unknownId=" << m_unknownId << std::endl);
//install caches
m_lmtb->init_probcache();
m_lmtb->init_statecache();
m_lmtb->init_lmtcaches(m_lmtb->maxlevel()>2?m_lmtb->maxlevel()-1:2);
if (m_lmtb_dub >0) m_lmtb->setlogOOVpenalty(m_lmtb_dub);
return true;
}
void LanguageModelIRST::CreateFactors(FactorCollection &factorCollection)
{ // add factors which have srilm id
// code copied & paste from SRI LM class. should do template function
std::map<size_t, int> lmIdMap;
size_t maxFactorId = 0; // to create lookup vector later on
dict_entry *entry;
dictionary_iter iter(m_lmtb->getDict()); // at the level of micro tags
while ( (entry = iter.next()) != NULL)
{
size_t factorId = factorCollection.AddFactor(Output, m_factorType, entry->word)->GetId();
lmIdMap[factorId] = entry->code;
maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;
}
size_t factorId;
m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
factorId = m_sentenceStart->GetId();
m_lmtb_sentenceStart=lmIdMap[factorId] = GetLmID(BOS_);
maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_);
factorId = m_sentenceEnd->GetId();
m_lmtb_sentenceEnd=lmIdMap[factorId] = GetLmID(EOS_);
maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
// add to lookup vector in object
m_lmIdLookup.resize(maxFactorId+1);
fill(m_lmIdLookup.begin(), m_lmIdLookup.end(), m_unknownId);
map<size_t, int>::iterator iterMap;
for (iterMap = lmIdMap.begin() ; iterMap != lmIdMap.end() ; ++iterMap)
{
m_lmIdLookup[iterMap->first] = iterMap->second;
}
}
int LanguageModelIRST::GetLmID( const std::string &str ) const
{
return m_lmtb->getDict()->encode( str.c_str() ); // at the level of micro tags
}
float LanguageModelIRST::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const
{
unsigned int dummy;
if (!len) { len = &dummy; }
FactorType factorType = GetFactorType();
// set up context
size_t count = contextFactor.size();
m_lmtb_ng->size=0;
if (count< (size_t)(m_lmtb_size-1)) m_lmtb_ng->pushc(m_lmtb_sentenceEnd);
if (count< (size_t)m_lmtb_size) m_lmtb_ng->pushc(m_lmtb_sentenceStart);
for (size_t i = 0 ; i < count ; i++)
{
//int lmId = GetLmID((*contextFactor[i])[factorType]);
#ifdef DEBUG
cout << "i=" << i << " -> " << (*contextFactor[i])[factorType]->GetString() << "\n";
#endif
int lmId = GetLmID((*contextFactor[i])[factorType]->GetString());
// cerr << (*contextFactor[i])[factorType]->GetString() << " = " << lmId;
m_lmtb_ng->pushc(lmId);
}
if (finalState){
*finalState=(State *)m_lmtb->cmaxsuffptr(*m_lmtb_ng);
// back off stats not currently available
*len = 0;
}
float prob = m_lmtb->clprob(*m_lmtb_ng);
//apply OOV penalty if the n-gram starts with an OOV word
//in a following version this will be integrated into the
//irstlm library
if (*m_lmtb_ng->wordp(1) == m_lmtb->dict->oovcode())
prob-=m_lmtb->getlogOOVpenalty();
return TransformIRSTScore(prob);
}
void LanguageModelIRST::CleanUpAfterSentenceProcessing(){
TRACE_ERR( "reset caches\n");
m_lmtb->reset_caches();
#ifndef WIN32
TRACE_ERR( "reset mmap\n");
m_lmtb->reset_mmap();
#endif
}
void LanguageModelIRST::InitializeBeforeSentenceProcessing(){
//nothing to do
#ifdef TRACE_CACHE
m_lmtb->sentence_id++;
#endif
}
<|endoftext|> |
<commit_before>#include "EM.h"
#include "MathFunctions.h"
#include <iostream>
EM::~EM() {
}
EM::EM(const std::vector<double> &data, const std::vector<Param> ¶ms) :
data_(data),
params_(params),
pikn_(data.size(), std::vector<double>(params.size(),0)) {
if(data_.size() == 0)
throw(std::runtime_error("Cannot initialize EM with empty dataset"));
double psum = 0;
for(int i=0; i<params_.size(); i++) {
psum += params_[i].p;
if(params_[i].p <= 0)
throw(std::runtime_error("Cannot have p <= 0 in parameters"));
if(params_[i].p > 1)
throw(std::runtime_error("Cannot have p > 1 in parameters"));
if(params_[i].s <= 0)
throw(std::runtime_error("Cannot have s <= 0 in parameters"));
}
if(psum > 1.0001) {
throw(std::runtime_error("Initial probabilities sum to greater than 1"));
}
}
void EM::setParams(const std::vector<Param> &input) {
params_ = input;
}
std::vector<Param> EM::getParams() const {
return params_;
}
int EM::getDataSize() const {
return data_.size();
}
double EM::getLikelihood() const {
double lambda = 0;
for(int n=0; n<data_.size(); n++) {
double sum = 0;
for(int k=0; k<params_.size(); k++) {
sum += qkn(k,n);
}
lambda += log(sum);
}
return lambda;
}
#include <iostream>
using namespace std;
bool EM::run(int maxSteps, double tolerance) {
int steps = 0;
double likelihood = getLikelihood();
double likelihoodOld = likelihood;
do {
likelihoodOld = likelihood;
EStep();
MStep();
steps++;
likelihood = getLikelihood();
} while(fabs(likelihoodOld - likelihood) > tolerance && steps < maxSteps);
return (steps < maxSteps);
}
void EM::EStep() {
for(int n=0; n<data_.size(); n++) {
double sum = 0;
for(int k=0; k<params_.size(); k++) {
sum += qkn(k,n);
}
for(int k=0; k<params_.size(); k++) {
pikn_[n][k] = qkn(k,n)/sum;
}
}
testIntegrity();
}
void EM::testIntegrity() const {
double sum = 0;
for(int k=0; k<params_.size(); k++) {
for(int n=0; n<data_.size(); n++) {
sum += pikn_[n][k];
}
if(fabs(sum-1.0) < 0.01) {
throw(std::runtime_error("pikn no longer sums to 1"));
}
}
};
<commit_msg>Removed extraneous cout<commit_after>#include "EM.h"
#include "MathFunctions.h"
#include <iostream>
EM::~EM() {
}
EM::EM(const std::vector<double> &data, const std::vector<Param> ¶ms) :
data_(data),
params_(params),
pikn_(data.size(), std::vector<double>(params.size(),0)) {
if(data_.size() == 0)
throw(std::runtime_error("Cannot initialize EM with empty dataset"));
double psum = 0;
for(int i=0; i<params_.size(); i++) {
psum += params_[i].p;
if(params_[i].p <= 0)
throw(std::runtime_error("Cannot have p <= 0 in parameters"));
if(params_[i].p > 1)
throw(std::runtime_error("Cannot have p > 1 in parameters"));
if(params_[i].s <= 0)
throw(std::runtime_error("Cannot have s <= 0 in parameters"));
}
if(psum > 1.0001) {
throw(std::runtime_error("Initial probabilities sum to greater than 1"));
}
}
void EM::setParams(const std::vector<Param> &input) {
params_ = input;
}
std::vector<Param> EM::getParams() const {
return params_;
}
int EM::getDataSize() const {
return data_.size();
}
double EM::getLikelihood() const {
double lambda = 0;
for(int n=0; n<data_.size(); n++) {
double sum = 0;
for(int k=0; k<params_.size(); k++) {
sum += qkn(k,n);
}
lambda += log(sum);
}
return lambda;
}
bool EM::run(int maxSteps, double tolerance) {
int steps = 0;
double likelihood = getLikelihood();
double likelihoodOld = likelihood;
do {
likelihoodOld = likelihood;
EStep();
MStep();
steps++;
likelihood = getLikelihood();
} while(fabs(likelihoodOld - likelihood) > tolerance && steps < maxSteps);
return (steps < maxSteps);
}
void EM::EStep() {
for(int n=0; n<data_.size(); n++) {
double sum = 0;
for(int k=0; k<params_.size(); k++) {
sum += qkn(k,n);
}
for(int k=0; k<params_.size(); k++) {
pikn_[n][k] = qkn(k,n)/sum;
}
}
testIntegrity();
}
void EM::testIntegrity() const {
double sum = 0;
for(int k=0; k<params_.size(); k++) {
for(int n=0; n<data_.size(); n++) {
sum += pikn_[n][k];
}
if(fabs(sum-1.0) < 0.01) {
throw(std::runtime_error("pikn no longer sums to 1"));
}
}
};
<|endoftext|> |
<commit_before>// source_expr.C -- Data source for gnuplot interface
//
// Copyright 2005 Per Abrahamsen and KVL.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "source_file.h"
#include "scope_table.h"
#include "number.h"
struct SourceExpr : public SourceFile
{
// Content.
const std::auto_ptr<Number> expr;
const std::string title_;
std::string dimension_;
// Interface.
public:
const std::string& title () const
{ return title_; }
const std::string& dimension () const
{ return dimension_; }
// Read.
public:
bool load (Treelog& msg);
// Create and Destroy.
public:
explicit SourceExpr (Block& al);
~SourceExpr ();
};
bool
SourceExpr::load (Treelog& msg)
{
// Lex it.
if (!read_header (msg))
return false;
// Scope
ScopeTable scope (lex);
if (!expr->initialize (msg) || !expr->check (scope, msg))
{
lex.error ("Bad expression");
return false;
}
dimension_ = expr->dimension (scope);
// Read data.
Time last_time (9999, 12, 31, 23);
std::vector<double> vals;
while (lex.good ())
{
// Read entries.
Time time (9999, 1, 1, 0);
std::vector<std::string> entries;
if (!read_entry (entries, time))
continue;
// Set it.
scope.set (entries);
// Missing value.
if (expr->missing (scope))
continue;
// Store it.
vals.push_back (expr->value (scope));
if (time != last_time)
{
last_time = time;
add_entry (time, vals);
}
}
if (vals.size () > 0)
add_entry (last_time, vals);
// Done.
return true;
}
SourceExpr::SourceExpr (Block& al)
: SourceFile (al),
expr (Librarian<Number>::build_item (al, "expr")),
title_ (al.name ("title", expr->title ())),
dimension_ ("UNINITIALIZED")
{ }
SourceExpr::~SourceExpr ()
{ }
static struct SourceExprSyntax
{
static Source& make (Block& al)
{ return *new SourceExpr (al); }
SourceExprSyntax ()
{
Syntax& syntax = *new Syntax ();
AttributeList& alist = *new AttributeList ();
SourceFile::load_style (syntax, alist, "\
By default the name of the 'expr' object.");
alist.add ("description",
"Read a daisy log, weather or data file.\n\
Calculate a single value for each time step, based on the value\n\
in the various columns.");
syntax.add ("expr", Librarian<Number>::library (),
Syntax::Const, Syntax::Singleton, "\
Expression for calculating the value for this source for each row.\n\
The expression can refer to the value in a specific column by the tag\n\
for that column.");
Librarian<Source>::add_type ("arithmetic", alist, syntax, &make);
}
} SourceExpr_syntax;
// source_expr.C ends here.
<commit_msg>kvl-t<commit_after>// source_expr.C -- Data source for gnuplot interface
//
// Copyright 2005 Per Abrahamsen and KVL.
//
// This file is part of Daisy.
//
// Daisy is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// Daisy 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 Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with Daisy; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#include "source_file.h"
#include "scope_table.h"
#include "number.h"
struct SourceExpr : public SourceFile
{
// Content.
const std::auto_ptr<Number> expr;
const std::string title_;
std::string dimension_;
// Interface.
public:
const std::string& title () const
{ return title_; }
const std::string& dimension () const
{ return dimension_; }
// Read.
public:
bool load (Treelog& msg);
// Create and Destroy.
public:
explicit SourceExpr (Block& al);
~SourceExpr ();
};
bool
SourceExpr::load (Treelog& msg)
{
// Lex it.
if (!read_header (msg))
return false;
// Scope
ScopeTable scope (lex);
if (!expr->initialize (msg) || !expr->check (scope, msg))
{
lex.error ("Bad expression");
return false;
}
dimension_ = expr->dimension (scope);
// Read data.
Time last_time (9999, 12, 31, 23);
std::vector<double> vals;
while (lex.good ())
{
// Read entries.
Time time (9999, 1, 1, 0);
std::vector<std::string> entries;
if (!read_entry (entries, time))
continue;
// Set it.
scope.set (entries);
// Missing value.
if (expr->missing (scope))
continue;
// Store it.
if (time != last_time)
{
if (vals.size () > 0)
add_entry (last_time, vals);
last_time = time;
}
vals.push_back (expr->value (scope));
}
if (vals.size () > 0)
add_entry (last_time, vals);
// Done.
return true;
}
SourceExpr::SourceExpr (Block& al)
: SourceFile (al),
expr (Librarian<Number>::build_item (al, "expr")),
title_ (al.name ("title", expr->title ())),
dimension_ ("UNINITIALIZED")
{ }
SourceExpr::~SourceExpr ()
{ }
static struct SourceExprSyntax
{
static Source& make (Block& al)
{ return *new SourceExpr (al); }
SourceExprSyntax ()
{
Syntax& syntax = *new Syntax ();
AttributeList& alist = *new AttributeList ();
SourceFile::load_style (syntax, alist, "\
By default the name of the 'expr' object.");
alist.add ("description",
"Read a daisy log, weather or data file.\n\
Calculate a single value for each time step, based on the value\n\
in the various columns.");
syntax.add ("expr", Librarian<Number>::library (),
Syntax::Const, Syntax::Singleton, "\
Expression for calculating the value for this source for each row.\n\
The expression can refer to the value in a specific column by the tag\n\
for that column.");
Librarian<Source>::add_type ("arithmetic", alist, syntax, &make);
}
} SourceExpr_syntax;
// source_expr.C ends here.
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNumericTraits.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkNumericTraits.h"
namespace itk
{
const bool NumericTraits<bool>::Zero = false;
const bool NumericTraits<bool>::One = true;
const unsigned char NumericTraits<unsigned char>::Zero = 0;
const unsigned char NumericTraits<unsigned char>::One = 1;
const signed char NumericTraits<signed char>::Zero = 0;
const signed char NumericTraits<signed char>::One = 1;
const char NumericTraits<char>::Zero = 0;
const char NumericTraits<char>::One = 1;
const unsigned short NumericTraits<unsigned short>::Zero = 0;
const unsigned short NumericTraits<unsigned short>::One = 1;
const short NumericTraits<short>::Zero = 0;
const short NumericTraits<short>::One = 1;
const unsigned int NumericTraits<unsigned int>::Zero = 0;
const unsigned int NumericTraits<unsigned int>::One = 1;
const int NumericTraits<int>::Zero = 0;
const int NumericTraits<int>::One = 1;
const unsigned long NumericTraits<unsigned long>::Zero = 0;
const unsigned long NumericTraits<unsigned long>::One = 1;
const long NumericTraits<long>::Zero = 0UL;
const long NumericTraits<long>::One = 1UL;
const float NumericTraits<float>::Zero = 0.0F;
const float NumericTraits<float>::One = 1.0F;
const double NumericTraits<double>::Zero = 0.0;
const double NumericTraits<double>::One = 1.0;
const long double NumericTraits<long double>::Zero = 0.0;
const long double NumericTraits<long double>::One = 1.0;
const std::complex<float> NumericTraits< std::complex<float> >::Zero = std::complex<float>(0.0,0.0);
const std::complex<float> NumericTraits< std::complex<float> >::One = std::complex<float>(1.0,0.0);
const std::complex<double> NumericTraits< std::complex<double> >::Zero = std::complex<double>(0.0,0.0);
const std::complex<double> NumericTraits< std::complex<double> >::One = std::complex<double>(1.0,0.0);
} // end namespace itk
<commit_msg>ENH: Adding declaration for size_type under _WIN64. This will be used from the new statistics framework.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNumericTraits.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkNumericTraits.h"
namespace itk
{
const bool NumericTraits<bool>::Zero = false;
const bool NumericTraits<bool>::One = true;
const unsigned char NumericTraits<unsigned char>::Zero = 0;
const unsigned char NumericTraits<unsigned char>::One = 1;
const signed char NumericTraits<signed char>::Zero = 0;
const signed char NumericTraits<signed char>::One = 1;
const char NumericTraits<char>::Zero = 0;
const char NumericTraits<char>::One = 1;
const unsigned short NumericTraits<unsigned short>::Zero = 0;
const unsigned short NumericTraits<unsigned short>::One = 1;
const short NumericTraits<short>::Zero = 0;
const short NumericTraits<short>::One = 1;
const unsigned int NumericTraits<unsigned int>::Zero = 0;
const unsigned int NumericTraits<unsigned int>::One = 1;
const int NumericTraits<int>::Zero = 0;
const int NumericTraits<int>::One = 1;
const unsigned long NumericTraits<unsigned long>::Zero = 0;
const unsigned long NumericTraits<unsigned long>::One = 1;
const long NumericTraits<long>::Zero = 0UL;
const long NumericTraits<long>::One = 1UL;
const float NumericTraits<float>::Zero = 0.0F;
const float NumericTraits<float>::One = 1.0F;
const double NumericTraits<double>::Zero = 0.0;
const double NumericTraits<double>::One = 1.0;
const long double NumericTraits<long double>::Zero = 0.0;
const long double NumericTraits<long double>::One = 1.0;
#ifdef _WIN64
typedef std::string::size_type size_type;
const size_type NumericTraits<size_type>::Zero = 0.0;
const size_type NumericTraits<size_type>::One = 1.0;
#endif
const std::complex<float> NumericTraits< std::complex<float> >::Zero = std::complex<float>(0.0,0.0);
const std::complex<float> NumericTraits< std::complex<float> >::One = std::complex<float>(1.0,0.0);
const std::complex<double> NumericTraits< std::complex<double> >::Zero = std::complex<double>(0.0,0.0);
const std::complex<double> NumericTraits< std::complex<double> >::One = std::complex<double>(1.0,0.0);
} // end namespace itk
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/proxy/single_threaded_proxy_resolver.h"
#include "base/thread.h"
#include "net/base/load_log.h"
#include "net/base/net_errors.h"
#include "net/proxy/proxy_info.h"
namespace net {
namespace {
class PurgeMemoryTask : public base::RefCountedThreadSafe<PurgeMemoryTask> {
public:
explicit PurgeMemoryTask(ProxyResolver* resolver) : resolver_(resolver) {}
void PurgeMemory() { resolver_->PurgeMemory(); }
private:
ProxyResolver* resolver_;
};
}
// SingleThreadedProxyResolver::SetPacScriptTask ------------------------------
// Runs on the worker thread to call ProxyResolver::SetPacScript.
class SingleThreadedProxyResolver::SetPacScriptTask
: public base::RefCountedThreadSafe<
SingleThreadedProxyResolver::SetPacScriptTask> {
public:
SetPacScriptTask(SingleThreadedProxyResolver* coordinator,
const GURL& pac_url,
const std::string& pac_bytes,
CompletionCallback* callback)
: coordinator_(coordinator),
callback_(callback),
pac_bytes_(pac_bytes),
pac_url_(pac_url),
origin_loop_(MessageLoop::current()) {
DCHECK(callback);
}
// Start the SetPacScript request on the worker thread.
void Start() {
// TODO(eroman): Are these manual AddRef / Release necessary?
AddRef(); // balanced in RequestComplete
coordinator_->thread()->message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(this, &SetPacScriptTask::DoRequest,
coordinator_->resolver_.get()));
}
void Cancel() {
// Clear these to inform RequestComplete that it should not try to
// access them.
coordinator_ = NULL;
callback_ = NULL;
}
// Returns true if Cancel() has been called.
bool was_cancelled() const { return callback_ == NULL; }
private:
// Runs on the worker thread.
void DoRequest(ProxyResolver* resolver) {
int rv = resolver->expects_pac_bytes() ?
resolver->SetPacScriptByData(pac_bytes_, NULL) :
resolver->SetPacScriptByUrl(pac_url_, NULL);
DCHECK_NE(rv, ERR_IO_PENDING);
origin_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this, &SetPacScriptTask::RequestComplete, rv));
}
// Runs the completion callback on the origin thread.
void RequestComplete(int result_code) {
// The task may have been cancelled after it was started.
if (!was_cancelled()) {
CompletionCallback* callback = callback_;
coordinator_->RemoveOutstandingSetPacScriptTask(this);
callback->Run(result_code);
}
Release(); // Balances the AddRef in Start.
}
// Must only be used on the "origin" thread.
SingleThreadedProxyResolver* coordinator_;
CompletionCallback* callback_;
std::string pac_bytes_;
GURL pac_url_;
// Usable from within DoQuery on the worker thread.
MessageLoop* origin_loop_;
};
// SingleThreadedProxyResolver::Job -------------------------------------------
class SingleThreadedProxyResolver::Job
: public base::RefCountedThreadSafe<SingleThreadedProxyResolver::Job> {
public:
// |coordinator| -- the SingleThreadedProxyResolver that owns this job.
// |url| -- the URL of the query.
// |results| -- the structure to fill with proxy resolve results.
Job(SingleThreadedProxyResolver* coordinator,
const GURL& url,
ProxyInfo* results,
CompletionCallback* callback,
LoadLog* load_log)
: coordinator_(coordinator),
callback_(callback),
results_(results),
load_log_(load_log),
url_(url),
is_started_(false),
origin_loop_(MessageLoop::current()) {
DCHECK(callback);
}
// Start the resolve proxy request on the worker thread.
void Start() {
is_started_ = true;
AddRef(); // balanced in QueryComplete
coordinator_->thread()->message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(this, &Job::DoQuery,
coordinator_->resolver_.get()));
}
bool is_started() const { return is_started_; }
void Cancel() {
// Clear these to inform QueryComplete that it should not try to
// access them.
coordinator_ = NULL;
callback_ = NULL;
results_ = NULL;
}
// Returns true if Cancel() has been called.
bool was_cancelled() const { return callback_ == NULL; }
private:
// Runs on the worker thread.
void DoQuery(ProxyResolver* resolver) {
scoped_refptr<LoadLog> worker_log(new LoadLog);
int rv = resolver->GetProxyForURL(url_, &results_buf_, NULL, NULL,
worker_log);
DCHECK_NE(rv, ERR_IO_PENDING);
worker_log->AddRef(); // Balanced in QueryComplete.
origin_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this, &Job::QueryComplete, rv, worker_log));
}
// Runs the completion callback on the origin thread.
void QueryComplete(int result_code, LoadLog* worker_log) {
// Merge the load log that was generated on the worker thread, into the
// main log.
if (load_log_)
load_log_->Append(worker_log);
worker_log->Release();
// The Job may have been cancelled after it was started.
if (!was_cancelled()) {
if (result_code >= OK) { // Note: unit-tests use values > 0.
results_->Use(results_buf_);
}
callback_->Run(result_code);
// We check for cancellation once again, in case the callback deleted
// the owning ProxyService (whose destructor will in turn cancel us).
if (!was_cancelled())
coordinator_->RemoveFrontOfJobsQueueAndStartNext(this);
}
Release(); // Balances the AddRef in Start. We may get deleted after
// we return.
}
// Must only be used on the "origin" thread.
SingleThreadedProxyResolver* coordinator_;
CompletionCallback* callback_;
ProxyInfo* results_;
scoped_refptr<LoadLog> load_log_;
GURL url_;
bool is_started_;
// Usable from within DoQuery on the worker thread.
ProxyInfo results_buf_;
MessageLoop* origin_loop_;
};
// SingleThreadedProxyResolver ------------------------------------------------
SingleThreadedProxyResolver::SingleThreadedProxyResolver(
ProxyResolver* resolver)
: ProxyResolver(resolver->expects_pac_bytes()),
resolver_(resolver) {
}
SingleThreadedProxyResolver::~SingleThreadedProxyResolver() {
// Cancel the inprogress job (if any), and free the rest.
for (PendingJobsQueue::iterator it = pending_jobs_.begin();
it != pending_jobs_.end();
++it) {
(*it)->Cancel();
}
if (outstanding_set_pac_script_task_)
outstanding_set_pac_script_task_->Cancel();
// Note that |thread_| is destroyed before |resolver_|. This is important
// since |resolver_| could be running on |thread_|.
}
int SingleThreadedProxyResolver::GetProxyForURL(const GURL& url,
ProxyInfo* results,
CompletionCallback* callback,
RequestHandle* request,
LoadLog* load_log) {
DCHECK(callback);
scoped_refptr<Job> job = new Job(this, url, results, callback, load_log);
pending_jobs_.push_back(job);
ProcessPendingJobs(); // Jobs can never finish synchronously.
// Completion will be notified through |callback|, unless the caller cancels
// the request using |request|.
if (request)
*request = reinterpret_cast<RequestHandle>(job.get());
return ERR_IO_PENDING;
}
// There are three states of the request we need to handle:
// (1) Not started (just sitting in the queue).
// (2) Executing Job::DoQuery in the worker thread.
// (3) Waiting for Job::QueryComplete to be run on the origin thread.
void SingleThreadedProxyResolver::CancelRequest(RequestHandle req) {
DCHECK(req);
Job* job = reinterpret_cast<Job*>(req);
bool is_active_job = job->is_started() && !pending_jobs_.empty() &&
pending_jobs_.front().get() == job;
job->Cancel();
if (is_active_job) {
RemoveFrontOfJobsQueueAndStartNext(job);
return;
}
// Otherwise just delete the job from the queue.
PendingJobsQueue::iterator it = std::find(
pending_jobs_.begin(), pending_jobs_.end(), job);
DCHECK(it != pending_jobs_.end());
pending_jobs_.erase(it);
}
void SingleThreadedProxyResolver::CancelSetPacScript() {
DCHECK(outstanding_set_pac_script_task_);
outstanding_set_pac_script_task_->Cancel();
outstanding_set_pac_script_task_ = NULL;
}
void SingleThreadedProxyResolver::PurgeMemory() {
if (thread_.get()) {
scoped_refptr<PurgeMemoryTask> helper(new PurgeMemoryTask(resolver_.get()));
thread_->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(helper.get(), &PurgeMemoryTask::PurgeMemory));
}
}
int SingleThreadedProxyResolver::SetPacScript(
const GURL& pac_url,
const std::string& pac_bytes,
CompletionCallback* callback) {
EnsureThreadStarted();
DCHECK(!outstanding_set_pac_script_task_);
SetPacScriptTask* task = new SetPacScriptTask(
this, pac_url, pac_bytes, callback);
outstanding_set_pac_script_task_ = task;
task->Start();
return ERR_IO_PENDING;
}
void SingleThreadedProxyResolver::EnsureThreadStarted() {
if (!thread_.get()) {
thread_.reset(new base::Thread("pac-thread"));
thread_->Start();
}
}
void SingleThreadedProxyResolver::ProcessPendingJobs() {
if (pending_jobs_.empty())
return;
// Get the next job to process (FIFO).
Job* job = pending_jobs_.front().get();
if (job->is_started())
return;
EnsureThreadStarted();
job->Start();
}
void SingleThreadedProxyResolver::RemoveFrontOfJobsQueueAndStartNext(
Job* expected_job) {
DCHECK_EQ(expected_job, pending_jobs_.front().get());
pending_jobs_.pop_front();
// Start next work item.
ProcessPendingJobs();
}
void SingleThreadedProxyResolver::RemoveOutstandingSetPacScriptTask(
SetPacScriptTask* task) {
DCHECK_EQ(outstanding_set_pac_script_task_.get(), task);
outstanding_set_pac_script_task_ = NULL;
}
} // namespace net
<commit_msg>Remove some unnecessary manual AddRef/Release.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/proxy/single_threaded_proxy_resolver.h"
#include "base/thread.h"
#include "net/base/load_log.h"
#include "net/base/net_errors.h"
#include "net/proxy/proxy_info.h"
namespace net {
namespace {
class PurgeMemoryTask : public base::RefCountedThreadSafe<PurgeMemoryTask> {
public:
explicit PurgeMemoryTask(ProxyResolver* resolver) : resolver_(resolver) {}
void PurgeMemory() { resolver_->PurgeMemory(); }
private:
ProxyResolver* resolver_;
};
}
// SingleThreadedProxyResolver::SetPacScriptTask ------------------------------
// Runs on the worker thread to call ProxyResolver::SetPacScript.
class SingleThreadedProxyResolver::SetPacScriptTask
: public base::RefCountedThreadSafe<
SingleThreadedProxyResolver::SetPacScriptTask> {
public:
SetPacScriptTask(SingleThreadedProxyResolver* coordinator,
const GURL& pac_url,
const std::string& pac_bytes,
CompletionCallback* callback)
: coordinator_(coordinator),
callback_(callback),
pac_bytes_(pac_bytes),
pac_url_(pac_url),
origin_loop_(MessageLoop::current()) {
DCHECK(callback);
}
// Start the SetPacScript request on the worker thread.
void Start() {
coordinator_->thread()->message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(this, &SetPacScriptTask::DoRequest,
coordinator_->resolver_.get()));
}
void Cancel() {
// Clear these to inform RequestComplete that it should not try to
// access them.
coordinator_ = NULL;
callback_ = NULL;
}
// Returns true if Cancel() has been called.
bool was_cancelled() const { return callback_ == NULL; }
private:
// Runs on the worker thread.
void DoRequest(ProxyResolver* resolver) {
int rv = resolver->expects_pac_bytes() ?
resolver->SetPacScriptByData(pac_bytes_, NULL) :
resolver->SetPacScriptByUrl(pac_url_, NULL);
DCHECK_NE(rv, ERR_IO_PENDING);
origin_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this, &SetPacScriptTask::RequestComplete, rv));
}
// Runs the completion callback on the origin thread.
void RequestComplete(int result_code) {
// The task may have been cancelled after it was started.
if (!was_cancelled()) {
CompletionCallback* callback = callback_;
coordinator_->RemoveOutstandingSetPacScriptTask(this);
callback->Run(result_code);
}
}
// Must only be used on the "origin" thread.
SingleThreadedProxyResolver* coordinator_;
CompletionCallback* callback_;
std::string pac_bytes_;
GURL pac_url_;
// Usable from within DoQuery on the worker thread.
MessageLoop* origin_loop_;
};
// SingleThreadedProxyResolver::Job -------------------------------------------
class SingleThreadedProxyResolver::Job
: public base::RefCountedThreadSafe<SingleThreadedProxyResolver::Job> {
public:
// |coordinator| -- the SingleThreadedProxyResolver that owns this job.
// |url| -- the URL of the query.
// |results| -- the structure to fill with proxy resolve results.
Job(SingleThreadedProxyResolver* coordinator,
const GURL& url,
ProxyInfo* results,
CompletionCallback* callback,
LoadLog* load_log)
: coordinator_(coordinator),
callback_(callback),
results_(results),
load_log_(load_log),
url_(url),
is_started_(false),
origin_loop_(MessageLoop::current()) {
DCHECK(callback);
}
// Start the resolve proxy request on the worker thread.
void Start() {
is_started_ = true;
coordinator_->thread()->message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(this, &Job::DoQuery,
coordinator_->resolver_.get()));
}
bool is_started() const { return is_started_; }
void Cancel() {
// Clear these to inform QueryComplete that it should not try to
// access them.
coordinator_ = NULL;
callback_ = NULL;
results_ = NULL;
}
// Returns true if Cancel() has been called.
bool was_cancelled() const { return callback_ == NULL; }
private:
// Runs on the worker thread.
void DoQuery(ProxyResolver* resolver) {
scoped_refptr<LoadLog> worker_log(new LoadLog);
int rv = resolver->GetProxyForURL(url_, &results_buf_, NULL, NULL,
worker_log);
DCHECK_NE(rv, ERR_IO_PENDING);
worker_log->AddRef(); // Balanced in QueryComplete.
origin_loop_->PostTask(FROM_HERE,
NewRunnableMethod(this, &Job::QueryComplete, rv, worker_log));
}
// Runs the completion callback on the origin thread.
void QueryComplete(int result_code, LoadLog* worker_log) {
// Merge the load log that was generated on the worker thread, into the
// main log.
if (load_log_)
load_log_->Append(worker_log);
worker_log->Release();
// The Job may have been cancelled after it was started.
if (!was_cancelled()) {
if (result_code >= OK) { // Note: unit-tests use values > 0.
results_->Use(results_buf_);
}
callback_->Run(result_code);
// We check for cancellation once again, in case the callback deleted
// the owning ProxyService (whose destructor will in turn cancel us).
if (!was_cancelled())
coordinator_->RemoveFrontOfJobsQueueAndStartNext(this);
}
}
// Must only be used on the "origin" thread.
SingleThreadedProxyResolver* coordinator_;
CompletionCallback* callback_;
ProxyInfo* results_;
scoped_refptr<LoadLog> load_log_;
GURL url_;
bool is_started_;
// Usable from within DoQuery on the worker thread.
ProxyInfo results_buf_;
MessageLoop* origin_loop_;
};
// SingleThreadedProxyResolver ------------------------------------------------
SingleThreadedProxyResolver::SingleThreadedProxyResolver(
ProxyResolver* resolver)
: ProxyResolver(resolver->expects_pac_bytes()),
resolver_(resolver) {
}
SingleThreadedProxyResolver::~SingleThreadedProxyResolver() {
// Cancel the inprogress job (if any), and free the rest.
for (PendingJobsQueue::iterator it = pending_jobs_.begin();
it != pending_jobs_.end();
++it) {
(*it)->Cancel();
}
if (outstanding_set_pac_script_task_)
outstanding_set_pac_script_task_->Cancel();
// Note that |thread_| is destroyed before |resolver_|. This is important
// since |resolver_| could be running on |thread_|.
}
int SingleThreadedProxyResolver::GetProxyForURL(const GURL& url,
ProxyInfo* results,
CompletionCallback* callback,
RequestHandle* request,
LoadLog* load_log) {
DCHECK(callback);
scoped_refptr<Job> job = new Job(this, url, results, callback, load_log);
pending_jobs_.push_back(job);
ProcessPendingJobs(); // Jobs can never finish synchronously.
// Completion will be notified through |callback|, unless the caller cancels
// the request using |request|.
if (request)
*request = reinterpret_cast<RequestHandle>(job.get());
return ERR_IO_PENDING;
}
// There are three states of the request we need to handle:
// (1) Not started (just sitting in the queue).
// (2) Executing Job::DoQuery in the worker thread.
// (3) Waiting for Job::QueryComplete to be run on the origin thread.
void SingleThreadedProxyResolver::CancelRequest(RequestHandle req) {
DCHECK(req);
Job* job = reinterpret_cast<Job*>(req);
bool is_active_job = job->is_started() && !pending_jobs_.empty() &&
pending_jobs_.front().get() == job;
job->Cancel();
if (is_active_job) {
RemoveFrontOfJobsQueueAndStartNext(job);
return;
}
// Otherwise just delete the job from the queue.
PendingJobsQueue::iterator it = std::find(
pending_jobs_.begin(), pending_jobs_.end(), job);
DCHECK(it != pending_jobs_.end());
pending_jobs_.erase(it);
}
void SingleThreadedProxyResolver::CancelSetPacScript() {
DCHECK(outstanding_set_pac_script_task_);
outstanding_set_pac_script_task_->Cancel();
outstanding_set_pac_script_task_ = NULL;
}
void SingleThreadedProxyResolver::PurgeMemory() {
if (thread_.get()) {
scoped_refptr<PurgeMemoryTask> helper(new PurgeMemoryTask(resolver_.get()));
thread_->message_loop()->PostTask(FROM_HERE,
NewRunnableMethod(helper.get(), &PurgeMemoryTask::PurgeMemory));
}
}
int SingleThreadedProxyResolver::SetPacScript(
const GURL& pac_url,
const std::string& pac_bytes,
CompletionCallback* callback) {
EnsureThreadStarted();
DCHECK(!outstanding_set_pac_script_task_);
SetPacScriptTask* task = new SetPacScriptTask(
this, pac_url, pac_bytes, callback);
outstanding_set_pac_script_task_ = task;
task->Start();
return ERR_IO_PENDING;
}
void SingleThreadedProxyResolver::EnsureThreadStarted() {
if (!thread_.get()) {
thread_.reset(new base::Thread("pac-thread"));
thread_->Start();
}
}
void SingleThreadedProxyResolver::ProcessPendingJobs() {
if (pending_jobs_.empty())
return;
// Get the next job to process (FIFO).
Job* job = pending_jobs_.front().get();
if (job->is_started())
return;
EnsureThreadStarted();
job->Start();
}
void SingleThreadedProxyResolver::RemoveFrontOfJobsQueueAndStartNext(
Job* expected_job) {
DCHECK_EQ(expected_job, pending_jobs_.front().get());
pending_jobs_.pop_front();
// Start next work item.
ProcessPendingJobs();
}
void SingleThreadedProxyResolver::RemoveOutstandingSetPacScriptTask(
SetPacScriptTask* task) {
DCHECK_EQ(outstanding_set_pac_script_task_.get(), task);
outstanding_set_pac_script_task_ = NULL;
}
} // namespace net
<|endoftext|> |
<commit_before>#include "inmost.h"
#include <stdio.h>
using namespace INMOST;
typedef Storage::real real;
typedef Storage::real_array real_array;
int main(int argc, char ** argv)
{
if( argc < 2 )
{
printf("Usage: %s input_mesh [rotation_angle=0 degrees] [refine_boundary=1] [output_mesh]\n",argv[0]);
return -1;
}
Mesh m;
m.Load(argv[1]);
const double pi = 3.1415926536;
double theta = 0, ct, st;
int refine = 1;
if( argc > 2 ) theta = atof(argv[2])/180.0*pi;
if( argc > 3 ) refine = atoi(argv[3]);
ct = cos(theta);
st = sin(theta);
double xmin = 1.0e20, xmax = -1.0e20;
double ymin = 1.0e20, ymax = -1.0e20;
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double x = n->Coords()[0];
double y = n->Coords()[1];
if( x > xmax ) xmax = x;
if( x < xmin ) xmin = x;
if( y > ymax ) ymax = y;
if( y < ymin ) ymin = y;
}
std::cout << "x: " << xmin << ":" << xmax << std::endl;
std::cout << "y: " << ymin << ":" << ymax << std::endl;
if( refine )
{
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double a = (n->Coords()[0]-xmin)/(xmax-xmin);
a = sin(3.14159265359*a/2.0);
n->Coords()[0] = (xmax-xmin)*a + xmin;
}
}
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double x = n->Coords()[0], mx = x;
double y = n->Coords()[1], my = y;
double alpha = pi/4*(2*y-1);
mx += 1 - x*(1-cos(alpha)) + x*cos(2*alpha)*0.2;
my += x*sin(alpha);
n->Coords()[0] = (mx-0.5)*ct - (my-0.5)*st + 0.5;
n->Coords()[1] = (mx-0.5)*st + (my-0.5)*ct + 0.5;
}
xmin = 1.0e20, xmax = -1.0e20;
ymin = 1.0e20, ymax = -1.0e20;
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double x = n->Coords()[0];
double y = n->Coords()[1];
if( x > xmax ) xmax = x;
if( x < xmin ) xmin = x;
if( y > ymax ) ymax = y;
if( y < ymin ) ymin = y;
}
std::cout << "x: " << xmin << ":" << xmax << std::endl;
std::cout << "y: " << ymin << ":" << ymax << std::endl;
if( argc > 4 )
{
std::cout << "Save to " << argv[4] << std::endl;
m.Save(argv[4]);
}
else
{
std::cout << "Save to out.vtk" << std::endl;
m.Save("out.vtk");
}
return 0;
}
<commit_msg>Different options to create sector mesh in Examples/GridTools/Sector<commit_after>#include "inmost.h"
#include <stdio.h>
using namespace INMOST;
typedef Storage::real real;
typedef Storage::real_array real_array;
int main(int argc, char ** argv)
{
if( argc < 2 )
{
printf("Usage: %s input_mesh [rotation_angle=0 degrees] [refine_boundary=1] [output_mesh] [type=0]\n",argv[0]);
return -1;
}
Mesh m;
m.Load(argv[1]);
const double pi = 3.1415926536;
double theta = 0, ct, st;
int refine = 1;
int stype = 0;
if( argc > 2 ) theta = atof(argv[2])/180.0*pi;
if( argc > 3 ) refine = atoi(argv[3]);
if( argc > 5 ) stype = atoi(argv[5]);
ct = cos(theta);
st = sin(theta);
double xmin = 1.0e20, xmax = -1.0e20;
double ymin = 1.0e20, ymax = -1.0e20;
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double x = n->Coords()[0];
double y = n->Coords()[1];
if( x > xmax ) xmax = x;
if( x < xmin ) xmin = x;
if( y > ymax ) ymax = y;
if( y < ymin ) ymin = y;
}
std::cout << "x: " << xmin << ":" << xmax << std::endl;
std::cout << "y: " << ymin << ":" << ymax << std::endl;
if( refine )
{
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double a = (n->Coords()[0]-xmin)/(xmax-xmin);
if( refine == 1 )
a = sin(3.14159265359*a/2.0);
else if( refine == -1 )
a = 1 - sin(3.14159265359*(1-a)/2.0);
n->Coords()[0] = (xmax-xmin)*a + xmin;
}
}
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double x = n->Coords()[0], mx = x;
double y = n->Coords()[1], my = y;
double alpha = pi/4*(2*y-1);
double outer = - x*(1-cos(alpha)) + x*(cos(alpha)-1.0/sqrt(2.0))/(1-1.0/sqrt(2))*(1.0/sqrt(2.0)-0.5);
double inner = (1-x)*(cos(alpha)-1.0/sqrt(2))/(1-1.0/sqrt(2))*(1.0/sqrt(2.0)-0.5);
//~ double inner = (1-x)*(cos(alpha*4.0/6.0)-sqrt(3.0)/2.0)/(1-sqrt(3.0)/2.0)*(1.0/sqrt(2.0)-0.5);
//~ double inner = (1-x)*cos(2*alpha)*(1.0/sqrt(2.0)-0.5);
if( stype == 0 )
{
mx += 1 + outer;
//~ mx += 1 - x*(1-cos(alpha));
my += x*sin(alpha);
}
else if( stype == 1 )
{
mx += 1 + inner;
my += x*sin(alpha)*sqrt(2);
}
else if( stype == 2 )
{
mx += 1;
my += x*sin(alpha)*sqrt(2);
}
else if( stype == 3 )
{
mx += 1 + inner+outer;
my += x*sin(alpha);
}
n->Coords()[0] = (mx-0.5)*ct - (my-0.5)*st + 0.5;
n->Coords()[1] = (mx-0.5)*st + (my-0.5)*ct + 0.5;
}
xmin = 1.0e20, xmax = -1.0e20;
ymin = 1.0e20, ymax = -1.0e20;
for(Mesh::iteratorNode n = m.BeginNode(); n != m.EndNode(); ++n)
{
double x = n->Coords()[0];
double y = n->Coords()[1];
if( x > xmax ) xmax = x;
if( x < xmin ) xmin = x;
if( y > ymax ) ymax = y;
if( y < ymin ) ymin = y;
}
std::cout << "x: " << xmin << ":" << xmax << std::endl;
std::cout << "y: " << ymin << ":" << ymax << std::endl;
if( argc > 4 )
{
std::cout << "Save to " << argv[4] << std::endl;
m.Save(argv[4]);
}
else
{
std::cout << "Save to out.vtk" << std::endl;
m.Save("out.vtk");
}
return 0;
}
<|endoftext|> |
<commit_before>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include <iterator>
#include <algorithm>
#include <math.h>
#include "AdaptiveLayerHeights.h"
namespace cura
{
AdaptiveLayer::AdaptiveLayer(int layer_height)
{
this->layer_height = layer_height;
}
AdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)
{
// store the required parameters
this->mesh = mesh;
this->layer_height = layer_thickness;
this->initial_layer_height = initial_layer_thickness;
this->max_variation = static_cast<int>(variation);
this->step_size = static_cast<int>(step_size);
this->threshold = threshold;
// calculate the allowed layer heights from variation and step size
// note: the order is from thickest to thinnest height!
for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)
{
this->allowed_layer_heights.push_back(allowed_layer_height);
}
this->calculateMeshTriangleSlopes();
this->calculateLayers();
}
int AdaptiveLayerHeights::getLayerCount()
{
return this->layers.size();
}
std::vector<AdaptiveLayer>* AdaptiveLayerHeights::getLayers()
{
return &this->layers;
}
void AdaptiveLayerHeights::calculateLayers()
{
const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());
SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance("slicing_tolerance");
std::vector<int> triangles_of_interest;
int z_level = 0;
int previous_layer_height = 0;
// the first layer has it's own independent height set, so we always add that
z_level += this->initial_layer_height;
// compensate first layer thickness depending on slicing mode
if (slicing_tolerance == SlicingTolerance::MIDDLE)
{
z_level += this->initial_layer_height / 2;
this->initial_layer_height += this->initial_layer_height / 2;
}
auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
// loop while triangles are found
while (!triangles_of_interest.empty() || this->layers.size() < 2)
{
// loop over all allowed layer heights starting with the largest
for (auto & layer_height : this->allowed_layer_heights)
{
int lower_bound = z_level;
int upper_bound = z_level + layer_height;
std::vector<int> min_bounds;
std::vector<int> max_bounds;
// calculate all intersecting lower bounds
for (auto it_lower = this->face_min_z_values.begin(); it_lower != this->face_min_z_values.end(); ++it_lower)
{
if (*it_lower <= upper_bound)
{
min_bounds.emplace_back(std::distance(this->face_min_z_values.begin(), it_lower));
}
}
// calculate all intersecting upper bounds
for (auto it_upper = this->face_max_z_values.begin(); it_upper != this->face_max_z_values.end(); ++it_upper)
{
if (*it_upper >= lower_bound)
{
max_bounds.emplace_back(std::distance(this->face_max_z_values.begin(), it_upper));
}
}
// use lower and upper bounds to filter on triangles that are interesting for this potential layer
triangles_of_interest.clear();
std::set_intersection(min_bounds.begin(), min_bounds.end(), max_bounds.begin(), max_bounds.end(), std::back_inserter(triangles_of_interest));
// when there not interesting triangles in this potential layer go to the next one
if (triangles_of_interest.empty())
{
break;
}
std::vector<double> slopes;
// find all slopes for interesting triangles
for (auto & triangle_index : triangles_of_interest)
{
double slope = this->face_slopes.at(triangle_index);
slopes.push_back(slope);
}
double minimum_slope = *std::min_element(slopes.begin(), slopes.end());
double minimum_slope_tan = std::tan(minimum_slope);
// check if the maximum step size has been exceeded depending on layer height direction
bool has_exceeded_step_size = false;
if (previous_layer_height > layer_height && previous_layer_height - layer_height >= this->step_size)
{
has_exceeded_step_size = true;
}
else if (layer_height - previous_layer_height > this->step_size)
{
continue;
}
// we add the layer in the following cases:
// 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size
// 2) the layer height is the smallest it is allowed
// 3) the layer is a flat surface (we can't divide by 0)
if (minimum_slope_tan == 0.0
|| (layer_height / minimum_slope_tan) <= this->threshold
|| layer_height == minimum_layer_height
|| has_exceeded_step_size)
{
z_level += layer_height;
auto * adaptive_layer = new AdaptiveLayer(layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
break;
}
}
// stop calculating when we're out of triangles (e.g. above the mesh)
if (triangles_of_interest.empty())
{
break;
}
}
}
void AdaptiveLayerHeights::calculateMeshTriangleSlopes()
{
// loop over all mesh faces (triangles) and find their slopes
for (const auto &face : this->mesh->faces)
{
const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];
const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];
const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];
FPoint3 p0 = v0.p;
FPoint3 p1 = v1.p;
FPoint3 p2 = v2.p;
int32_t minZ = p0.z;
int32_t maxZ = p0.z;
if (p1.z < minZ) minZ = p1.z;
if (p2.z < minZ) minZ = p2.z;
if (p1.z > maxZ) maxZ = p1.z;
if (p2.z > maxZ) maxZ = p2.z;
// calculate the angle of this triangle in the z direction
FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);
FPoint3 normal = n.normalized();
double z_angle = std::acos(std::abs(normal.z));
// prevent flat surfaces from influencing the algorithm
if (z_angle == 0)
{
z_angle = M_PI;
}
this->face_min_z_values.push_back(minZ * 1000);
this->face_max_z_values.push_back(maxZ * 1000);
this->face_slopes.push_back(z_angle);
}
}
}<commit_msg>Use > rather than >= so that code matches comment.<commit_after>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include <iterator>
#include <algorithm>
#include <math.h>
#include "AdaptiveLayerHeights.h"
namespace cura
{
AdaptiveLayer::AdaptiveLayer(int layer_height)
{
this->layer_height = layer_height;
}
AdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)
{
// store the required parameters
this->mesh = mesh;
this->layer_height = layer_thickness;
this->initial_layer_height = initial_layer_thickness;
this->max_variation = static_cast<int>(variation);
this->step_size = static_cast<int>(step_size);
this->threshold = threshold;
// calculate the allowed layer heights from variation and step size
// note: the order is from thickest to thinnest height!
for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)
{
this->allowed_layer_heights.push_back(allowed_layer_height);
}
this->calculateMeshTriangleSlopes();
this->calculateLayers();
}
int AdaptiveLayerHeights::getLayerCount()
{
return this->layers.size();
}
std::vector<AdaptiveLayer>* AdaptiveLayerHeights::getLayers()
{
return &this->layers;
}
void AdaptiveLayerHeights::calculateLayers()
{
const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());
SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance("slicing_tolerance");
std::vector<int> triangles_of_interest;
int z_level = 0;
int previous_layer_height = 0;
// the first layer has it's own independent height set, so we always add that
z_level += this->initial_layer_height;
// compensate first layer thickness depending on slicing mode
if (slicing_tolerance == SlicingTolerance::MIDDLE)
{
z_level += this->initial_layer_height / 2;
this->initial_layer_height += this->initial_layer_height / 2;
}
auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
// loop while triangles are found
while (!triangles_of_interest.empty() || this->layers.size() < 2)
{
// loop over all allowed layer heights starting with the largest
for (auto & layer_height : this->allowed_layer_heights)
{
int lower_bound = z_level;
int upper_bound = z_level + layer_height;
std::vector<int> min_bounds;
std::vector<int> max_bounds;
// calculate all intersecting lower bounds
for (auto it_lower = this->face_min_z_values.begin(); it_lower != this->face_min_z_values.end(); ++it_lower)
{
if (*it_lower <= upper_bound)
{
min_bounds.emplace_back(std::distance(this->face_min_z_values.begin(), it_lower));
}
}
// calculate all intersecting upper bounds
for (auto it_upper = this->face_max_z_values.begin(); it_upper != this->face_max_z_values.end(); ++it_upper)
{
if (*it_upper >= lower_bound)
{
max_bounds.emplace_back(std::distance(this->face_max_z_values.begin(), it_upper));
}
}
// use lower and upper bounds to filter on triangles that are interesting for this potential layer
triangles_of_interest.clear();
std::set_intersection(min_bounds.begin(), min_bounds.end(), max_bounds.begin(), max_bounds.end(), std::back_inserter(triangles_of_interest));
// when there not interesting triangles in this potential layer go to the next one
if (triangles_of_interest.empty())
{
break;
}
std::vector<double> slopes;
// find all slopes for interesting triangles
for (auto & triangle_index : triangles_of_interest)
{
double slope = this->face_slopes.at(triangle_index);
slopes.push_back(slope);
}
double minimum_slope = *std::min_element(slopes.begin(), slopes.end());
double minimum_slope_tan = std::tan(minimum_slope);
// check if the maximum step size has been exceeded depending on layer height direction
bool has_exceeded_step_size = false;
if (previous_layer_height > layer_height && previous_layer_height - layer_height > this->step_size)
{
has_exceeded_step_size = true;
}
else if (layer_height - previous_layer_height > this->step_size)
{
continue;
}
// we add the layer in the following cases:
// 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size
// 2) the layer height is the smallest it is allowed
// 3) the layer is a flat surface (we can't divide by 0)
if (minimum_slope_tan == 0.0
|| (layer_height / minimum_slope_tan) <= this->threshold
|| layer_height == minimum_layer_height
|| has_exceeded_step_size)
{
z_level += layer_height;
auto * adaptive_layer = new AdaptiveLayer(layer_height);
adaptive_layer->z_position = z_level;
previous_layer_height = adaptive_layer->layer_height;
this->layers.push_back(*adaptive_layer);
break;
}
}
// stop calculating when we're out of triangles (e.g. above the mesh)
if (triangles_of_interest.empty())
{
break;
}
}
}
void AdaptiveLayerHeights::calculateMeshTriangleSlopes()
{
// loop over all mesh faces (triangles) and find their slopes
for (const auto &face : this->mesh->faces)
{
const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];
const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];
const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];
FPoint3 p0 = v0.p;
FPoint3 p1 = v1.p;
FPoint3 p2 = v2.p;
int32_t minZ = p0.z;
int32_t maxZ = p0.z;
if (p1.z < minZ) minZ = p1.z;
if (p2.z < minZ) minZ = p2.z;
if (p1.z > maxZ) maxZ = p1.z;
if (p2.z > maxZ) maxZ = p2.z;
// calculate the angle of this triangle in the z direction
FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);
FPoint3 normal = n.normalized();
double z_angle = std::acos(std::abs(normal.z));
// prevent flat surfaces from influencing the algorithm
if (z_angle == 0)
{
z_angle = M_PI;
}
this->face_min_z_values.push_back(minZ * 1000);
this->face_max_z_values.push_back(maxZ * 1000);
this->face_slopes.push_back(z_angle);
}
}
}<|endoftext|> |
<commit_before>
// Copyright (c) 2012, 2013, 2014, 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/sfm.hpp"
#include "software/SfM/io_readGT.hpp"
#include "software/SfM/tools_precisionEvaluationToGt.hpp"
#include "software/SfM/SfMPlyHelper.hpp"
#include "third_party/htmlDoc/htmlDoc.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <cstdlib>
using namespace openMVG;
using namespace openMVG::sfm;
int main(int argc, char **argv)
{
using namespace std;
CmdLine cmd;
std::string
sGTDirectory,
sComputedDirectory,
sOutDir = "";
int camType = -1; //1: openMVG cam, 2,3: Strechas cam
cmd.add( make_option('i', sGTDirectory, "gt") );
cmd.add( make_option('c', sComputedDirectory, "computed") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('t', camType, "camtype") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--gt] path (where ground truth camera trajectory are saved)\n"
<< "[-c|--computed] path (openMVG SfM_Output directory)\n"
<< "[-o|--output] path (where statistics will be saved)\n"
<< "[-t|--camtype] Type of the camera:\n"
<< " -1: autoguess (try 1,2,3),\n"
<< " 1: openMVG (bin),\n"
<< " 2: Strechas 'png.camera' \n"
<< " 3: Strechas 'jpg.camera' ]\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty()) {
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
stlplus::folder_create(sOutDir);
//Setup the camera type and the appropriate camera reader
bool (*fcnReadCamPtr)(const std::string&, Pinhole_Intrinsic&, geometry::Pose3&);
std::string suffix;
switch (camType)
{
case -1: // handle auto guess
{
if (!stlplus::folder_wildcard(sGTDirectory, "*.bin", false, true).empty())
camType = 1;
else if (!stlplus::folder_wildcard(sGTDirectory, "*.png.camera", false, true).empty())
camType = 2;
else if (!stlplus::folder_wildcard(sGTDirectory, "*.jpg.camera", false, true).empty())
camType = 3;
else
camType = std::numeric_limits<int>::infinity();
}
break;
}
switch (camType)
{
case 1:
std::cout << "\nusing openMVG Camera";
fcnReadCamPtr = &read_openMVG_Camera;
suffix = "bin";
break;
case 2:
case 3:
std::cout << "\nusing Strechas Camera";
fcnReadCamPtr = &read_Strecha_Camera;
suffix = (camType == 2) ? "png.camera" : "jpg.camera";
break;
default:
std::cerr << "Unsupported camera type. Please write your camera reader." << std::endl;
return EXIT_FAILURE;
}
//---------------------------------------
// Quality evaluation
//---------------------------------------
//-- Load GT camera rotations & positions [R|C]:
SfM_Data sfm_data_gt;
// READ DATA FROM GT
{
std::cout << "\nTry to read data from GT";
std::vector<std::string> vec_fileNames;
readGt(fcnReadCamPtr, sGTDirectory, suffix, vec_fileNames, sfm_data_gt.poses, sfm_data_gt.intrinsics);
std::cout << sfm_data_gt.poses.size() << " gt cameras have been found" << std::endl;
}
//-- Load the camera that we have to evaluate
SfM_Data sfm_data;
if (!Load(sfm_data, sComputedDirectory, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS)))
{
std::cerr << std::endl
<< "The input SfM_Data file \""<< sComputedDirectory << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
// Assert that GT and loaded scene have the same camera count
if (sfm_data_gt.poses.size() != sfm_data.GetPoses().size())
{
std::cerr << std::endl
<< "There is missing camera in the loaded scene." << std::endl;
return EXIT_FAILURE;
}
// Prepare data for comparison (corresponding camera centers and rotations)
Poses::const_iterator iter_poses_eval = sfm_data.GetPoses().begin();
Poses::const_iterator iter_poses_gt = sfm_data_gt.GetPoses().begin();
std::vector<Vec3> vec_camPosGT, vec_C;
std::vector<Mat3> vec_camRotGT, vec_camRot;
for(; iter_poses_gt != sfm_data_gt.GetPoses().end(); ++iter_poses_gt, ++iter_poses_eval)
{
//-- GT
const geometry::Pose3& pose_gt = iter_poses_gt->second;
vec_camPosGT.push_back(pose_gt.center());
vec_camRotGT.push_back(pose_gt.rotation());
//-- Data to evaluate
const geometry::Pose3& pose_eval = iter_poses_eval->second;
vec_C.push_back(pose_eval.center());
vec_camRot.push_back(pose_eval.rotation());
}
// Visual output of the camera location
plyHelper::exportToPly(vec_camPosGT, string(stlplus::folder_append_separator(sOutDir) + "camGT.ply").c_str());
plyHelper::exportToPly(vec_C, string(stlplus::folder_append_separator(sOutDir) + "camComputed.ply").c_str());
// Evaluation
htmlDocument::htmlDocumentStream _htmlDocStream("openMVG Quality evaluation.");
EvaluteToGT(vec_camPosGT, vec_C, vec_camRotGT, vec_camRot, sOutDir, &_htmlDocStream);
ofstream htmlFileStream( string(stlplus::folder_append_separator(sOutDir) +
"ExternalCalib_Report.html").c_str());
htmlFileStream << _htmlDocStream.getDoc();
return EXIT_SUCCESS;
}
<commit_msg>[gt_tests] handle bug if file extensions are maj<commit_after>
// Copyright (c) 2012, 2013, 2014, 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/sfm.hpp"
#include "software/SfM/io_readGT.hpp"
#include "software/SfM/tools_precisionEvaluationToGt.hpp"
#include "software/SfM/SfMPlyHelper.hpp"
#include "third_party/htmlDoc/htmlDoc.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <cstdlib>
using namespace openMVG;
using namespace openMVG::sfm;
int main(int argc, char **argv)
{
using namespace std;
CmdLine cmd;
std::string
sGTDirectory,
sComputedDirectory,
sOutDir = "";
int camType = -1; //1: openMVG cam, 2,3: Strechas cam
cmd.add( make_option('i', sGTDirectory, "gt") );
cmd.add( make_option('c', sComputedDirectory, "computed") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('t', camType, "camtype") );
try {
if (argc == 1) throw std::string("Invalid command line parameter.");
cmd.process(argc, argv);
} catch(const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--gt] path (where ground truth camera trajectory are saved)\n"
<< "[-c|--computed] path (openMVG SfM_Output directory)\n"
<< "[-o|--output] path (where statistics will be saved)\n"
<< "[-t|--camtype] Type of the camera:\n"
<< " -1: autoguess (try 1,2,3),\n"
<< " 1: openMVG (bin),\n"
<< " 2: Strechas 'png.camera' \n"
<< " 3: Strechas 'jpg.camera' ]\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty()) {
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
stlplus::folder_create(sOutDir);
//Setup the camera type and the appropriate camera reader
bool (*fcnReadCamPtr)(const std::string&, Pinhole_Intrinsic&, geometry::Pose3&);
std::string suffix;
switch (camType)
{
case -1: // handle auto guess
{
if (!stlplus::folder_wildcard(sGTDirectory, "*.bin", false, true).empty())
camType = 1;
else if (!stlplus::folder_wildcard(sGTDirectory, "*.png.camera", false, true).empty())
camType = 2;
else if (!stlplus::folder_wildcard(sGTDirectory, "*.jpg.camera", false, true).empty())
camType = 3;
else if (!stlplus::folder_wildcard(sGTDirectory, "*.PNG.camera", false, true).empty())
camType = 4;
else if (!stlplus::folder_wildcard(sGTDirectory, "*.JPG.camera", false, true).empty())
camType = 5;
else
camType = std::numeric_limits<int>::infinity();
}
break;
}
switch (camType)
{
case 1:
std::cout << "\nusing openMVG Camera";
fcnReadCamPtr = &read_openMVG_Camera;
suffix = "bin";
break;
case 2:
std::cout << "\nusing Strechas Camera (png)";
fcnReadCamPtr = &read_Strecha_Camera;
suffix = "png.camera";
break;
case 3:
std::cout << "\nusing Strechas Camera (jpg)";
fcnReadCamPtr = &read_Strecha_Camera;
suffix = "jpg.camera";
break;
case 4:
std::cout << "\nusing Strechas Camera (PNG)";
fcnReadCamPtr = &read_Strecha_Camera;
suffix = "PNG.camera";
break;
case 5:
std::cout << "\nusing Strechas Camera (JPG)";
fcnReadCamPtr = &read_Strecha_Camera;
suffix = "JPG.camera";
break;
default:
std::cerr << "Unsupported camera type. Please write your camera reader." << std::endl;
return EXIT_FAILURE;
}
//---------------------------------------
// Quality evaluation
//---------------------------------------
//-- Load GT camera rotations & positions [R|C]:
SfM_Data sfm_data_gt;
// READ DATA FROM GT
{
std::cout << "\nTry to read data from GT";
std::vector<std::string> vec_fileNames;
readGt(fcnReadCamPtr, sGTDirectory, suffix, vec_fileNames, sfm_data_gt.poses, sfm_data_gt.intrinsics);
std::cout << sfm_data_gt.poses.size() << " gt cameras have been found" << std::endl;
}
//-- Load the camera that we have to evaluate
SfM_Data sfm_data;
if (!Load(sfm_data, sComputedDirectory, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS)))
{
std::cerr << std::endl
<< "The input SfM_Data file \""<< sComputedDirectory << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
// Assert that GT and loaded scene have the same camera count
if (sfm_data_gt.poses.size() != sfm_data.GetPoses().size())
{
std::cerr << std::endl
<< "There is missing camera in the loaded scene." << std::endl;
return EXIT_FAILURE;
}
// Prepare data for comparison (corresponding camera centers and rotations)
Poses::const_iterator iter_poses_eval = sfm_data.GetPoses().begin();
Poses::const_iterator iter_poses_gt = sfm_data_gt.GetPoses().begin();
std::vector<Vec3> vec_camPosGT, vec_C;
std::vector<Mat3> vec_camRotGT, vec_camRot;
for(; iter_poses_gt != sfm_data_gt.GetPoses().end(); ++iter_poses_gt, ++iter_poses_eval)
{
//-- GT
const geometry::Pose3& pose_gt = iter_poses_gt->second;
vec_camPosGT.push_back(pose_gt.center());
vec_camRotGT.push_back(pose_gt.rotation());
//-- Data to evaluate
const geometry::Pose3& pose_eval = iter_poses_eval->second;
vec_C.push_back(pose_eval.center());
vec_camRot.push_back(pose_eval.rotation());
}
// Visual output of the camera location
plyHelper::exportToPly(vec_camPosGT, string(stlplus::folder_append_separator(sOutDir) + "camGT.ply").c_str());
plyHelper::exportToPly(vec_C, string(stlplus::folder_append_separator(sOutDir) + "camComputed.ply").c_str());
// Evaluation
htmlDocument::htmlDocumentStream _htmlDocStream("openMVG Quality evaluation.");
EvaluteToGT(vec_camPosGT, vec_C, vec_camRotGT, vec_camRot, sOutDir, &_htmlDocStream);
ofstream htmlFileStream( string(stlplus::folder_append_separator(sOutDir) +
"ExternalCalib_Report.html").c_str());
htmlFileStream << _htmlDocStream.getDoc();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(1)
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy = ListNode(0);
auto *curr = &dummy;
while (l1 && l2) {
if (l1->val <= l2->val) {
curr->next = l1;
l1 = l1->next;
} else {
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
curr->next = l1 ? l1 : l2;
return dummy.next;
}
};
<commit_msg>Update merge-two-sorted-lists.cpp<commit_after>// Time: O(n)
// Space: O(1)
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy = ListNode(0);
auto *curr = &dummy;
while (l1 && l2) {
if (l1->val <= l2->val) {
curr->next = l1;
l1 = l1->next;
} else {
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
curr->next = l1 ? l1 : l2;
return dummy.next;
}
};
<|endoftext|> |
<commit_before>#ifndef __STAN__MATH__MATRIX__SORT_INDICES_HPP__
#define __STAN__MATH__MATRIX__SORT_INDICES_HPP__
#include <stan/math/matrix/Eigen.hpp>
#include <vector>
#include <algorithm> // std::sort
namespace stan {
namespace math {
namespace {
struct svector_asc {
template <typename T> bool operator() (std::pair <T, int> i,
std::pair <T, int> j) {
if (i.first!=j.first)
return (i.first < j.first);
else
return (i.second < j.second);
}
} vector_asc;
struct svector_desc {
template <typename T> bool operator() (std::pair <T, int> i,
std::pair <T, int> j) {
if (i.first!=j.first)
return (i.first > j.first);
else
return (i.second > j.second);
}
} vector_desc;
}
template <typename T>
inline std::vector<int> sort_indices_asc(std::vector<T> xs) {
size_t size = xs.size();
if (size < 2) {
if (size == 1)
return std::vector<int>(1, 1);
else
return std::vector<int>();
}
std::vector<std::pair <T, int> > vector_pairs(size);
for (size_t i=0; i != size; i++)
vector_pairs[i] = std::pair <T, int>(xs[i], i+1);
std::sort(vector_pairs.begin(), vector_pairs.end(), vector_asc);
std::vector<int> results(size);
for (size_t i=0; i != size; i++)
results[i] = vector_pairs[i].second;
return results;
}
template <typename T>
inline std::vector<int> sort_indices_desc(std::vector<T> xs) {
size_t size = xs.size();
if (size < 2) {
if (size == 1)
return std::vector<int>(1, 1);
else
return std::vector<int>();
}
std::vector<std::pair <T, int> > vector_pairs(size);
for (size_t i=0; i < size; i++)
vector_pairs[i] = std::pair <T, int>(xs[i], i+1);
std::sort(vector_pairs.begin(), vector_pairs.end(), vector_desc);
std::vector<int> results(size);
for (size_t i=0; i < size; i++)
results[i] = vector_pairs[i].second;
return results;
}
template <typename T, int R, int C>
inline std::vector<int> sort_indices_asc(Eigen::Matrix<T, R, C> xs) {
ptrdiff_t size = xs.size();
if (size < 2) {
if (size == 1)
return std::vector<int>(1, 1);
else
return std::vector<int>();
}
std::vector<std::pair <T, int> > vector_pairs(size);
T* data = xs.data();
for (ptrdiff_t i = 0; i < size; i++)
vector_pairs[i] = std::pair <T, int>(data[i], i+1);
std::sort(vector_pairs.begin(), vector_pairs.end(), vector_asc);
std::vector<int> results(size);
for (size_t i = 0; i < size; i++)
results[i] = vector_pairs[i].second;
return results;
}
template <typename T, int R, int C>
inline std::vector<int> sort_indices_desc(Eigen::Matrix<T, R, C> xs) {
ptrdiff_t size = xs.size();
if (size < 2) {
if (size == 1)
return std::vector<int>(1, 1);
else
return std::vector<int>();
}
std::vector<std::pair <T, int> > vector_pairs(size);
T* data = xs.data();
for (ptrdiff_t i = 0; i < size; i++)
vector_pairs[i] = std::pair <T, int>(data[i], i+1);
std::sort(vector_pairs.begin(), vector_pairs.end(), vector_desc);
std::vector<int> results(size);
for (size_t i=0; i < size; i++)
results[i] = vector_pairs[i].second;
return results;
}
}
}
#endif
<commit_msg>refactor of sort_indices_* functions based on Bob Carpenter's https://github.com/stan-dev/stan/pull/564#issuecomment-35143532<commit_after>#ifndef __STAN__MATH__MATRIX__SORT_INDICES_HPP__
#define __STAN__MATH__MATRIX__SORT_INDICES_HPP__
#include <stan/math/matrix/Eigen.hpp>
#include <vector>
#include <algorithm> // std::sort
#include <iostream>
namespace stan {
namespace math {
namespace {
template <bool ascending, typename T>
class index_comparator_stdvector {
const std::vector<T>& xs_;
public:
index_comparator_stdvector(const std::vector<T>& xs) : xs_(xs) { }
bool operator()(int i, int j) const {
if (ascending)
return xs_[i-1] < xs_[j-1];
else
return xs_[i-1] > xs_[j-1];
}
};
template <bool ascending, typename T>
std::vector<int> sort_indices(const std::vector<T>& xs) {
size_t size = xs.size();
std::vector<int> idxs(size);
for (int i = 0; i < size; ++i)
idxs[i] = i + 1;
index_comparator_stdvector<ascending,T> comparator(xs);
std::sort(idxs.begin(), idxs.end(),
comparator);
return idxs;
}
}
template <typename T>
std::vector<int> sort_indices_asc(const std::vector<T>& xs) {
return sort_indices<true>(xs);
}
template <typename T>
std::vector<int> sort_indices_desc(const std::vector<T>& xs) {
return sort_indices<false>(xs);
}
//Same as all above, but for eigen matrices
namespace {
template <bool ascending, int R, int C, typename T>
class index_comparator_eigen {
const Eigen::Matrix<T, R, C>& xs_;
public:
index_comparator_eigen(const Eigen::Matrix<T, R, C>& xs) : xs_(xs) { }
bool operator()(int i, int j) const {
if (ascending)
return xs_[i-1] < xs_[j-1];
else
return xs_[i-1] > xs_[j-1];
}
};
template <bool ascending, int R, int C, typename T>
std::vector<int> sort_indices(const Eigen::Matrix<T, R, C>& xs) {
size_t size = xs.size();
std::vector<int> idxs(size);
for (int i = 0; i < size; ++i)
idxs[i] = i + 1;
index_comparator_eigen<ascending, R, C, T> comparator(xs);
std::sort(idxs.begin(), idxs.end(),
comparator);
return idxs;
}
}
template <typename T, int R, int C>
std::vector<int> sort_indices_asc(const Eigen::Matrix<T, R, C>& xs) {
return sort_indices<true, R, C>(xs);
}
template <typename T, int R, int C>
std::vector<int> sort_indices_desc(const Eigen::Matrix<T, R, C>& xs) {
return sort_indices<false, R, C>(xs);
}
}
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
#include "Media.h"
#include "database/SqliteTools.h"
const std::string policy::AlbumTable::Name = "Album";
const std::string policy::AlbumTable::CacheColumn = "id_album";
unsigned int Album::* const policy::AlbumTable::PrimaryKey = &Album::m_id;
Album::Album(DBConnection dbConnection, sqlite::Row& row)
: m_dbConnection( dbConnection )
, m_tracksCached( false )
{
row >> m_id
>> m_title
>> m_artistId
>> m_releaseYear
>> m_shortSummary
>> m_artworkUrl
>> m_lastSyncDate
>> m_nbTracks;
}
Album::Album(const std::string& title )
: m_id( 0 )
, m_title( title )
, m_artistId( 0 )
, m_releaseYear( ~0u )
, m_lastSyncDate( 0 )
, m_nbTracks( 0 )
, m_tracksCached( false )
{
}
Album::Album( const Artist* artist )
: m_id( 0 )
, m_artistId( artist->id() )
, m_releaseYear( ~0u )
, m_lastSyncDate( 0 )
, m_nbTracks( 0 )
, m_tracksCached( false )
{
}
unsigned int Album::id() const
{
return m_id;
}
const std::string& Album::title() const
{
return m_title;
}
unsigned int Album::releaseYear() const
{
if ( m_releaseYear == ~0U )
return 0;
return m_releaseYear;
}
bool Album::setReleaseYear( unsigned int date, bool force )
{
if ( date == m_releaseYear )
return true;
if ( force == false )
{
if ( m_releaseYear != ~0u && date != m_releaseYear )
{
// If we already have set the date back to 0, don't do it again.
if ( m_releaseYear == 0 )
return true;
date = 0;
}
}
static const std::string req = "UPDATE " + policy::AlbumTable::Name
+ " SET release_year = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, date, m_id ) == false )
return false;
m_releaseYear = date;
return true;
}
const std::string& Album::shortSummary() const
{
return m_shortSummary;
}
bool Album::setShortSummary( const std::string& summary )
{
static const std::string& req = "UPDATE " + policy::AlbumTable::Name
+ " SET short_summary = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, summary, m_id ) == false )
return false;
m_shortSummary = summary;
return true;
}
const std::string& Album::artworkUrl() const
{
return m_artworkUrl;
}
bool Album::setArtworkUrl( const std::string& artworkUrl )
{
static const std::string& req = "UPDATE " + policy::AlbumTable::Name
+ " SET artwork_url = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artworkUrl, m_id ) == false )
return false;
m_artworkUrl = artworkUrl;
return true;
}
time_t Album::lastSyncDate() const
{
return m_lastSyncDate;
}
std::vector<MediaPtr> Album::tracks() const
{
std::lock_guard<std::mutex> lock( m_tracksLock );
if ( m_tracksCached == true )
return m_tracks;
static const std::string req = "SELECT med.* FROM " + policy::MediaTable::Name + " med "
" LEFT JOIN " + policy::AlbumTrackTable::Name + " att ON att.media_id = med.id_media "
" WHERE att.album_id = ? ORDER BY att.track_number";
m_tracks = Media::fetchAll( m_dbConnection, req, m_id );
m_tracksCached = true;
return m_tracks;
}
std::shared_ptr<AlbumTrack> Album::addTrack(std::shared_ptr<Media> media, unsigned int trackNb )
{
//FIXME: This MUST be executed as a transaction
auto track = AlbumTrack::create( m_dbConnection, m_id, media.get(), trackNb );
if ( track == nullptr )
return nullptr;
if ( media->setAlbumTrack( track ) == false )
return nullptr;
static const std::string req = "UPDATE " + policy::AlbumTable::Name +
" SET nb_tracks = nb_tracks + 1 WHERE id_album = ?";
std::lock_guard<std::mutex> lock( m_tracksLock );
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, m_id ) == false )
return nullptr;
m_nbTracks++;
m_tracks.push_back( std::move( media ) );
m_tracksCached = true;
return track;
}
unsigned int Album::nbTracks() const
{
return m_nbTracks;
}
ArtistPtr Album::albumArtist() const
{
if ( m_artistId == 0 )
return nullptr;
return Artist::fetch( m_dbConnection, m_artistId );
}
bool Album::setAlbumArtist(Artist* artist)
{
if ( m_artistId == artist->id() )
return true;
if ( artist->id() == 0 )
return false;
static const std::string req = "UPDATE " + policy::AlbumTable::Name + " SET "
"artist_id = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artist->id(), m_id ) == false )
return false;
if ( m_artistId != 0 )
{
auto previousArtist = Artist::fetch( m_dbConnection, m_artistId );
previousArtist->updateNbAlbum( -1 );
}
m_artistId = artist->id();
artist->updateNbAlbum( 1 );
return true;
}
std::vector<ArtistPtr> Album::artists() const
{
static const std::string req = "SELECT art.* FROM " + policy::ArtistTable::Name + " art "
"LEFT JOIN AlbumArtistRelation aar ON aar.id_artist = art.id_artist "
"WHERE aar.id_album = ?";
return Artist::fetchAll( m_dbConnection, req, m_id );
}
bool Album::addArtist( std::shared_ptr<Artist> artist )
{
static const std::string req = "INSERT OR IGNORE INTO AlbumArtistRelation VALUES(?, ?)";
if ( m_id == 0 || artist->id() == 0 )
{
LOG_ERROR("Both artist & album need to be inserted in database before being linked together" );
return false;
}
return sqlite::Tools::executeRequest( m_dbConnection, req, m_id, artist->id() );
}
bool Album::removeArtist(Artist* artist)
{
static const std::string req = "DELETE FROM AlbumArtistRelation WHERE id_album = ? "
"AND id_artist = ?";
return sqlite::Tools::executeDelete( m_dbConnection, req, m_id, artist->id() );
}
bool Album::createTable(DBConnection dbConnection )
{
static const std::string req = "CREATE TABLE IF NOT EXISTS " +
policy::AlbumTable::Name +
"("
"id_album INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT,"
"artist_id UNSIGNED INTEGER,"
"release_year UNSIGNED INTEGER,"
"short_summary TEXT,"
"artwork_url TEXT,"
"last_sync_date UNSIGNED INTEGER,"
"nb_tracks UNSIGNED INTEGER DEFAULT 0"
")";
static const std::string reqRel = "CREATE TABLE IF NOT EXISTS AlbumArtistRelation("
"id_album INTEGER,"
"id_artist INTEGER,"
"PRIMARY KEY (id_album, id_artist),"
"FOREIGN KEY(id_album) REFERENCES " + policy::AlbumTable::Name + "("
+ policy::AlbumTable::CacheColumn + ") ON DELETE CASCADE,"
"FOREIGN KEY(id_artist) REFERENCES " + policy::ArtistTable::Name + "("
+ policy::ArtistTable::CacheColumn + ") ON DELETE CASCADE"
")";
return sqlite::Tools::executeRequest( dbConnection, req ) &&
sqlite::Tools::executeRequest( dbConnection, reqRel );
}
std::shared_ptr<Album> Album::create(DBConnection dbConnection, const std::string& title )
{
auto album = std::make_shared<Album>( title );
static const std::string req = "INSERT INTO " + policy::AlbumTable::Name +
"(id_album, title) VALUES(NULL, ?)";
if ( _Cache::insert( dbConnection, album, req, title ) == false )
return nullptr;
album->m_dbConnection = dbConnection;
return album;
}
std::shared_ptr<Album> Album::createUnknownAlbum( DBConnection dbConnection, const Artist* artist )
{
auto album = std::make_shared<Album>( artist );
static const std::string req = "INSERT INTO " + policy::AlbumTable::Name +
"(id_album, artist_id) VALUES(NULL, ?)";
if ( _Cache::insert( dbConnection, album, req, artist->id() ) == false )
return nullptr;
album->m_dbConnection = dbConnection;
return album;
}
<commit_msg>Album: Don't mess up tracks ordering when filling the cache<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program 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 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include <algorithm>
#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
#include "Media.h"
#include "database/SqliteTools.h"
const std::string policy::AlbumTable::Name = "Album";
const std::string policy::AlbumTable::CacheColumn = "id_album";
unsigned int Album::* const policy::AlbumTable::PrimaryKey = &Album::m_id;
Album::Album(DBConnection dbConnection, sqlite::Row& row)
: m_dbConnection( dbConnection )
, m_tracksCached( false )
{
row >> m_id
>> m_title
>> m_artistId
>> m_releaseYear
>> m_shortSummary
>> m_artworkUrl
>> m_lastSyncDate
>> m_nbTracks;
}
Album::Album(const std::string& title )
: m_id( 0 )
, m_title( title )
, m_artistId( 0 )
, m_releaseYear( ~0u )
, m_lastSyncDate( 0 )
, m_nbTracks( 0 )
, m_tracksCached( false )
{
}
Album::Album( const Artist* artist )
: m_id( 0 )
, m_artistId( artist->id() )
, m_releaseYear( ~0u )
, m_lastSyncDate( 0 )
, m_nbTracks( 0 )
, m_tracksCached( false )
{
}
unsigned int Album::id() const
{
return m_id;
}
const std::string& Album::title() const
{
return m_title;
}
unsigned int Album::releaseYear() const
{
if ( m_releaseYear == ~0U )
return 0;
return m_releaseYear;
}
bool Album::setReleaseYear( unsigned int date, bool force )
{
if ( date == m_releaseYear )
return true;
if ( force == false )
{
if ( m_releaseYear != ~0u && date != m_releaseYear )
{
// If we already have set the date back to 0, don't do it again.
if ( m_releaseYear == 0 )
return true;
date = 0;
}
}
static const std::string req = "UPDATE " + policy::AlbumTable::Name
+ " SET release_year = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, date, m_id ) == false )
return false;
m_releaseYear = date;
return true;
}
const std::string& Album::shortSummary() const
{
return m_shortSummary;
}
bool Album::setShortSummary( const std::string& summary )
{
static const std::string& req = "UPDATE " + policy::AlbumTable::Name
+ " SET short_summary = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, summary, m_id ) == false )
return false;
m_shortSummary = summary;
return true;
}
const std::string& Album::artworkUrl() const
{
return m_artworkUrl;
}
bool Album::setArtworkUrl( const std::string& artworkUrl )
{
static const std::string& req = "UPDATE " + policy::AlbumTable::Name
+ " SET artwork_url = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artworkUrl, m_id ) == false )
return false;
m_artworkUrl = artworkUrl;
return true;
}
time_t Album::lastSyncDate() const
{
return m_lastSyncDate;
}
std::vector<MediaPtr> Album::tracks() const
{
std::lock_guard<std::mutex> lock( m_tracksLock );
if ( m_tracksCached == true )
return m_tracks;
static const std::string req = "SELECT med.* FROM " + policy::MediaTable::Name + " med "
" LEFT JOIN " + policy::AlbumTrackTable::Name + " att ON att.media_id = med.id_media "
" WHERE att.album_id = ? ORDER BY att.track_number";
m_tracks = Media::fetchAll( m_dbConnection, req, m_id );
m_tracksCached = true;
return m_tracks;
}
std::shared_ptr<AlbumTrack> Album::addTrack(std::shared_ptr<Media> media, unsigned int trackNb )
{
//FIXME: This MUST be executed as a transaction
auto track = AlbumTrack::create( m_dbConnection, m_id, media.get(), trackNb );
if ( track == nullptr )
return nullptr;
if ( media->setAlbumTrack( track ) == false )
return nullptr;
static const std::string req = "UPDATE " + policy::AlbumTable::Name +
" SET nb_tracks = nb_tracks + 1 WHERE id_album = ?";
std::lock_guard<std::mutex> lock( m_tracksLock );
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, m_id ) == false )
return nullptr;
m_nbTracks++;
m_tracks.push_back( std::move( media ) );
std::sort( begin( m_tracks ), end( m_tracks ), [](const MediaPtr& a, const MediaPtr& b) {
return a->albumTrack()->trackNumber() < b->albumTrack()->trackNumber();
});
m_tracksCached = true;
return track;
}
unsigned int Album::nbTracks() const
{
return m_nbTracks;
}
ArtistPtr Album::albumArtist() const
{
if ( m_artistId == 0 )
return nullptr;
return Artist::fetch( m_dbConnection, m_artistId );
}
bool Album::setAlbumArtist(Artist* artist)
{
if ( m_artistId == artist->id() )
return true;
if ( artist->id() == 0 )
return false;
static const std::string req = "UPDATE " + policy::AlbumTable::Name + " SET "
"artist_id = ? WHERE id_album = ?";
if ( sqlite::Tools::executeUpdate( m_dbConnection, req, artist->id(), m_id ) == false )
return false;
if ( m_artistId != 0 )
{
auto previousArtist = Artist::fetch( m_dbConnection, m_artistId );
previousArtist->updateNbAlbum( -1 );
}
m_artistId = artist->id();
artist->updateNbAlbum( 1 );
return true;
}
std::vector<ArtistPtr> Album::artists() const
{
static const std::string req = "SELECT art.* FROM " + policy::ArtistTable::Name + " art "
"LEFT JOIN AlbumArtistRelation aar ON aar.id_artist = art.id_artist "
"WHERE aar.id_album = ?";
return Artist::fetchAll( m_dbConnection, req, m_id );
}
bool Album::addArtist( std::shared_ptr<Artist> artist )
{
static const std::string req = "INSERT OR IGNORE INTO AlbumArtistRelation VALUES(?, ?)";
if ( m_id == 0 || artist->id() == 0 )
{
LOG_ERROR("Both artist & album need to be inserted in database before being linked together" );
return false;
}
return sqlite::Tools::executeRequest( m_dbConnection, req, m_id, artist->id() );
}
bool Album::removeArtist(Artist* artist)
{
static const std::string req = "DELETE FROM AlbumArtistRelation WHERE id_album = ? "
"AND id_artist = ?";
return sqlite::Tools::executeDelete( m_dbConnection, req, m_id, artist->id() );
}
bool Album::createTable(DBConnection dbConnection )
{
static const std::string req = "CREATE TABLE IF NOT EXISTS " +
policy::AlbumTable::Name +
"("
"id_album INTEGER PRIMARY KEY AUTOINCREMENT,"
"title TEXT,"
"artist_id UNSIGNED INTEGER,"
"release_year UNSIGNED INTEGER,"
"short_summary TEXT,"
"artwork_url TEXT,"
"last_sync_date UNSIGNED INTEGER,"
"nb_tracks UNSIGNED INTEGER DEFAULT 0"
")";
static const std::string reqRel = "CREATE TABLE IF NOT EXISTS AlbumArtistRelation("
"id_album INTEGER,"
"id_artist INTEGER,"
"PRIMARY KEY (id_album, id_artist),"
"FOREIGN KEY(id_album) REFERENCES " + policy::AlbumTable::Name + "("
+ policy::AlbumTable::CacheColumn + ") ON DELETE CASCADE,"
"FOREIGN KEY(id_artist) REFERENCES " + policy::ArtistTable::Name + "("
+ policy::ArtistTable::CacheColumn + ") ON DELETE CASCADE"
")";
return sqlite::Tools::executeRequest( dbConnection, req ) &&
sqlite::Tools::executeRequest( dbConnection, reqRel );
}
std::shared_ptr<Album> Album::create(DBConnection dbConnection, const std::string& title )
{
auto album = std::make_shared<Album>( title );
static const std::string req = "INSERT INTO " + policy::AlbumTable::Name +
"(id_album, title) VALUES(NULL, ?)";
if ( _Cache::insert( dbConnection, album, req, title ) == false )
return nullptr;
album->m_dbConnection = dbConnection;
return album;
}
std::shared_ptr<Album> Album::createUnknownAlbum( DBConnection dbConnection, const Artist* artist )
{
auto album = std::make_shared<Album>( artist );
static const std::string req = "INSERT INTO " + policy::AlbumTable::Name +
"(id_album, artist_id) VALUES(NULL, ?)";
if ( _Cache::insert( dbConnection, album, req, artist->id() ) == false )
return nullptr;
album->m_dbConnection = dbConnection;
return album;
}
<|endoftext|> |
<commit_before>// Simple OCR program
// Copyright (C) 2014 vhb
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <Brain.hpp>
#include <utility>
#include <Image.hpp>
namespace ocr {
Brain::Brain(std::string &&json_path, std::string &&dataset_path)
: m_preprocessorManager(new PreprocessorManager())
{
utils::Json::Map datas = JSON_CAST(Map const, m_json.load(std::move(json_path)));
if (not datas["preprocessors"])
throw std::runtime_error("No preprocessors in json");
m_preprocessorManager->load_preprocessor(
JSON_CAST(Vector const, datas["preprocessors"])
);
if (not datas["segmenter"])
throw std::runtime_error("No segmenter in json");
m_segmenter = m_moduleManager.load_module<ISegmenter>(
(JSON_CAST(Map const, datas["segmenter"]))
);
if (not datas["feature_extractor"])
throw std::runtime_error("No feature_extractor in json");
m_featureExtractor = m_moduleManager.load_module<IFeatureExtractor>(
JSON_CAST(Map const, datas["feature_extractor"])
);
if (not datas["classifier"])
throw std::runtime_error("No classifier in json");
auto tmp = datas["classifier"].get<utils::Json::Map>();
JSON_CAST(Map, tmp["args"])["feature_extractor"] = m_featureExtractor;
m_classifier = m_moduleManager.load_module<IClassifier>(tmp);
m_dataset = Dataset(m_featureExtractor, m_preprocessorManager, dataset_path);
}
Brain::~Brain()
{
}
std::vector<std::string>
Brain::apply(std::string const &imagePath) const
{
auto img = Image(std::move(imagePath));
m_preprocessorManager->apply(img);
std::cout << "Segmentation" << std::endl;
std::cout << "\tApply " << m_segmenter->name() << std::endl;
std::cout << "Looping over sub matrices" << std::endl;
auto nb_subMatrix = m_segmenter->apply(std::move(img));
std::cout << nb_subMatrix << std::endl;
for (ssize_t i = 0; i < nb_subMatrix; ++i) {
auto subMatrix = img.getSubMatrix(i);
std::cout << "\t Feature extractor: " << m_featureExtractor->name()
<< std::endl;
auto features = m_featureExtractor->extract(std::move(img), i);
std::cout << "\t Classifier: " << m_classifier->name() << std::endl;
auto value = m_classifier->classify(std::move(features), m_dataset);
std::cout << "output value: " << value << std::endl;
}
img.writeImage();
return std::vector<std::string>();
}
void
Brain::loadTrainData(std::string const &filePath)
{
m_classifier->unserialize(filePath);
}
void
Brain::train()
{
std::cout << "Brain::train" << std::endl;
//auto dataset = Dataset(m_featureExtractor,
//m_preprocessorManager,
//dataset_path);
m_classifier->train(std::move(m_dataset));
}
void
Brain::serialize(std::string &&filePath)
{
m_classifier->serialize(std::move(filePath));
}
void
Brain::update_json(utils::Json::Map &)
{
#warning "TODO: implement depencies injection"
}
}
<commit_msg>fix invalid preprocessing<commit_after>// Simple OCR program
// Copyright (C) 2014 vhb
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <Brain.hpp>
#include <utility>
#include <Image.hpp>
namespace ocr {
Brain::Brain(std::string &&json_path, std::string &&dataset_path)
: m_preprocessorManager(new PreprocessorManager())
{
utils::Json::Map datas = JSON_CAST(Map const, m_json.load(std::move(json_path)));
if (not datas["preprocessors"])
throw std::runtime_error("No preprocessors in json");
m_preprocessorManager->load_preprocessor(
JSON_CAST(Vector const, datas["preprocessors"])
);
if (not datas["segmenter"])
throw std::runtime_error("No segmenter in json");
m_segmenter = m_moduleManager.load_module<ISegmenter>(
(JSON_CAST(Map const, datas["segmenter"]))
);
if (not datas["feature_extractor"])
throw std::runtime_error("No feature_extractor in json");
m_featureExtractor = m_moduleManager.load_module<IFeatureExtractor>(
JSON_CAST(Map const, datas["feature_extractor"])
);
if (not datas["classifier"])
throw std::runtime_error("No classifier in json");
auto tmp = datas["classifier"].get<utils::Json::Map>();
JSON_CAST(Map, tmp["args"])["feature_extractor"] = m_featureExtractor;
m_classifier = m_moduleManager.load_module<IClassifier>(tmp);
m_dataset = Dataset(m_featureExtractor, m_preprocessorManager, dataset_path);
}
Brain::~Brain()
{
}
std::vector<std::string>
Brain::apply(std::string const &imagePath) const
{
auto img = Image(std::move(imagePath));
m_preprocessorManager->apply(img);
std::cout << "Segmentation" << std::endl;
std::cout << "\tApply " << m_segmenter->name() << std::endl;
std::cout << "Looping over sub matrices" << std::endl;
//auto nb_subMatrix =
//auto nb_subMatrix = m_segmenter->apply(std::move(img));
auto subMatrix = img.getCurrentMatrix();
//std::cout << nb_subMatrix << std::endl;
//for (ssize_t i = 0; i < nb_subMatrix; ++i) {
//auto subMatrix = img.getSubMatrix(i);
std::cout << "\t Feature extractor: " << m_featureExtractor->name()
<< std::endl;
auto features = m_featureExtractor->extract(subMatrix);
//auto features = m_featureExtractor->extract(std::move(img), i);
std::cout << "\t Classifier: " << m_classifier->name() << std::endl;
auto value = m_classifier->classify(std::move(features), m_dataset);
std::cout << "output value: " << value << std::endl;
//}
img.writeImage();
return std::vector<std::string>();
}
void
Brain::loadTrainData(std::string const &filePath)
{
m_classifier->unserialize(filePath);
}
void
Brain::train()
{
std::cout << "Brain::train" << std::endl;
//auto dataset = Dataset(m_featureExtractor,
//m_preprocessorManager,
//dataset_path);
m_classifier->train(std::move(m_dataset));
}
void
Brain::serialize(std::string &&filePath)
{
m_classifier->serialize(std::move(filePath));
}
void
Brain::update_json(utils::Json::Map &)
{
#warning "TODO: implement depencies injection"
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DrawCallPerf:
// Performance tests for ANGLE draw call overhead.
//
#include <sstream>
#include "ANGLEPerfTest.h"
#include "shader_utils.h"
using namespace angle;
namespace
{
struct DrawCallPerfParams final : public RenderTestParams
{
// Common default options
DrawCallPerfParams()
{
majorVersion = 2;
minorVersion = 0;
windowWidth = 256;
windowHeight = 256;
iterations = 50;
numTris = 1;
runTimeSeconds = 10.0;
}
std::string suffix() const override
{
std::stringstream strstr;
strstr << RenderTestParams::suffix();
if (numTris == 0)
{
strstr << "_validation_only";
}
if (eglParameters.deviceType == EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE)
{
strstr << "_null";
}
return strstr.str();
}
unsigned int iterations;
double runTimeSeconds;
int numTris;
};
std::ostream &operator<<(std::ostream &os, const DrawCallPerfParams ¶ms)
{
os << params.suffix().substr(1);
return os;
}
class DrawCallPerfBenchmark : public ANGLERenderTest,
public ::testing::WithParamInterface<DrawCallPerfParams>
{
public:
DrawCallPerfBenchmark();
void initializeBenchmark() override;
void destroyBenchmark() override;
void drawBenchmark() override;
private:
GLuint mProgram;
GLuint mBuffer;
int mNumTris;
};
DrawCallPerfBenchmark::DrawCallPerfBenchmark()
: ANGLERenderTest("DrawCallPerf", GetParam()),
mProgram(0),
mBuffer(0),
mNumTris(GetParam().numTris)
{
mRunTimeSeconds = GetParam().runTimeSeconds;
}
void DrawCallPerfBenchmark::initializeBenchmark()
{
const auto ¶ms = GetParam();
ASSERT_LT(0u, params.iterations);
const std::string vs = SHADER_SOURCE
(
attribute vec2 vPosition;
uniform float uScale;
uniform float uOffset;
void main()
{
gl_Position = vec4(vPosition * vec2(uScale) - vec2(uOffset), 0, 1);
}
);
const std::string fs = SHADER_SOURCE
(
precision mediump float;
void main()
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
);
mProgram = CompileProgram(vs, fs);
ASSERT_NE(0u, mProgram);
// Use the program object
glUseProgram(mProgram);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
std::vector<GLfloat> floatData;
for (int quadIndex = 0; quadIndex < mNumTris; ++quadIndex)
{
floatData.push_back(1);
floatData.push_back(2);
floatData.push_back(0);
floatData.push_back(0);
floatData.push_back(2);
floatData.push_back(0);
}
glGenBuffers(1, &mBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mBuffer);
// To avoid generating GL errors when testing validation-only
if (floatData.empty())
{
floatData.push_back(0.0f);
}
glBufferData(GL_ARRAY_BUFFER, floatData.size() * sizeof(GLfloat), &floatData[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
// Set the viewport
glViewport(0, 0, getWindow()->getWidth(), getWindow()->getHeight());
GLfloat scale = 0.5f;
GLfloat offset = 0.5f;
glUniform1f(glGetUniformLocation(mProgram, "uScale"), scale);
glUniform1f(glGetUniformLocation(mProgram, "uOffset"), offset);
ASSERT_GL_NO_ERROR();
}
void DrawCallPerfBenchmark::destroyBenchmark()
{
glDeleteProgram(mProgram);
glDeleteBuffers(1, &mBuffer);
}
void DrawCallPerfBenchmark::drawBenchmark()
{
glClear(GL_COLOR_BUFFER_BIT);
const auto ¶ms = GetParam();
for (unsigned int it = 0; it < params.iterations; it++)
{
glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(3 * mNumTris));
}
ASSERT_GL_NO_ERROR();
}
using namespace egl_platform;
DrawCallPerfParams DrawCallPerfD3D11Params(bool useNullDevice)
{
DrawCallPerfParams params;
params.eglParameters = useNullDevice ? D3D11_NULL() : D3D11();
return params;
}
DrawCallPerfParams DrawCallPerfD3D9Params(bool useNullDevice)
{
DrawCallPerfParams params;
params.eglParameters = useNullDevice ? D3D9_NULL() : D3D9();
return params;
}
DrawCallPerfParams DrawCallPerfOpenGLParams(bool useNullDevice)
{
DrawCallPerfParams params;
params.eglParameters = useNullDevice ? OPENGL_NULL() : OPENGL();
return params;
}
DrawCallPerfParams DrawCallPerfValidationOnly()
{
DrawCallPerfParams params;
params.eglParameters = DEFAULT();
params.iterations = 10000;
params.numTris = 0;
params.runTimeSeconds = 5.0;
return params;
}
TEST_P(DrawCallPerfBenchmark, Run)
{
run();
}
ANGLE_INSTANTIATE_TEST(DrawCallPerfBenchmark,
DrawCallPerfD3D11Params(false),
DrawCallPerfD3D9Params(false),
DrawCallPerfOpenGLParams(false),
DrawCallPerfD3D11Params(true),
DrawCallPerfD3D9Params(true),
DrawCallPerfOpenGLParams(true),
DrawCallPerfValidationOnly());
} // namespace
<commit_msg>Add a perf test for render-to-texture.<commit_after>//
// Copyright (c) 2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DrawCallPerf:
// Performance tests for ANGLE draw call overhead.
//
#include <sstream>
#include "ANGLEPerfTest.h"
#include "shader_utils.h"
using namespace angle;
namespace
{
struct DrawCallPerfParams final : public RenderTestParams
{
// Common default options
DrawCallPerfParams()
{
majorVersion = 2;
minorVersion = 0;
windowWidth = 256;
windowHeight = 256;
}
std::string suffix() const override
{
std::stringstream strstr;
strstr << RenderTestParams::suffix();
if (numTris == 0)
{
strstr << "_validation_only";
}
if (useFBO)
{
strstr << "_render_to_texture";
}
if (eglParameters.deviceType == EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE)
{
strstr << "_null";
}
return strstr.str();
}
unsigned int iterations = 50;
double runTimeSeconds = 10.0;
int numTris = 1;
bool useFBO = false;
};
std::ostream &operator<<(std::ostream &os, const DrawCallPerfParams ¶ms)
{
os << params.suffix().substr(1);
return os;
}
class DrawCallPerfBenchmark : public ANGLERenderTest,
public ::testing::WithParamInterface<DrawCallPerfParams>
{
public:
DrawCallPerfBenchmark();
void initializeBenchmark() override;
void destroyBenchmark() override;
void drawBenchmark() override;
private:
GLuint mProgram = 0;
GLuint mBuffer = 0;
GLuint mFBO = 0;
GLuint mTexture = 0;
int mNumTris = GetParam().numTris;
};
DrawCallPerfBenchmark::DrawCallPerfBenchmark() : ANGLERenderTest("DrawCallPerf", GetParam())
{
mRunTimeSeconds = GetParam().runTimeSeconds;
}
void DrawCallPerfBenchmark::initializeBenchmark()
{
const auto ¶ms = GetParam();
ASSERT_LT(0u, params.iterations);
const std::string vs = SHADER_SOURCE
(
attribute vec2 vPosition;
uniform float uScale;
uniform float uOffset;
void main()
{
gl_Position = vec4(vPosition * vec2(uScale) - vec2(uOffset), 0, 1);
}
);
const std::string fs = SHADER_SOURCE
(
precision mediump float;
void main()
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
);
mProgram = CompileProgram(vs, fs);
ASSERT_NE(0u, mProgram);
// Use the program object
glUseProgram(mProgram);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
std::vector<GLfloat> floatData;
for (int quadIndex = 0; quadIndex < mNumTris; ++quadIndex)
{
floatData.push_back(1);
floatData.push_back(2);
floatData.push_back(0);
floatData.push_back(0);
floatData.push_back(2);
floatData.push_back(0);
}
glGenBuffers(1, &mBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mBuffer);
// To avoid generating GL errors when testing validation-only
if (floatData.empty())
{
floatData.push_back(0.0f);
}
glBufferData(GL_ARRAY_BUFFER, floatData.size() * sizeof(GLfloat), &floatData[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
// Set the viewport
glViewport(0, 0, getWindow()->getWidth(), getWindow()->getHeight());
GLfloat scale = 0.5f;
GLfloat offset = 0.5f;
glUniform1f(glGetUniformLocation(mProgram, "uScale"), scale);
glUniform1f(glGetUniformLocation(mProgram, "uOffset"), offset);
if (params.useFBO)
{
glGenFramebuffers(1, &mFBO);
glBindFramebuffer(GL_FRAMEBUFFER, mFBO);
glGenTextures(1, &mTexture);
glBindTexture(GL_TEXTURE_2D, mTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWindow()->getWidth(), getWindow()->getHeight(),
0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTexture, 0);
}
ASSERT_GL_NO_ERROR();
}
void DrawCallPerfBenchmark::destroyBenchmark()
{
glDeleteProgram(mProgram);
glDeleteBuffers(1, &mBuffer);
glDeleteTextures(1, &mTexture);
glDeleteFramebuffers(1, &mFBO);
}
void DrawCallPerfBenchmark::drawBenchmark()
{
glClear(GL_COLOR_BUFFER_BIT);
const auto ¶ms = GetParam();
for (unsigned int it = 0; it < params.iterations; it++)
{
glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(3 * mNumTris));
}
ASSERT_GL_NO_ERROR();
}
using namespace egl_platform;
DrawCallPerfParams DrawCallPerfD3D11Params(bool useNullDevice, bool renderToTexture)
{
DrawCallPerfParams params;
params.eglParameters = useNullDevice ? D3D11_NULL() : D3D11();
params.useFBO = renderToTexture;
return params;
}
DrawCallPerfParams DrawCallPerfD3D9Params(bool useNullDevice, bool renderToTexture)
{
DrawCallPerfParams params;
params.eglParameters = useNullDevice ? D3D9_NULL() : D3D9();
params.useFBO = renderToTexture;
return params;
}
DrawCallPerfParams DrawCallPerfOpenGLParams(bool useNullDevice, bool renderToTexture)
{
DrawCallPerfParams params;
params.eglParameters = useNullDevice ? OPENGL_NULL() : OPENGL();
params.useFBO = renderToTexture;
return params;
}
DrawCallPerfParams DrawCallPerfValidationOnly()
{
DrawCallPerfParams params;
params.eglParameters = DEFAULT();
params.iterations = 10000;
params.numTris = 0;
params.runTimeSeconds = 5.0;
return params;
}
TEST_P(DrawCallPerfBenchmark, Run)
{
run();
}
ANGLE_INSTANTIATE_TEST(DrawCallPerfBenchmark,
DrawCallPerfD3D9Params(false, false),
DrawCallPerfD3D9Params(true, false),
DrawCallPerfD3D11Params(false, false),
DrawCallPerfD3D11Params(true, false),
DrawCallPerfD3D11Params(true, true),
DrawCallPerfOpenGLParams(false, false),
DrawCallPerfOpenGLParams(true, false),
DrawCallPerfOpenGLParams(true, true),
DrawCallPerfValidationOnly());
} // namespace
<|endoftext|> |
<commit_before>#include "Course.h"
#include <string>
using namespace std;
Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){
startTime = _startTime;
endTime = _endTime;
days = _days;
courseName = _courseName;
courseLoc = _courseLoc;
courseId = _courseId;
}
int const Course::getEndTime(){
return endTime;
}
int const Course::getStartTime(){
return startTime;
}
string const Course::getDays(){
return days;
}
string const Course::getName(){
return courseName;
}
string const Course::getLoc(){
return courseLoc;
}
int const Course::getId(){
return 0;
}<commit_msg>Course.it10 - pass: get id<commit_after>#include "Course.h"
#include <string>
using namespace std;
Course::Course(unsigned int _startTime, unsigned int _endTime, string _days, string _courseName, string _courseLoc, unsigned int _courseId){
startTime = _startTime;
endTime = _endTime;
days = _days;
courseName = _courseName;
courseLoc = _courseLoc;
courseId = _courseId;
}
int const Course::getEndTime(){
return endTime;
}
int const Course::getStartTime(){
return startTime;
}
string const Course::getDays(){
return days;
}
string const Course::getName(){
return courseName;
}
string const Course::getLoc(){
return courseLoc;
}
int const Course::getId(){
return courseId;
}<|endoftext|> |
<commit_before>#include "Error.hpp"
#include <cstdarg>
PyObject * MGLError_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
MGLError * self = (MGLError *)type->tp_alloc(type, 0);
#ifdef MGL_VERBOSE
printf("MGLError_tp_new %p\n", self);
#endif
if (self) {
self->dict = 0;
self->args = 0;
self->traceback = 0;
self->context = 0;
self->cause = 0;
self->suppress_context = 0;
}
return (PyObject *)self;
}
void MGLError_tp_dealloc(MGLError * self) {
#ifdef MGL_VERBOSE
printf("MGLError_tp_dealloc %p\n", self);
#endif
Py_XDECREF(self->github);
PyTypeObject * super = Py_TYPE(self)->tp_base;
return super->tp_dealloc((PyObject *)self);
}
int MGLError_tp_init(MGLError * self, PyObject * args, PyObject * kwargs) {
MGLError * error = MGLError_New(TRACE, "Cannot create ModernGL.Error manually");
PyErr_SetObject((PyObject *)&MGLError_Type, (PyObject *)error);
return -1;
}
PyMethodDef MGLError_tp_methods[] = {
{0},
};
PyObject * MGLError_get_github(MGLError * self) {
if (self->github) {
Py_INCREF(self->github);
return self->github;
} else {
Py_RETURN_NONE;
}
}
char MGLError_github_doc[] = R"(
github
A link to the source code, where the error occurred.
)";
PyGetSetDef MGLError_tp_getseters[] = {
{(char *)"github", (getter)MGLError_get_github, 0, MGLError_github_doc, 0},
{0},
};
const char * MGLError_tp_doc = R"(
Error
)";
PyTypeObject MGLError_Type = {
PyVarObject_HEAD_INIT(0, 0)
"ModernGL.Error", // tp_name
sizeof(MGLError), // tp_basicsize
0, // tp_itemsize
(destructor)MGLError_tp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
MGLError_tp_doc, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
MGLError_tp_methods, // tp_methods
0, // tp_members
MGLError_tp_getseters, // tp_getset
(PyTypeObject *)PyExc_Exception, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)MGLError_tp_init, // tp_init
0, // tp_alloc
MGLError_tp_new, // tp_new
};
#define GITHUB_URL "https://github.com/cprogrammer1994/ModernGL/blob/ModernGL3"
#define GITHUB(path) GITHUB_URL # path
MGLError * MGLError_New(const char * filename, int line, const char * format, ...) {
MGLError * self = (MGLError *)MGLError_tp_new(&MGLError_Type, 0, 0);
va_list va_args;
va_start(va_args, format);
self->args = PyTuple_New(1);
PyObject * message = PyUnicode_FromFormatV(format, va_args);
PyTuple_SET_ITEM(self->args, 0, message);
va_end(va_args);
self->github = PyUnicode_FromFormat(GITHUB("/src/%s#L%d"), filename + 4, line);
return self;
}
// void MGLError_LinkSource(MGLError * error, const char * filename, int line) {
// }
<commit_msg>suppress_context is not a member of ERR in py2<commit_after>#include "Error.hpp"
#include <cstdarg>
PyObject * MGLError_tp_new(PyTypeObject * type, PyObject * args, PyObject * kwargs) {
MGLError * self = (MGLError *)type->tp_alloc(type, 0);
#ifdef MGL_VERBOSE
printf("MGLError_tp_new %p\n", self);
#endif
if (self) {
self->dict = 0;
self->args = 0;
self->traceback = 0;
self->context = 0;
self->cause = 0;
// TODO: fix this :)
#if PY_MAJOR_VERSION >= 3
self->suppress_context = 0;
#endif
}
return (PyObject *)self;
}
void MGLError_tp_dealloc(MGLError * self) {
#ifdef MGL_VERBOSE
printf("MGLError_tp_dealloc %p\n", self);
#endif
Py_XDECREF(self->github);
PyTypeObject * super = Py_TYPE(self)->tp_base;
return super->tp_dealloc((PyObject *)self);
}
int MGLError_tp_init(MGLError * self, PyObject * args, PyObject * kwargs) {
MGLError * error = MGLError_New(TRACE, "Cannot create ModernGL.Error manually");
PyErr_SetObject((PyObject *)&MGLError_Type, (PyObject *)error);
return -1;
}
PyMethodDef MGLError_tp_methods[] = {
{0},
};
PyObject * MGLError_get_github(MGLError * self) {
if (self->github) {
Py_INCREF(self->github);
return self->github;
} else {
Py_RETURN_NONE;
}
}
char MGLError_github_doc[] = R"(
github
A link to the source code, where the error occurred.
)";
PyGetSetDef MGLError_tp_getseters[] = {
{(char *)"github", (getter)MGLError_get_github, 0, MGLError_github_doc, 0},
{0},
};
const char * MGLError_tp_doc = R"(
Error
)";
PyTypeObject MGLError_Type = {
PyVarObject_HEAD_INIT(0, 0)
"ModernGL.Error", // tp_name
sizeof(MGLError), // tp_basicsize
0, // tp_itemsize
(destructor)MGLError_tp_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
MGLError_tp_doc, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
MGLError_tp_methods, // tp_methods
0, // tp_members
MGLError_tp_getseters, // tp_getset
(PyTypeObject *)PyExc_Exception, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)MGLError_tp_init, // tp_init
0, // tp_alloc
MGLError_tp_new, // tp_new
};
#define GITHUB_URL "https://github.com/cprogrammer1994/ModernGL/blob/ModernGL3"
#define GITHUB(path) GITHUB_URL # path
MGLError * MGLError_New(const char * filename, int line, const char * format, ...) {
MGLError * self = (MGLError *)MGLError_tp_new(&MGLError_Type, 0, 0);
va_list va_args;
va_start(va_args, format);
self->args = PyTuple_New(1);
PyObject * message = PyUnicode_FromFormatV(format, va_args);
PyTuple_SET_ITEM(self->args, 0, message);
va_end(va_args);
self->github = PyUnicode_FromFormat(GITHUB("/src/%s#L%d"), filename + 4, line);
return self;
}
// void MGLError_LinkSource(MGLError * error, const char * filename, int line) {
// }
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Nodes.hpp"
#include "StringPool.hpp"
#include "Options.hpp"
#include "ByteCodeFileWriter.hpp"
#include "Variables.hpp"
#include <cassert>
using std::string;
void Declaration::checkVariables(Variables& variables) throw (CompilerException){
if(variables.exists(m_variable)){
throw CompilerException("Variable has already been declared");
}
Variable* var = variables.create(m_variable, m_type);
m_index = var->index();
value->checkVariables(variables);
if(value->type() != m_type){
throw CompilerException("Incompatible type");
}
}
void Declaration::checkStrings(StringPool& pool){
value->checkStrings(pool);
}
void Assignment::checkVariables(Variables& variables) throw (CompilerException){
if(!variables.exists(m_variable)){
throw CompilerException("Variable has not been declared");
}
Variable* var = variables.find(m_variable);
m_index = var->index();
value->checkVariables(variables);
if(value->type() != var->type()){
throw CompilerException("Incompatible type");
}
}
void Assignment::checkStrings(StringPool& pool){
value->checkStrings(pool);
}
void VariableValue::checkVariables(Variables& variables) throw (CompilerException){
if(!variables.exists(m_variable)){
throw CompilerException("Variable has not been declared");
}
Variable* variable = variables.find(m_variable);
m_type = variable->type();
m_index = variable->index();
}
void Litteral::checkStrings(StringPool& pool){
m_label = pool.label(m_litteral);
}
void Declaration::write(ByteCodeFileWriter& writer){
value->write(writer);
switch(m_type){
case INT:
writer.stream() << "movl (%esp), %eax" << std::endl;
writer.stream() << "movl %eax, VI" << m_index << "" << std::endl;
writer.stream() << "addl $4, %esp" << std::endl;
break;
case STRING:
writer.writeOneOperandCall(SSTORE, m_index);
break;
}
}
void Assignment::write(ByteCodeFileWriter& writer){
value->write(writer);
switch(value->type()){
case INT:
writer.stream() << "movl (%esp), %eax" << std::endl;
writer.stream() << "movl %eax, VI" << m_index << "" << std::endl;
writer.stream() << "addl $4, %esp" << std::endl;
break;
case STRING:
writer.writeOneOperandCall(SSTORE, m_index);
break;
}
}
void Print::write(ByteCodeFileWriter& writer){
value->write(writer);
switch(value->type()){
case INT:
writer.nativeWrite("call print_integer");
writer.nativeWrite("addl $4, %esp");
//TODO Optimize that shit
writer.nativeWrite("pushl $S1");
writer.nativeWrite("pushl $1");
writer.nativeWrite("call print_string");
writer.nativeWrite("addl $8, %esp");
break;
case STRING:
writer.nativeWrite("call print_string");
writer.nativeWrite("addl $8, %esp");
//TODO Optimize that shit
writer.nativeWrite("pushl $S1");
writer.nativeWrite("pushl $1");
writer.nativeWrite("call print_string");
writer.nativeWrite("addl $8, %esp");
break;
}
}
void Print::checkStrings(StringPool& pool){
value->checkStrings(pool);
}
void Print::checkVariables(Variables& variables) throw (CompilerException) {
value->checkVariables(variables);
}
void Integer::write(ByteCodeFileWriter& writer){
writer.stream() << "pushl $" << m_value << std::endl;
}
void VariableValue::write(ByteCodeFileWriter& writer){
switch(m_type){
case INT:
writer.stream() << "pushl VI" << m_index << std::endl;
break;
case STRING:
writer.writeOneOperandCall(SLOAD, m_index);
break;
}
}
void Litteral::write(ByteCodeFileWriter& writer){
writer.stream() << "pushl $" << m_label << std::endl;
writer.stream() << "pushl $" << (m_litteral.size() - 2) << std::endl;
}
//Constantness
bool Value::isConstant(){
return false;
}
bool Litteral::isConstant(){
return true;
}
bool Integer::isConstant(){
return true;
}
bool VariableValue::isConstant(){
return false;
}
//Values
string Value::getStringValue(){
throw "Not constant";
}
int Value::getIntValue(){
throw "Not constant";
}
int Integer::getIntValue(){
return m_value;
}
string Litteral::getStringValue(){
return m_litteral;
}
<commit_msg>Implement push for string variables<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "Nodes.hpp"
#include "StringPool.hpp"
#include "Options.hpp"
#include "ByteCodeFileWriter.hpp"
#include "Variables.hpp"
#include <cassert>
using std::string;
void Declaration::checkVariables(Variables& variables) throw (CompilerException){
if(variables.exists(m_variable)){
throw CompilerException("Variable has already been declared");
}
Variable* var = variables.create(m_variable, m_type);
m_index = var->index();
value->checkVariables(variables);
if(value->type() != m_type){
throw CompilerException("Incompatible type");
}
}
void Declaration::checkStrings(StringPool& pool){
value->checkStrings(pool);
}
void Assignment::checkVariables(Variables& variables) throw (CompilerException){
if(!variables.exists(m_variable)){
throw CompilerException("Variable has not been declared");
}
Variable* var = variables.find(m_variable);
m_index = var->index();
value->checkVariables(variables);
if(value->type() != var->type()){
throw CompilerException("Incompatible type");
}
}
void Assignment::checkStrings(StringPool& pool){
value->checkStrings(pool);
}
void VariableValue::checkVariables(Variables& variables) throw (CompilerException){
if(!variables.exists(m_variable)){
throw CompilerException("Variable has not been declared");
}
Variable* variable = variables.find(m_variable);
m_type = variable->type();
m_index = variable->index();
}
void Litteral::checkStrings(StringPool& pool){
m_label = pool.label(m_litteral);
}
void Declaration::write(ByteCodeFileWriter& writer){
value->write(writer);
switch(m_type){
case INT:
writer.stream() << "movl (%esp), %eax" << std::endl;
writer.stream() << "movl %eax, VI" << m_index << "" << std::endl;
writer.stream() << "addl $4, %esp" << std::endl;
break;
case STRING:
writer.writeOneOperandCall(SSTORE, m_index);
break;
}
}
void Assignment::write(ByteCodeFileWriter& writer){
value->write(writer);
switch(value->type()){
case INT:
writer.stream() << "movl (%esp), %eax" << std::endl;
writer.stream() << "movl %eax, VI" << m_index << "" << std::endl;
writer.stream() << "addl $4, %esp" << std::endl;
break;
case STRING:
writer.writeOneOperandCall(SSTORE, m_index);
break;
}
}
void Print::write(ByteCodeFileWriter& writer){
value->write(writer);
switch(value->type()){
case INT:
writer.nativeWrite("call print_integer");
writer.nativeWrite("addl $4, %esp");
//TODO Optimize that shit
writer.nativeWrite("pushl $S1");
writer.nativeWrite("pushl $1");
writer.nativeWrite("call print_string");
writer.nativeWrite("addl $8, %esp");
break;
case STRING:
writer.nativeWrite("call print_string");
writer.nativeWrite("addl $8, %esp");
//TODO Optimize that shit
writer.nativeWrite("pushl $S1");
writer.nativeWrite("pushl $1");
writer.nativeWrite("call print_string");
writer.nativeWrite("addl $8, %esp");
break;
}
}
void Print::checkStrings(StringPool& pool){
value->checkStrings(pool);
}
void Print::checkVariables(Variables& variables) throw (CompilerException) {
value->checkVariables(variables);
}
void Integer::write(ByteCodeFileWriter& writer){
writer.stream() << "pushl $" << m_value << std::endl;
}
void VariableValue::write(ByteCodeFileWriter& writer){
switch(m_type){
case INT:
writer.stream() << "pushl VI" << m_index << std::endl;
break;
case STRING:
writer.stream() << "pushl $VS" << m_index << std::endl;
writer.stream() << "pushl 4(VS" << m_index << ")" << std::endl;
break;
}
}
void Litteral::write(ByteCodeFileWriter& writer){
writer.stream() << "pushl $" << m_label << std::endl;
writer.stream() << "pushl $" << (m_litteral.size() - 2) << std::endl;
}
//Constantness
bool Value::isConstant(){
return false;
}
bool Litteral::isConstant(){
return true;
}
bool Integer::isConstant(){
return true;
}
bool VariableValue::isConstant(){
return false;
}
//Values
string Value::getStringValue(){
throw "Not constant";
}
int Value::getIntValue(){
throw "Not constant";
}
int Integer::getIntValue(){
return m_value;
}
string Litteral::getStringValue(){
return m_litteral;
}
<|endoftext|> |
<commit_before>#include <WPILib.h>
#include "EventRelay.hpp"
#include "Autonomous.hpp"
#include "Action.hpp"
#include "JoyButton.hpp"
#include "DriveAuto.hpp"
#include "JoystickWrapper.hpp"
#include "RobotLocation.hpp"
#include "TwoMotorGroup.hpp"
#include "Vision.hpp"
#include "ActionMap.hpp"
#include "Shifter.hpp"
#include "ToteLifter.hpp"
class Robot: public IterativeRobot
{
private:
EventRelay relay;
ToteLifter lifter;
Shifter shifter;
public:
Robot() : shifter(0, 1)
{
}
void RobotInit()
{
JoyButton button9(true, false, false, ButtonNames::Button9);
std::function<void()> callbackManualUp(std::bind(&ToteLifter::manualUp, &lifter));
Action<void()> actionManualUp(callbackManualUp, 0);
relay.getMapJoy().associate(button9, actionManualUp);
JoyButton button11(true, false, false, ButtonNames::Button11);
std::function<void()> callbackManualStop(std::bind(&ToteLifter::manualStop, &lifter));
Action<void()> actionManualStop(callbackManualStop, 0);
relay.getMapJoy().associate(button11, actionManualStop);
JoyButton button10(true, false, false, ButtonNames::Button10);
std::function<void()> callbackManualDown(std::bind(&ToteLifter::manualDown, &lifter));
Action<void()> actionManualDown(callbackManualDown, 0);
relay.getMapJoy().associate(button10, actionManualDown);
JoyButton button(true, false, false, ButtonNames::Button7);
std::function<void()> callbackShiftLow(std::bind(&Shifter::shiftLow, &shifter));
Action<void()> actionB(callbackShiftLow, 0);
relay.getMapJoy().associate(button, actionB);
JoyButton buttonHigh(true, false, false, ButtonNames::Button8);
std::function<void()> callbackShiftHigh(std::bind(&Shifter::shiftHigh, &shifter));
Action<void()> actionHigh(callbackShiftHigh, 0);
relay.getMapJoy().associate(buttonHigh, actionHigh);
}
void AutonomousInit()
{
}
void AutonomousPeriodic()
{
}
void TeleopInit()
{
}
void TeleopPeriodic()
{
relay.checkStates();
}
void DisabledInit()
{
}
void DisabledPeriodic()
{
}
};
START_ROBOT_CLASS(Robot);
<commit_msg>final robot code<commit_after>#include <WPILib.h>
#include "EventRelay.hpp"
#include "Autonomous.hpp"
#include "Action.hpp"
#include "JoyButton.hpp"
#include "DriveAuto.hpp"
#include "JoystickWrapper.hpp"
#include "RobotLocation.hpp"
#include "TwoMotorGroup.hpp"
#include "Vision.hpp"
#include "ActionMap.hpp"
#include "Shifter.hpp"
#include "ToteLifter.hpp"
#include "JoyTest.hpp"
void createButtonMapping(bool down, bool pressed, bool up,
ButtonNames buttonName,
std::function<void()> callback,
ActionMap &map)
{
JoyButton button(down, pressed, up, buttonName);
Action<void()> action(callback, 0);
map.associate(button, action);
}
class Robot: public IterativeRobot
{
private:
EventRelay relay;
ToteLifter lifter;
Shifter shifter;
Timer timer;
JoyTest joyTest;
public:
Robot() : shifter(0, 1)
{
}
void RobotInit()
{
auto &joyMap = relay.getMapJoy();
auto &gcnMap = relay.getMapGCN();
createButtonMapping(true, false, false
, ButtonNames::Button9
, std::bind(&ToteLifter::manualUp, &lifter)
, joyMap);
createButtonMapping(true, false, false
, ButtonNames::Button11
, std::bind(&ToteLifter::manualStop, &lifter)
, joyMap);
createButtonMapping(true, false, false
, ButtonNames::Button10
, std::bind(&ToteLifter::manualDown, &lifter)
, joyMap);
createButtonMapping(true, false, false
, ButtonNames::Button7
, std::bind(&Shifter::shiftLow, &shifter)
, joyMap);
createButtonMapping(true, false, false
, ButtonNames::Button8
, std::bind(&Shifter::shiftHigh, &shifter)
, joyMap);
createButtonMapping(true, false, false
, ButtonNames::Trigger
, std::bind(&JoyTest::button21, &joyTest)
, gcnMap);
createButtonMapping(true, false, false
, ButtonNames::Trigger
, std::bind(&JoyTest::button11, &joyTest)
, joyMap);
}
void AutonomousInit()
{
RobotLocation::get();
}
void AutonomousPeriodic()
{
int dist = RobotLocation::get()->getEast()->getDistance();
std::cout << dist << std::endl;
std::cout << "\t" << RobotLocation::get()->getNorth()->getDistance() << std::endl;
}
void TeleopInit()
{
}
void TeleopPeriodic()
{
relay.checkStates();
shifter.shiftUpdate();
}
void DisabledInit()
{
}
void DisabledPeriodic()
{
}
};
START_ROBOT_CLASS(Robot);
<|endoftext|> |
<commit_before>#include "Scene.hpp"
//#define LOG_GL
#include "glerr.hpp"
Scene::Scene() {
m_ambience = 0.1f;
try {
m_actors.emplace_back(std::make_unique<Actor>("Akari"));
} catch(const std::exception& exception) {
g_logger->write(Logger::ERROR, exception.what());
throw std::runtime_error("Failed to load Actor");
}
m_physicsSimulator = new PhysicsSimulator();
m_activeCamera = new Camera();
m_activeCamera->translate(-10.0f, 0.0f, 0.0f);
m_activeShader = new Shader("textured.vert.glsl", "textured.frag.glsl");
m_pointLight = new PointLight(glm::vec3(-3.0f, 0.0f, 0.0f), // Position
glm::vec3(1.0f, 0.0f, 0.0f), // Color
20.0f, // Intensity
3.0f); // Radius
m_spotLight = new SpotLight(glm::vec3(2.0f, 0.0f, 0.0f), // Position
glm::vec3(0.0f, 0.0f, -1.0f), // Direction
glm::vec3(0.0f, 1.0f, 0.0f), // Color
7.0f, // Intensity
5.0f, // Angle
15.0f); // Radius
m_directionLight =
new DirectionLight(glm::vec3(1.0f, 0.0f, 0.0f), // Direction
glm::vec3(0.0f, 0.0f, 1.0f), // Color
1.0f); // Intensity
}
Scene::~Scene() {
delete m_pointLight;
delete m_spotLight;
delete m_directionLight;
delete m_activeCamera;
delete m_physicsSimulator;
delete m_activeShader;
}
/**
* Called to perform once-per-cycle processing
*
* TODO: Need to take time since last cycle as input
*/
void Scene::update() { m_actors.at(0)->rotate(0.0001f, 0.0001f, 0.0f); }
/**
* Runs the once-per-cycle physics simulation. Likely to be merged into the default update() method.
*
* TODO: Needs to take time since last cycle as input
*/
void Scene::simulate() { m_physicsSimulator->stepSimulation(); }
/**
* Draws all render models that are part of the scene using information passed down by the renderer
*
* @param [in] projectionMatrix Pointer to a 16-element array representing the 3D->2D, world->screen transformation
*/
void Scene::draw(glm::mat4 projectionMatrix) {
glLogErr("Pre-draw check");
m_activeShader->setAmbience(m_ambience);
m_activeShader->setPointLight(0, *m_pointLight);
m_activeShader->setSpotLight(0, *m_spotLight);
m_activeShader->setDirectionLight(0, *m_directionLight);
// Send camera position to the GPU.
// NOTE: Lighting uses explicit uniform locations. eyePos must be declared at
// location 0 in the shader, and lights from 1-8 (while we use forward
// rendering)
glm::vec4 camPos4 = m_activeCamera->getPosition();
glm::vec3 camPos3 = glm::vec3(camPos4.x, camPos4.y, camPos4.z);
m_activeShader->setViewMatrix(m_activeCamera->getViewMatrix());
glLogErr("Uploading view matrix");
m_activeShader->setEyePosition(camPos3);
glLogErr("Uploading camera position");
m_activeShader->setProjectionMatrix(projectionMatrix);
glLogErr("Uploading projection matrix");
m_actors.at(0)->draw(*m_activeShader);
glLogErr("Drawing actors");
}
<commit_msg>Speed up rotation of test model--vsync slowed it down<commit_after>#include "Scene.hpp"
//#define LOG_GL
#include "glerr.hpp"
Scene::Scene() {
m_ambience = 0.1f;
try {
m_actors.emplace_back(std::make_unique<Actor>("Akari"));
} catch(const std::exception& exception) {
g_logger->write(Logger::ERROR, exception.what());
throw std::runtime_error("Failed to load Actor");
}
m_physicsSimulator = new PhysicsSimulator();
m_activeCamera = new Camera();
m_activeCamera->translate(-10.0f, 0.0f, 0.0f);
m_activeShader = new Shader("textured.vert.glsl", "textured.frag.glsl");
m_pointLight = new PointLight(glm::vec3(-3.0f, 0.0f, 0.0f), // Position
glm::vec3(1.0f, 0.0f, 0.0f), // Color
20.0f, // Intensity
3.0f); // Radius
m_spotLight = new SpotLight(glm::vec3(2.0f, 0.0f, 0.0f), // Position
glm::vec3(0.0f, 0.0f, -1.0f), // Direction
glm::vec3(0.0f, 1.0f, 0.0f), // Color
7.0f, // Intensity
5.0f, // Angle
15.0f); // Radius
m_directionLight =
new DirectionLight(glm::vec3(1.0f, 0.0f, 0.0f), // Direction
glm::vec3(0.0f, 0.0f, 1.0f), // Color
1.0f); // Intensity
}
Scene::~Scene() {
delete m_pointLight;
delete m_spotLight;
delete m_directionLight;
delete m_activeCamera;
delete m_physicsSimulator;
delete m_activeShader;
}
/**
* Called to perform once-per-cycle processing
*
* TODO: Need to take time since last cycle as input
*/
void Scene::update() { m_actors.at(0)->rotate(0.01f, 0.01f, 0.0f); }
/**
* Runs the once-per-cycle physics simulation. Likely to be merged into the default update() method.
*
* TODO: Needs to take time since last cycle as input
*/
void Scene::simulate() { m_physicsSimulator->stepSimulation(); }
/**
* Draws all render models that are part of the scene using information passed down by the renderer
*
* @param [in] projectionMatrix Pointer to a 16-element array representing the 3D->2D, world->screen transformation
*/
void Scene::draw(glm::mat4 projectionMatrix) {
glLogErr("Pre-draw check");
m_activeShader->setAmbience(m_ambience);
m_activeShader->setPointLight(0, *m_pointLight);
m_activeShader->setSpotLight(0, *m_spotLight);
m_activeShader->setDirectionLight(0, *m_directionLight);
// Send camera position to the GPU.
// NOTE: Lighting uses explicit uniform locations. eyePos must be declared at
// location 0 in the shader, and lights from 1-8 (while we use forward
// rendering)
glm::vec4 camPos4 = m_activeCamera->getPosition();
glm::vec3 camPos3 = glm::vec3(camPos4.x, camPos4.y, camPos4.z);
m_activeShader->setViewMatrix(m_activeCamera->getViewMatrix());
glLogErr("Uploading view matrix");
m_activeShader->setEyePosition(camPos3);
glLogErr("Uploading camera position");
m_activeShader->setProjectionMatrix(projectionMatrix);
glLogErr("Uploading projection matrix");
m_actors.at(0)->draw(*m_activeShader);
glLogErr("Drawing actors");
}
<|endoftext|> |
<commit_before>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_ELIMINATOR_HPP
#define RESEMBLA_ELIMINATOR_HPP
#include <string>
#include <vector>
#include <map>
#include "string_util.hpp"
namespace resembla {
template<typename string_type, typename bitvector_type = uint64_t>
struct Eliminator
{
using size_type = typename string_type::size_type;
using symbol_type = typename string_type::value_type;
using distance_type = int;
Eliminator(string_type const& pattern = string_type())
{
init(pattern);
}
void init(string_type const& pattern)
{
this->pattern = pattern;
if(pattern.empty()){
return;
}
pattern_length = pattern.size();
block_size = ((pattern_length - 1) >> bitOffset<bitvector_type>()) + 1;
rest_bits = pattern_length - (block_size - 1) * bitWidth<bitvector_type>();
sink = bitvector_type{1} << (rest_bits - 1);
constructPM();
zeroes.resize(block_size, 0);
work.resize(block_size);
VP0 = 0;
for(size_type i = 0; i < rest_bits; ++i){
VP0 |= bitvector_type{1} << i;
}
}
void operator()(std::vector<string_type>& candidates, size_type k, bool keep_tie = true)
{
using index_distance = std::pair<size_type, distance_type>;
// calculate scores
std::vector<index_distance> work(candidates.size());
for(size_type i = 0; i < work.size(); ++i){
work[i].first = i;
work[i].second = -distance(candidates[i]);
}
if(keep_tie){
// sort partially to obtain top-k elements
std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
}
else{
std::sort(std::begin(work), std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
// expand k so that work[l] < work[k] for all l > k
while(k < work.size() - 1 && work[k] == work[k + 1]){
++k;
}
}
// ensure that work[i].first < work[j].first if i < j < k
std::sort(std::begin(work), std::begin(work) + k,
[](const index_distance& a, const index_distance& b) -> bool{
return a.first < b.first;
});
#ifdef DEBUG
std::cerr << "narrow " << work.size() << " strings" << std::endl;
for(size_type i = 0; i < k; ++i){
std::cerr << cast_string<std::string>(candidates[work[i].first]) << ": " << work[i].second << std::endl;
}
#endif
// sort original list
for(size_type i = 0; i < k; ++i){
std::swap(candidates[i], candidates[work[i].first]);
}
candidates.erase(std::begin(candidates) + k, std::end(candidates));
}
protected:
string_type pattern;
size_type pattern_length;
symbol_type c_min, c_max;
size_type block_size;
size_type rest_bits;
bitvector_type sink;
std::vector<std::pair<symbol_type, std::vector<bitvector_type>>> PM;
std::vector<bitvector_type> zeroes;
struct WorkData
{
bitvector_type D0;
bitvector_type HP;
bitvector_type HN;
bitvector_type VP;
bitvector_type VN;
void reset()
{
D0 = HP = HN = VN = 0;
VP = ~(bitvector_type{0});
}
};
std::vector<WorkData> work;
bitvector_type VP0;
template<typename Integer> static constexpr int bitWidth()
{
return 8 * sizeof(Integer);
}
static constexpr int bitOffset(int w)
{
return w < 2 ? 0 : (bitOffset(w >> 1) + 1);
}
template<typename Integer> static constexpr int bitOffset()
{
return bitOffset(bitWidth<Integer>());
}
template<typename key_type, typename value_type>
const value_type& findValue(const std::vector<std::pair<key_type, value_type>>& data,
const key_type c, const value_type& default_value) const
{
if(c < c_min || c_max < c){
return default_value;
}
else if(c == c_min){
return PM.front().second;
}
else if(c == c_max){
return PM.back().second;
}
size_type l = 1, r = data.size() - 1;
while(r - l > 8){
auto i = (l + r) / 2;
if(data[i].first < c){
l = i + 1;
}
else if(data[i].first > c){
r = i;
}
else{
return data[i].second;
}
}
for(size_type i = l; i < r; ++i){
if(data[i].first == c){
return data[i].second;
}
}
return default_value;
}
void constructPM()
{
std::map<symbol_type, std::vector<bitvector_type>> PM_work;
for(size_type i = 0; i < block_size - 1; ++i){
for(size_type j = 0; j < bitWidth<bitvector_type>(); ++j){
if(PM_work[pattern[i * bitWidth<bitvector_type>() + j]].empty()){
PM_work[pattern[i * bitWidth<bitvector_type>() + j]].resize(block_size, 0);
}
PM_work[pattern[i * bitWidth<bitvector_type>() + j]][i] |= bitvector_type{1} << j;
}
}
for(size_type i = 0; i < rest_bits; ++i){
if(PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].empty()){
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].resize(block_size, 0);
}
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].back() |= bitvector_type{1} << i;
}
PM.clear();
for(const auto& p: PM_work){
PM.push_back(p);
}
c_min = PM.front().first;
c_max = PM.back().first;
}
distance_type distance_sp(string_type const &text)
{
auto& w = work.front();
w.reset();
w.VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
auto X = findValue(PM, c, zeroes).front() | w.VN;
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = (w.HP << 1) | 1;
w.VP = (w.HN << 1) | ~(X | w.D0);
w.VN = X & w.D0;
if(w.HP & sink){
++D;
}
else if(w.HN & sink){
--D;
}
}
return D;
}
distance_type distance_lp(string_type const &text)
{
constexpr bitvector_type msb = bitvector_type{1} << (bitWidth<bitvector_type>() - 1);
for(auto& w: work){
w.reset();
}
work.back().VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
const auto& PMc = findValue(PM, c, zeroes);
for(size_type r = 0; r < block_size; ++r){
auto& w = work[r];
auto X = PMc[r];
if(r > 0 && (work[r - 1].HN & msb)){
X |= 1;
}
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = w.HP << 1;
if(r == 0 || work[r - 1].HP & msb){
X |= 1;
}
w.VP = (w.HN << 1) | ~(X | w.D0);
if(r > 0 && (work[r - 1].HN & msb)){
w.VP |= 1;
}
w.VN = X & w.D0;
}
if(work.back().HP & sink){
++D;
}
else if(work.back().HN & sink){
--D;
}
}
return D;
}
distance_type distance(string_type const &text)
{
if(text.empty()){
return pattern_length;
}
else if(pattern_length == 0){
return text.size();
}
if(block_size == 1){
return distance_sp(text);
}
else{
return distance_lp(text);
}
}
};
}
#endif
<commit_msg>use std::copy<commit_after>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RESEMBLA_ELIMINATOR_HPP
#define RESEMBLA_ELIMINATOR_HPP
#include <string>
#include <vector>
#include <map>
#include "string_util.hpp"
namespace resembla {
template<typename string_type, typename bitvector_type = uint64_t>
struct Eliminator
{
using size_type = typename string_type::size_type;
using symbol_type = typename string_type::value_type;
using distance_type = int;
Eliminator(string_type const& pattern = string_type())
{
init(pattern);
}
void init(string_type const& pattern)
{
this->pattern = pattern;
if(pattern.empty()){
return;
}
pattern_length = pattern.size();
block_size = ((pattern_length - 1) >> bitOffset<bitvector_type>()) + 1;
rest_bits = pattern_length - (block_size - 1) * bitWidth<bitvector_type>();
sink = bitvector_type{1} << (rest_bits - 1);
constructPM();
zeroes.resize(block_size, 0);
work.resize(block_size);
VP0 = 0;
for(size_type i = 0; i < rest_bits; ++i){
VP0 |= bitvector_type{1} << i;
}
}
void operator()(std::vector<string_type>& candidates, size_type k, bool keep_tie = true)
{
using index_distance = std::pair<size_type, distance_type>;
// calculate scores
std::vector<index_distance> work(candidates.size());
for(size_type i = 0; i < work.size(); ++i){
work[i].first = i;
work[i].second = -distance(candidates[i]);
}
if(keep_tie){
// sort partially to obtain top-k elements
std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
}
else{
std::sort(std::begin(work), std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
// expand k so that work[l] < work[k] for all l > k
while(k < work.size() - 1 && work[k] == work[k + 1]){
++k;
}
}
// ensure that work[i].first < work[j].first if i < j < k
std::sort(std::begin(work), std::begin(work) + k,
[](const index_distance& a, const index_distance& b) -> bool{
return a.first < b.first;
});
#ifdef DEBUG
std::cerr << "narrow " << work.size() << " strings" << std::endl;
for(size_type i = 0; i < k; ++i){
std::cerr << cast_string<std::string>(candidates[work[i].first]) << ": " << work[i].second << std::endl;
}
#endif
// sort original list
for(size_type i = 0; i < k; ++i){
std::swap(candidates[i], candidates[work[i].first]);
}
candidates.erase(std::begin(candidates) + k, std::end(candidates));
}
protected:
string_type pattern;
size_type pattern_length;
symbol_type c_min, c_max;
size_type block_size;
size_type rest_bits;
bitvector_type sink;
std::vector<std::pair<symbol_type, std::vector<bitvector_type>>> PM;
std::vector<bitvector_type> zeroes;
struct WorkData
{
bitvector_type D0;
bitvector_type HP;
bitvector_type HN;
bitvector_type VP;
bitvector_type VN;
void reset()
{
D0 = HP = HN = VN = 0;
VP = ~(bitvector_type{0});
}
};
std::vector<WorkData> work;
bitvector_type VP0;
template<typename Integer> static constexpr int bitWidth()
{
return 8 * sizeof(Integer);
}
static constexpr int bitOffset(int w)
{
return w < 2 ? 0 : (bitOffset(w >> 1) + 1);
}
template<typename Integer> static constexpr int bitOffset()
{
return bitOffset(bitWidth<Integer>());
}
template<typename key_type, typename value_type>
const value_type& findValue(const std::vector<std::pair<key_type, value_type>>& data,
const key_type c, const value_type& default_value) const
{
if(c < c_min || c_max < c){
return default_value;
}
else if(c == c_min){
return PM.front().second;
}
else if(c == c_max){
return PM.back().second;
}
size_type l = 1, r = data.size() - 1;
while(r - l > 8){
auto i = (l + r) / 2;
if(data[i].first < c){
l = i + 1;
}
else if(data[i].first > c){
r = i;
}
else{
return data[i].second;
}
}
for(size_type i = l; i < r; ++i){
if(data[i].first == c){
return data[i].second;
}
}
return default_value;
}
void constructPM()
{
std::map<symbol_type, std::vector<bitvector_type>> PM_work;
for(size_type i = 0; i < block_size - 1; ++i){
for(size_type j = 0; j < bitWidth<bitvector_type>(); ++j){
if(PM_work[pattern[i * bitWidth<bitvector_type>() + j]].empty()){
PM_work[pattern[i * bitWidth<bitvector_type>() + j]].resize(block_size, 0);
}
PM_work[pattern[i * bitWidth<bitvector_type>() + j]][i] |= bitvector_type{1} << j;
}
}
for(size_type i = 0; i < rest_bits; ++i){
if(PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].empty()){
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].resize(block_size, 0);
}
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].back() |= bitvector_type{1} << i;
}
PM.resize(PM_work.size());
std::copy(PM_work.begin(), PM_work.end(), PM.begin());
c_min = PM.front().first;
c_max = PM.back().first;
}
distance_type distance_sp(string_type const &text)
{
auto& w = work.front();
w.reset();
w.VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
auto X = findValue(PM, c, zeroes).front() | w.VN;
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = (w.HP << 1) | 1;
w.VP = (w.HN << 1) | ~(X | w.D0);
w.VN = X & w.D0;
if(w.HP & sink){
++D;
}
else if(w.HN & sink){
--D;
}
}
return D;
}
distance_type distance_lp(string_type const &text)
{
constexpr bitvector_type msb = bitvector_type{1} << (bitWidth<bitvector_type>() - 1);
for(auto& w: work){
w.reset();
}
work.back().VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
const auto& PMc = findValue(PM, c, zeroes);
for(size_type r = 0; r < block_size; ++r){
auto& w = work[r];
auto X = PMc[r];
if(r > 0 && (work[r - 1].HN & msb)){
X |= 1;
}
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = w.HP << 1;
if(r == 0 || work[r - 1].HP & msb){
X |= 1;
}
w.VP = (w.HN << 1) | ~(X | w.D0);
if(r > 0 && (work[r - 1].HN & msb)){
w.VP |= 1;
}
w.VN = X & w.D0;
}
if(work.back().HP & sink){
++D;
}
else if(work.back().HN & sink){
--D;
}
}
return D;
}
distance_type distance(string_type const &text)
{
if(text.empty()){
return pattern_length;
}
else if(pattern_length == 0){
return text.size();
}
if(block_size == 1){
return distance_sp(text);
}
else{
return distance_lp(text);
}
}
};
}
#endif
<|endoftext|> |
<commit_before>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <strings.h>
#include "config.hpp"
#include "utils.hpp"
#include "event_queue.hpp"
// TODO: report event queue statistics.
void process_aio_notify(event_queue_t *self) {
int res;
eventfd_t nevents;
res = eventfd_read(self->aio_notify_fd, &nevents);
check("Could not read aio_notify_fd value", res != 0);
// TODO: we need an array allocator here
io_event *events = (io_event*)malloc(&self->allocator, sizeof(io_event) * nevents);
// Grab the events
nevents = io_getevents(self->aio_context, 1, 1, events, NULL);
check("Waiting for AIO event failed", nevents != 1);
// Process the events
for(int i = 0; i < nevents; i++) {
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_disk_event;
iocb *op = (iocb*)events[i].obj;
qevent.source = op->aio_fildes;
qevent.result = events[i].res;
qevent.buf = op->u.c.buf;
qevent.state = events[i].data;
if(op->aio_lio_opcode == IO_CMD_PREAD)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
free(&self->allocator, events[i].obj);
}
free(&self->allocator, events);
}
void* epoll_handler(void *arg) {
int res;
event_queue_t *self = (event_queue_t*)arg;
epoll_event events[MAX_IO_EVENT_PROCESSING_BATCH_SIZE];
do {
res = epoll_wait(self->epoll_fd, events, sizeof(events), -1);
// epoll_wait might return with EINTR in some cases (in
// particular under GDB), we just need to retry.
if(res == -1 && errno == EINTR) {
if(self->dying)
break;
else
continue;
}
check("Waiting for epoll events failed", res == -1);
for(int i = 0; i < res; i++) {
if(events[i].data.fd == self->aio_notify_fd) {
process_aio_notify(self);
continue;
}
if(events[i].events == EPOLLIN ||
events[i].events == EPOLLOUT)
{
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_sock_event;
qevent.source = events[i].data.fd;
qevent.state = events[i].data.ptr;
if(events[i].events & EPOLLIN)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
}
if(events[i].events == EPOLLRDHUP ||
events[i].events == EPOLLERR ||
events[i].events == EPOLLHUP) {
queue_forget_resource(self, events[i].data.fd);
close(events[i].data.fd);
}
}
} while(1);
return NULL;
}
void create_event_queue(event_queue_t *event_queue, int queue_id, event_handler_t event_handler,
worker_pool_t *parent_pool) {
int res;
event_queue->queue_id = queue_id;
event_queue->event_handler = event_handler;
event_queue->parent_pool = parent_pool;
event_queue->dying = false;
// Initialize the allocator
create_allocator(&event_queue->allocator, ALLOCATOR_WORKER_HEAP);
// Create aio context
event_queue->aio_context = 0;
res = io_setup(MAX_CONCURRENT_IO_REQUESTS, &event_queue->aio_context);
check("Could not setup aio context", res != 0);
// Create a poll fd
event_queue->epoll_fd = epoll_create(CONCURRENT_NETWORK_EVENTS_COUNT_HINT);
check("Could not create epoll fd", event_queue->epoll_fd == -1);
// Start the epoll thread
res = pthread_create(&event_queue->epoll_thread, NULL, epoll_handler, (void*)event_queue);
check("Could not create epoll thread", res != 0);
// Create aio notify fd
event_queue->aio_notify_fd = eventfd(0, 0);
check("Could not create aio notification fd", event_queue->aio_notify_fd == -1);
res = fcntl(event_queue->aio_notify_fd, F_SETFL, O_NONBLOCK);
check("Could not make aio notify socket non-blocking", res != 0);
queue_watch_resource(event_queue, event_queue->aio_notify_fd, eo_read, NULL);
// Set thread affinity
int ncpus = get_cpu_count();
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(queue_id % ncpus, &mask);
res = pthread_setaffinity_np(event_queue->epoll_thread, sizeof(cpu_set_t), &mask);
check("Could not set thread affinity", res != 0);
}
void destroy_event_queue(event_queue_t *event_queue) {
int res;
event_queue->dying = true;
// Kill the threads
res = pthread_kill(event_queue->epoll_thread, SIGTERM);
check("Could not send kill signal to epoll thread", res != 0);
// Wait for the threads to die
res = pthread_join(event_queue->epoll_thread, NULL);
check("Could not join with epoll thread", res != 0);
// Cleanup resources
close(event_queue->aio_notify_fd);
close(event_queue->epoll_fd);
io_destroy(event_queue->aio_context);
destroy_allocator(&event_queue->allocator);
}
void queue_watch_resource(event_queue_t *event_queue, resource_t resource,
event_op_t watch_mode, void *state) {
epoll_event event;
// only trigger if new events come in
event.events = EPOLLET;
if(watch_mode == eo_read)
event.events |= EPOLLIN;
else
event.events |= EPOLLOUT;
event.data.ptr = state;
event.data.fd = resource;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_ADD, resource, &event);
check("Could not pass socket to worker", res != 0);
}
void queue_forget_resource(event_queue_t *event_queue, resource_t resource) {
epoll_event event;
event.events = EPOLLIN;
event.data.ptr = NULL;
event.data.fd = resource;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_DEL, resource, &event);
check("Could remove socket from watching", res != 0);
}
<commit_msg>Removing general purpose allocator requirement from event_queue<commit_after>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <fcntl.h>
#include <unistd.h>
#include <sched.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <strings.h>
#include "config.hpp"
#include "utils.hpp"
#include "event_queue.hpp"
// TODO: report event queue statistics.
void process_aio_notify(event_queue_t *self) {
int res, nevents;
eventfd_t nevents_total;
res = eventfd_read(self->aio_notify_fd, &nevents_total);
check("Could not read aio_notify_fd value", res != 0);
// Note: O(1) array allocators are hard. To avoid all the
// complexity, we'll use a fixed sized array and call io_getevents
// multiple times if we have to (which should be very unlikely,
// anyway).
io_event events[MAX_IO_EVENT_PROCESSING_BATCH_SIZE];
do {
// Grab the events
nevents = io_getevents(self->aio_context, 1, MAX_IO_EVENT_PROCESSING_BATCH_SIZE,
events, NULL);
check("Waiting for AIO event failed", nevents < 1);
// Process the events
for(int i = 0; i < nevents; i++) {
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_disk_event;
iocb *op = (iocb*)events[i].obj;
qevent.source = op->aio_fildes;
qevent.result = events[i].res;
qevent.buf = op->u.c.buf;
qevent.state = events[i].data;
if(op->aio_lio_opcode == IO_CMD_PREAD)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
free(&self->allocator, events[i].obj);
}
nevents_total -= nevents;
} while(nevents_total > 0);
}
void* epoll_handler(void *arg) {
int res;
event_queue_t *self = (event_queue_t*)arg;
epoll_event events[MAX_IO_EVENT_PROCESSING_BATCH_SIZE];
do {
res = epoll_wait(self->epoll_fd, events, sizeof(events), -1);
// epoll_wait might return with EINTR in some cases (in
// particular under GDB), we just need to retry.
if(res == -1 && errno == EINTR) {
if(self->dying)
break;
else
continue;
}
check("Waiting for epoll events failed", res == -1);
for(int i = 0; i < res; i++) {
if(events[i].data.fd == self->aio_notify_fd) {
process_aio_notify(self);
continue;
}
if(events[i].events == EPOLLIN ||
events[i].events == EPOLLOUT)
{
if(self->event_handler) {
event_t qevent;
bzero((char*)&qevent, sizeof(qevent));
qevent.event_type = et_sock_event;
qevent.source = events[i].data.fd;
qevent.state = events[i].data.ptr;
if(events[i].events & EPOLLIN)
qevent.op = eo_read;
else
qevent.op = eo_write;
self->event_handler(self, &qevent);
}
}
if(events[i].events == EPOLLRDHUP ||
events[i].events == EPOLLERR ||
events[i].events == EPOLLHUP) {
queue_forget_resource(self, events[i].data.fd);
close(events[i].data.fd);
}
}
} while(1);
return NULL;
}
void create_event_queue(event_queue_t *event_queue, int queue_id, event_handler_t event_handler,
worker_pool_t *parent_pool) {
int res;
event_queue->queue_id = queue_id;
event_queue->event_handler = event_handler;
event_queue->parent_pool = parent_pool;
event_queue->dying = false;
// Initialize the allocator
create_allocator(&event_queue->allocator, ALLOCATOR_WORKER_HEAP);
// Create aio context
event_queue->aio_context = 0;
res = io_setup(MAX_CONCURRENT_IO_REQUESTS, &event_queue->aio_context);
check("Could not setup aio context", res != 0);
// Create a poll fd
event_queue->epoll_fd = epoll_create(CONCURRENT_NETWORK_EVENTS_COUNT_HINT);
check("Could not create epoll fd", event_queue->epoll_fd == -1);
// Start the epoll thread
res = pthread_create(&event_queue->epoll_thread, NULL, epoll_handler, (void*)event_queue);
check("Could not create epoll thread", res != 0);
// Create aio notify fd
event_queue->aio_notify_fd = eventfd(0, 0);
check("Could not create aio notification fd", event_queue->aio_notify_fd == -1);
res = fcntl(event_queue->aio_notify_fd, F_SETFL, O_NONBLOCK);
check("Could not make aio notify socket non-blocking", res != 0);
queue_watch_resource(event_queue, event_queue->aio_notify_fd, eo_read, NULL);
// Set thread affinity
int ncpus = get_cpu_count();
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(queue_id % ncpus, &mask);
res = pthread_setaffinity_np(event_queue->epoll_thread, sizeof(cpu_set_t), &mask);
check("Could not set thread affinity", res != 0);
}
void destroy_event_queue(event_queue_t *event_queue) {
int res;
event_queue->dying = true;
// Kill the threads
res = pthread_kill(event_queue->epoll_thread, SIGTERM);
check("Could not send kill signal to epoll thread", res != 0);
// Wait for the threads to die
res = pthread_join(event_queue->epoll_thread, NULL);
check("Could not join with epoll thread", res != 0);
// Cleanup resources
close(event_queue->aio_notify_fd);
close(event_queue->epoll_fd);
io_destroy(event_queue->aio_context);
destroy_allocator(&event_queue->allocator);
}
void queue_watch_resource(event_queue_t *event_queue, resource_t resource,
event_op_t watch_mode, void *state) {
epoll_event event;
// only trigger if new events come in
event.events = EPOLLET;
if(watch_mode == eo_read)
event.events |= EPOLLIN;
else
event.events |= EPOLLOUT;
event.data.ptr = state;
event.data.fd = resource;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_ADD, resource, &event);
check("Could not pass socket to worker", res != 0);
}
void queue_forget_resource(event_queue_t *event_queue, resource_t resource) {
epoll_event event;
event.events = EPOLLIN;
event.data.ptr = NULL;
event.data.fd = resource;
int res = epoll_ctl(event_queue->epoll_fd, EPOLL_CTL_DEL, resource, &event);
check("Could remove socket from watching", res != 0);
}
<|endoftext|> |
<commit_before>#include "grok/runner.h"
#include "grok/context.h"
#include "input/input-stream.h"
#include "input/readline.h"
#include "lexer/lexer.h"
#include "object/jsbasicobject.h"
#include "parser/parser.h"
#include "vm/codegen.h"
#include "vm/context.h"
#include "vm/instruction-list.h"
#include "vm/printer.h"
#include "vm/vm.h"
#include "common/colors.h"
#include <iostream>
#include <cerrno>
using namespace grok;
using namespace grok::vm;
using namespace grok::parser;
using namespace grok::input;
namespace grok {
int tab_completer(int count, int key)
{
ReadLineBuffer buffer;
auto temp = buffer.GetBuffer();
temp += ' ';
buffer.SetText(temp);
return 0;
}
int ExecuteAST(Context *ctx, std::ostream &os, std::shared_ptr<Expression> AST)
{
try {
CodeGenerator CG;
CG.Generate(AST.get());
auto IR = CG.GetIR();
if (!IR || IR->size() == 0)
return 0;
if (ctx->DebugInstruction()) {
Printer P{ os };
P.Print(IR);
}
if (ctx->DryRun())
return 0;
auto TheVM = grok::vm::CreateVM(grok::vm::GetGlobalVMContext());
TheVM->SetCounters(IR->begin(), IR->end());
TheVM->Run();
Value Result = TheVM->GetResult();
auto O = GetObjectPointer<grok::obj::JSObject>(Result);
if (ctx->IsInteractive() || ctx->ShouldPrintLastInStack()) {
os << Color::Attr(Color::dim)
<< O->AsString() << Color::Reset() << std::endl;
} else {
return O->IsTrue();
}
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
int ExecuteFile(Context *ctx, const std::string &filename, std::ostream &os)
{
grok::vm::InitializeVMContext();
std::string v;
if (FILE *fp = fopen(filename.c_str(), "r"))
{
char buf[1024];
while (size_t len = fread(buf, 1, sizeof(buf), fp))
v.insert(v.end(), buf, buf + len);
fclose(fp);
} else {
std::cout << "fatal: " << filename << ": "
<< strerror(errno) << std::endl;
return -1;
}
auto lex = std::make_unique<Lexer>(v);
// create parser
grok::parser::GrokParser parser{ std::move(lex) };
auto result = parser.ParseExpression();
if (!result)
return -1;
if (ctx->PrintAST()) {
os << parser << std::endl;
}
auto AST = parser.ParsedAST();
return ExecuteAST(ctx, os, AST);
}
void ExecuteFiles(Context *ctx, std::ostream &os)
{
auto files = ctx->GetFiles();
for (auto file : files) {
ExecuteFile(ctx, file, os);
}
}
void InteractiveRun(Context *ctx)
{
grok::vm::InitializeVMContext();
ReadLine RL{"> "};
RL.BindKey('\t', tab_completer);
auto &os = ctx->GetOutputStream();
// main interpreter loop
while (true) {
auto str = RL.Read();
if (str == ".debug") {
ctx->SetDebugInstruction();
continue;
} else if (str == ".play") {
ctx->SetDebugExecution();
continue;
}
if (RL.Eof())
return;
auto lex = std::make_unique<Lexer>(str);
GrokParser parser{ std::move(lex) };
auto result = parser.ParseExpression();
if (!result)
continue;
if (ctx->PrintAST()) {
os << parser << std::endl;
}
auto AST = parser.ParsedAST();
ExecuteAST(ctx, os, AST);
}
}
int Start()
{
auto ctx = GetContext();
if (ctx->InputViaFile())
ExecuteFiles(ctx, ctx->GetOutputStream());
else
InteractiveRun(ctx);
return 0;
}
}
<commit_msg>Tab press should produce \\t<commit_after>#include "grok/runner.h"
#include "grok/context.h"
#include "input/input-stream.h"
#include "input/readline.h"
#include "lexer/lexer.h"
#include "object/jsbasicobject.h"
#include "parser/parser.h"
#include "vm/codegen.h"
#include "vm/context.h"
#include "vm/instruction-list.h"
#include "vm/printer.h"
#include "vm/vm.h"
#include "common/colors.h"
#include <iostream>
#include <cerrno>
using namespace grok;
using namespace grok::vm;
using namespace grok::parser;
using namespace grok::input;
namespace grok {
int tab_completer(int count, int key)
{
ReadLineBuffer buffer;
auto temp = buffer.GetBuffer();
temp += '\t';
buffer.SetText(temp);
return 0;
}
int ExecuteAST(Context *ctx, std::ostream &os, std::shared_ptr<Expression> AST)
{
try {
CodeGenerator CG;
CG.Generate(AST.get());
auto IR = CG.GetIR();
if (!IR || IR->size() == 0)
return 0;
if (ctx->DebugInstruction()) {
Printer P{ os };
P.Print(IR);
}
if (ctx->DryRun())
return 0;
auto TheVM = grok::vm::CreateVM(grok::vm::GetGlobalVMContext());
TheVM->SetCounters(IR->begin(), IR->end());
TheVM->Run();
Value Result = TheVM->GetResult();
auto O = GetObjectPointer<grok::obj::JSObject>(Result);
if (ctx->IsInteractive() || ctx->ShouldPrintLastInStack()) {
os << Color::Attr(Color::dim)
<< O->AsString() << Color::Reset() << std::endl;
} else {
return O->IsTrue();
}
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
int ExecuteFile(Context *ctx, const std::string &filename, std::ostream &os)
{
grok::vm::InitializeVMContext();
std::string v;
if (FILE *fp = fopen(filename.c_str(), "r"))
{
char buf[1024];
while (size_t len = fread(buf, 1, sizeof(buf), fp))
v.insert(v.end(), buf, buf + len);
fclose(fp);
} else {
std::cout << "fatal: " << filename << ": "
<< strerror(errno) << std::endl;
return -1;
}
auto lex = std::make_unique<Lexer>(v);
// create parser
grok::parser::GrokParser parser{ std::move(lex) };
auto result = parser.ParseExpression();
if (!result)
return -1;
if (ctx->PrintAST()) {
os << parser << std::endl;
}
auto AST = parser.ParsedAST();
return ExecuteAST(ctx, os, AST);
}
void ExecuteFiles(Context *ctx, std::ostream &os)
{
auto files = ctx->GetFiles();
for (auto file : files) {
ExecuteFile(ctx, file, os);
}
}
void InteractiveRun(Context *ctx)
{
grok::vm::InitializeVMContext();
ReadLine RL{"> "};
RL.BindKey('\t', tab_completer);
auto &os = ctx->GetOutputStream();
// main interpreter loop
while (true) {
auto str = RL.Read();
if (str == ".debug") {
ctx->SetDebugInstruction();
continue;
} else if (str == ".play") {
ctx->SetDebugExecution();
continue;
}
if (RL.Eof())
return;
auto lex = std::make_unique<Lexer>(str);
GrokParser parser{ std::move(lex) };
auto result = parser.ParseExpression();
if (!result)
continue;
if (ctx->PrintAST()) {
os << parser << std::endl;
}
auto AST = parser.ParsedAST();
ExecuteAST(ctx, os, AST);
}
}
int Start()
{
auto ctx = GetContext();
if (ctx->InputViaFile())
ExecuteFiles(ctx, ctx->GetOutputStream());
else
InteractiveRun(ctx);
return 0;
}
}
<|endoftext|> |
<commit_before>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* ------------------------------------------------------------------------ */
#include <limits.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include "Group.h"
#include "Nebula.h"
const char * Group::table = "group_pool";
const char * Group::db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * Group::db_bootstrap = "CREATE TABLE IF NOT EXISTS group_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ************************************************************************ */
/* Group :: Database Access Functions */
/* ************************************************************************ */
int Group::select(SqlDB * db)
{
int rc;
rc = PoolObjectSQL::select(db);
if ( rc != 0 )
{
return rc;
}
return quota.select(oid, db);
}
/* -------------------------------------------------------------------------- */
int Group::select(SqlDB * db, const string& name, int uid)
{
int rc;
rc = PoolObjectSQL::select(db,name,uid);
if ( rc != 0 )
{
return rc;
}
return quota.select(oid, db);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Group::drop(SqlDB * db)
{
int rc;
rc = PoolObjectSQL::drop(db);
if ( rc == 0 )
{
rc += quota.drop(db);
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Group::insert(SqlDB *db, string& error_str)
{
int rc;
rc = insert_replace(db, false, error_str);
if (rc == 0)
{
rc = quota.insert(oid, db, error_str);
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Group::insert_replace(SqlDB *db, bool replace, string& error_str)
{
ostringstream oss;
int rc;
string xml_body;
char * sql_name;
char * sql_xml;
// Set oneadmin as the owner
set_user(0,"");
// Set the Group ID as the group it belongs to
set_group(oid, name);
// Update the Group
sql_name = db->escape_str(name.c_str());
if ( sql_name == 0 )
{
goto error_name;
}
sql_xml = db->escape_str(to_xml(xml_body).c_str());
if ( sql_xml == 0 )
{
goto error_body;
}
if ( validate_xml(sql_xml) != 0 )
{
goto error_xml;
}
if ( replace )
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<<table <<" ("<< db_names <<") VALUES ("
<< oid << ","
<< "'" << sql_name << "',"
<< "'" << sql_xml << "',"
<< uid << ","
<< gid << ","
<< owner_u << ","
<< group_u << ","
<< other_u << ")";
rc = db->exec(oss);
db->free_str(sql_name);
db->free_str(sql_xml);
return rc;
error_xml:
db->free_str(sql_name);
db->free_str(sql_xml);
error_str = "Error transforming the Group to XML.";
goto error_common;
error_body:
db->free_str(sql_name);
goto error_generic;
error_name:
goto error_generic;
error_generic:
error_str = "Error inserting Group in DB.";
error_common:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Group::to_xml(string& xml) const
{
return to_xml_extended(xml, false);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Group::to_xml_extended(string& xml) const
{
return to_xml_extended(xml, true);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Group::to_xml_extended(string& xml, bool extended) const
{
ostringstream oss;
string collection_xml;
set<pair<int,int> >::const_iterator it;
ObjectCollection::to_xml(collection_xml);
oss <<
"<GROUP>" <<
"<ID>" << oid << "</ID>" <<
"<NAME>" << name << "</NAME>" <<
collection_xml;
for (it = providers.begin(); it != providers.end(); it++)
{
oss <<
"<RESOURCE_PROVIDER>" <<
"<ZONE_ID>" << it->first << "</ZONE_ID>" <<
"<CLUSTER_ID>" << it->second << "</CLUSTER_ID>" <<
"</RESOURCE_PROVIDER>";
}
if (extended)
{
string quota_xml;
string def_quota_xml;
oss << quota.to_xml(quota_xml)
<< Nebula::instance().get_default_group_quota().to_xml(def_quota_xml);
}
oss << "</GROUP>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Group::from_xml(const string& xml)
{
int rc = 0;
vector<xmlNodePtr> content;
vector<xmlNodePtr>::iterator it;
// Initialize the internal XML object
update_from_str(xml);
// Get class base attributes
rc += xpath(oid, "/GROUP/ID", -1);
rc += xpath(name,"/GROUP/NAME", "not_found");
// Set oneadmin as the owner
set_user(0,"");
// Set the Group ID as the group it belongs to
set_group(oid, name);
// Set of IDs
ObjectXML::get_nodes("/GROUP/USERS", content);
if (content.empty())
{
return -1;
}
rc += ObjectCollection::from_xml_node(content[0]);
ObjectXML::free_nodes(content);
content.clear();
// Set of resource providers
ObjectXML::get_nodes("/GROUP/RESOURCE_PROVIDER", content);
for (it = content.begin(); it != content.end(); it++)
{
ObjectXML tmp_xml(*it);
int zone_id, cluster_id;
rc += tmp_xml.xpath(zone_id, "RESOURCE_PROVIDER/ZONE_ID", -1);
rc += tmp_xml.xpath(cluster_id, "RESOURCE_PROVIDER/CLUSTER_ID", -1);
providers.insert(pair<int,int>(zone_id, cluster_id));
}
ObjectXML::free_nodes(content);
content.clear();
if (rc != 0)
{
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Group::add_resource_provider(int zone_id, int cluster_id, string& error_msg)
{
pair<set<pair<int, int> >::iterator,bool> ret;
ret = providers.insert(pair<int,int>(zone_id, cluster_id));
if( !ret.second )
{
error_msg = "Resource provider is already assigned to this group";
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Group::del_resource_provider(int zone_id, int cluster_id, string& error_msg)
{
if( providers.erase(pair<int,int>(zone_id, cluster_id)) != 1 )
{
error_msg = "Resource provider is not assigned to this group";
return -1;
}
return 0;
}
<commit_msg>Feature #2565: Bug in group::from_xml<commit_after>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* ------------------------------------------------------------------------ */
#include <limits.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include "Group.h"
#include "Nebula.h"
const char * Group::table = "group_pool";
const char * Group::db_names =
"oid, name, body, uid, gid, owner_u, group_u, other_u";
const char * Group::db_bootstrap = "CREATE TABLE IF NOT EXISTS group_pool ("
"oid INTEGER PRIMARY KEY, name VARCHAR(128), body MEDIUMTEXT, uid INTEGER, "
"gid INTEGER, owner_u INTEGER, group_u INTEGER, other_u INTEGER, "
"UNIQUE(name))";
/* ************************************************************************ */
/* Group :: Database Access Functions */
/* ************************************************************************ */
int Group::select(SqlDB * db)
{
int rc;
rc = PoolObjectSQL::select(db);
if ( rc != 0 )
{
return rc;
}
return quota.select(oid, db);
}
/* -------------------------------------------------------------------------- */
int Group::select(SqlDB * db, const string& name, int uid)
{
int rc;
rc = PoolObjectSQL::select(db,name,uid);
if ( rc != 0 )
{
return rc;
}
return quota.select(oid, db);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Group::drop(SqlDB * db)
{
int rc;
rc = PoolObjectSQL::drop(db);
if ( rc == 0 )
{
rc += quota.drop(db);
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Group::insert(SqlDB *db, string& error_str)
{
int rc;
rc = insert_replace(db, false, error_str);
if (rc == 0)
{
rc = quota.insert(oid, db, error_str);
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Group::insert_replace(SqlDB *db, bool replace, string& error_str)
{
ostringstream oss;
int rc;
string xml_body;
char * sql_name;
char * sql_xml;
// Set oneadmin as the owner
set_user(0,"");
// Set the Group ID as the group it belongs to
set_group(oid, name);
// Update the Group
sql_name = db->escape_str(name.c_str());
if ( sql_name == 0 )
{
goto error_name;
}
sql_xml = db->escape_str(to_xml(xml_body).c_str());
if ( sql_xml == 0 )
{
goto error_body;
}
if ( validate_xml(sql_xml) != 0 )
{
goto error_xml;
}
if ( replace )
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<<table <<" ("<< db_names <<") VALUES ("
<< oid << ","
<< "'" << sql_name << "',"
<< "'" << sql_xml << "',"
<< uid << ","
<< gid << ","
<< owner_u << ","
<< group_u << ","
<< other_u << ")";
rc = db->exec(oss);
db->free_str(sql_name);
db->free_str(sql_xml);
return rc;
error_xml:
db->free_str(sql_name);
db->free_str(sql_xml);
error_str = "Error transforming the Group to XML.";
goto error_common;
error_body:
db->free_str(sql_name);
goto error_generic;
error_name:
goto error_generic;
error_generic:
error_str = "Error inserting Group in DB.";
error_common:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Group::to_xml(string& xml) const
{
return to_xml_extended(xml, false);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Group::to_xml_extended(string& xml) const
{
return to_xml_extended(xml, true);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Group::to_xml_extended(string& xml, bool extended) const
{
ostringstream oss;
string collection_xml;
set<pair<int,int> >::const_iterator it;
ObjectCollection::to_xml(collection_xml);
oss <<
"<GROUP>" <<
"<ID>" << oid << "</ID>" <<
"<NAME>" << name << "</NAME>" <<
collection_xml;
for (it = providers.begin(); it != providers.end(); it++)
{
oss <<
"<RESOURCE_PROVIDER>" <<
"<ZONE_ID>" << it->first << "</ZONE_ID>" <<
"<CLUSTER_ID>" << it->second << "</CLUSTER_ID>" <<
"</RESOURCE_PROVIDER>";
}
if (extended)
{
string quota_xml;
string def_quota_xml;
oss << quota.to_xml(quota_xml)
<< Nebula::instance().get_default_group_quota().to_xml(def_quota_xml);
}
oss << "</GROUP>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Group::from_xml(const string& xml)
{
int rc = 0;
vector<xmlNodePtr> content;
vector<xmlNodePtr>::iterator it;
// Initialize the internal XML object
update_from_str(xml);
// Get class base attributes
rc += xpath(oid, "/GROUP/ID", -1);
rc += xpath(name,"/GROUP/NAME", "not_found");
// Set oneadmin as the owner
set_user(0,"");
// Set the Group ID as the group it belongs to
set_group(oid, name);
// Set of IDs
ObjectXML::get_nodes("/GROUP/USERS", content);
if (content.empty())
{
return -1;
}
rc += ObjectCollection::from_xml_node(content[0]);
ObjectXML::free_nodes(content);
content.clear();
// Set of resource providers
ObjectXML::get_nodes("/GROUP/RESOURCE_PROVIDER", content);
for (it = content.begin(); it != content.end(); it++)
{
ObjectXML tmp_xml(*it);
int zone_id, cluster_id;
rc += tmp_xml.xpath(zone_id, "/RESOURCE_PROVIDER/ZONE_ID", -1);
rc += tmp_xml.xpath(cluster_id, "/RESOURCE_PROVIDER/CLUSTER_ID", -1);
providers.insert(pair<int,int>(zone_id, cluster_id));
}
ObjectXML::free_nodes(content);
content.clear();
if (rc != 0)
{
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Group::add_resource_provider(int zone_id, int cluster_id, string& error_msg)
{
pair<set<pair<int, int> >::iterator,bool> ret;
ret = providers.insert(pair<int,int>(zone_id, cluster_id));
if( !ret.second )
{
error_msg = "Resource provider is already assigned to this group";
return -1;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Group::del_resource_provider(int zone_id, int cluster_id, string& error_msg)
{
if( providers.erase(pair<int,int>(zone_id, cluster_id)) != 1 )
{
error_msg = "Resource provider is not assigned to this group";
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "hash_reader.h"
#include <sys/mman.h>
#include <snappy.h>
#include <farmhash.h>
#include <glog/logging.h>
#include "scdb/writer.h"
#include "utils/varint.h"
#include "utils/timestamp.h"
#include "utils/file_stream.h"
namespace scdb {
class HashReader::Impl
{
public:
Impl(const Reader::Option& option, const std::string& fname)
: option_(option),
fd_(-1),
length_(0),
ptr_(NULL),
index_offset_(-1),
data_offset_(-1),
index_ptr_(NULL),
data_ptr_(NULL)
{
try
{
(void)option_;
FileInputStream is(fname);
char buf[7];
is.Read(buf, sizeof buf);
CHECK(strncmp(buf, "SCDBV1.", 7) == 0) << "Invalid Format: miss match format";
is.ReadInt64(); // create at
// Writer Option
is.Read(reinterpret_cast<char*>(&writer_option_.load_factor), sizeof(writer_option_.load_factor));
writer_option_.compress_type = is.ReadInt8();
writer_option_.build_type = is.ReadInt8();
writer_option_.with_checksum = is.ReadBool();
auto num_keys = is.ReadInt32();
auto num_key_length = is.ReadInt32();
auto max_key_length = is.ReadInt32();
LOG(INFO) << "num keys " << num_keys;
LOG(INFO) << "num key count " << num_key_length;
LOG(INFO) << "max key length " << max_key_length;
index_offsets_.resize(max_key_length+1, 0);
key_counts_.resize(max_key_length+1, 0);
slots_.resize(max_key_length+1, 0);
slots_size_.resize(max_key_length+1, 0);
if (writer_option_.build_type == 0)
{
data_offsets_.resize(max_key_length+1, 0);
}
int max_slot_size = 0;
for (int32_t i = 0;i < num_key_length; i++)
{
auto len = is.ReadInt32();
key_counts_[len] = is.ReadInt32();
slots_[len] = is.ReadInt32();
slots_size_[len] = is.ReadInt32();
index_offsets_[len] = is.ReadInt32();
if (writer_option_.build_type == 0)
{
data_offsets_[len] = is.ReadInt64();
}
max_slot_size = std::max(max_slot_size, slots_size_[len]);
}
slot_buf_.resize(max_slot_size);
index_offset_ = is.ReadInt32();
if (writer_option_.build_type == 0)
{
data_offset_ = is.ReadInt64();
}
}
catch (const std::exception& ex)
{
LOG(ERROR) << "HashReader ctor failed: " << ex.what();
throw;
}
fd_ = ::open(fname.c_str(), O_RDONLY);
CHECK(fd_) << "open " << fname << " failed";
FileUtil::GetFileSize(fname, &length_);
auto ptr_ = reinterpret_cast<char *>(::mmap(NULL, length_, PROT_READ, MAP_SHARED, fd_, 0));
//DCHECK(reinterpret_cast<int>(ptr_) != -1) << "mmap " << fname << " failed";
index_ptr_ = ptr_ + index_offset_;
if (writer_option_.build_type == 0)
{
data_ptr_ = ptr_ + data_offset_;
}
}
~Impl()
{
::munmap(ptr_, length_);
::close(fd_);
}
StringPiece GetInternal(const StringPiece& k) const
{
DCHECK(writer_option_.build_type == 0) << "Invalid Operation, No Value has been load!!!";
StringPiece result("");
if (writer_option_.build_type != 0)
{
return result;
}
auto len = k.length();
if (len > slots_.size() || key_counts_[len] == 0)
{
return result;
}
auto hash = util::Hash64(k.data(), k.length());
auto num_slots = slots_[len];
auto slot_size = slots_size_[len];
auto index_offset = index_offsets_[len];
auto data_offset = data_offsets_[len];
for (int32_t probe = 0;probe < num_slots; probe++)
{
auto slot = static_cast<int32_t>((hash + probe) % num_slots);
auto pos = index_ptr_ + index_offset + slot*slot_size;
memcpy(const_cast<char*>(&slot_buf_[0]), pos, slot_size);
if (strncmp(&slot_buf_[0], k.data(), len))
continue;
size_t offset_length = 0;
auto offset = DecodeVarint(slot_buf_, len, &offset_length);
if (offset == 0)
{
return result;
}
size_t prefix_length = 0;
auto block_ptr = reinterpret_cast<const int8_t*>(data_ptr_ + data_offset + offset);
auto value_length = DecodeVarint(block_ptr, block_ptr + 10, &prefix_length);
result.reset(reinterpret_cast<const char*>(block_ptr + prefix_length), value_length);
break;
}
return result;
}
StringPiece Get(const StringPiece& k) const
{
DCHECK(writer_option_.compress_type!=0) << "API Not Compressed Value, Use GetAsString() Instread!!!";
return GetInternal(k);
}
std::string GetAsString(const StringPiece& k) const
{
DCHECK(writer_option_.compress_type!=1) << "API Expect only use when value compressed!!!";
auto cv = GetInternal(k);
if (writer_option_.compress_type == 0)
{
return cv.ToString();
}
std::string ucv;
snappy::Uncompress(k.data(), k.length(), &ucv);
return ucv;
}
bool Exist(const StringPiece& k) const
{
auto len = k.length();
if (len > slots_.size() || key_counts_[len] == 0)
{
return false;
}
auto hash = util::Hash64(k.data(), k.length());
auto num_slots = slots_[len];
auto slot_size = slots_size_[len];
auto index_offset = index_offsets_[len];
for (int32_t probe = 0;probe < num_slots; probe++)
{
auto slot = static_cast<int32_t>((hash + probe) % num_slots);
auto pos = index_ptr_ + index_offset + slot*slot_size;
memcpy(const_cast<char*>(&slot_buf_[0]), pos, slot_size);
if (strncmp(&slot_buf_[0], k.data(), len) == 0)
{
return true;
}
}
return false;
}
private:
Reader::Option option_;
Writer::Option writer_option_;
int fd_;
uint64_t length_;
char* ptr_;
std::vector<int32_t> index_offsets_;
std::vector<int64_t> data_offsets_;
std::vector<int32_t> key_counts_;
std::vector<int32_t> slots_;
std::vector<int32_t> slots_size_;
mutable std::vector<char> slot_buf_;
int32_t index_offset_;
int64_t data_offset_;
const char* index_ptr_;
const char* data_ptr_;
};
HashReader::HashReader(const Reader::Option& option, const std::string& fname)
: impl_(new Impl(option, fname))
{
}
HashReader::~HashReader()
{
}
bool HashReader::Exist(const StringPiece& k) const
{
return impl_->Exist(k);
}
StringPiece HashReader::Get(const StringPiece& k) const
{
return impl_->Get(k);
}
std::string HashReader::GetAsString(const StringPiece& k) const
{
return impl_->GetAsString(k);
}
} // namespace
<commit_msg>remove extra memcpy<commit_after>#include "hash_reader.h"
#include <sys/mman.h>
#include <snappy.h>
#include <farmhash.h>
#include <glog/logging.h>
#include "scdb/writer.h"
#include "utils/varint.h"
#include "utils/timestamp.h"
#include "utils/file_stream.h"
namespace scdb {
class HashReader::Impl
{
public:
Impl(const Reader::Option& option, const std::string& fname)
: option_(option),
fd_(-1),
length_(0),
ptr_(NULL),
index_offset_(-1),
data_offset_(-1),
index_ptr_(NULL),
data_ptr_(NULL)
{
try
{
(void)option_;
FileInputStream is(fname);
char buf[7];
is.Read(buf, sizeof buf);
CHECK(strncmp(buf, "SCDBV1.", 7) == 0) << "Invalid Format: miss match format";
is.ReadInt64(); // create at
// Writer Option
is.Read(reinterpret_cast<char*>(&writer_option_.load_factor), sizeof(writer_option_.load_factor));
writer_option_.compress_type = is.ReadInt8();
writer_option_.build_type = is.ReadInt8();
writer_option_.with_checksum = is.ReadBool();
auto num_keys = is.ReadInt32();
auto num_key_length = is.ReadInt32();
auto max_key_length = is.ReadInt32();
LOG(INFO) << "num keys " << num_keys;
LOG(INFO) << "num key count " << num_key_length;
LOG(INFO) << "max key length " << max_key_length;
index_offsets_.resize(max_key_length+1, 0);
key_counts_.resize(max_key_length+1, 0);
slots_.resize(max_key_length+1, 0);
slots_size_.resize(max_key_length+1, 0);
if (writer_option_.build_type == 0)
{
data_offsets_.resize(max_key_length+1, 0);
}
int max_slot_size = 0;
for (int32_t i = 0;i < num_key_length; i++)
{
auto len = is.ReadInt32();
key_counts_[len] = is.ReadInt32();
slots_[len] = is.ReadInt32();
slots_size_[len] = is.ReadInt32();
index_offsets_[len] = is.ReadInt32();
if (writer_option_.build_type == 0)
{
data_offsets_[len] = is.ReadInt64();
}
max_slot_size = std::max(max_slot_size, slots_size_[len]);
}
index_offset_ = is.ReadInt32();
if (writer_option_.build_type == 0)
{
data_offset_ = is.ReadInt64();
}
}
catch (const std::exception& ex)
{
LOG(ERROR) << "HashReader ctor failed: " << ex.what();
throw;
}
fd_ = ::open(fname.c_str(), O_RDONLY);
CHECK(fd_) << "open " << fname << " failed";
FileUtil::GetFileSize(fname, &length_);
auto ptr_ = reinterpret_cast<char *>(::mmap(NULL, length_, PROT_READ, MAP_SHARED, fd_, 0));
//DCHECK(reinterpret_cast<int>(ptr_) != -1) << "mmap " << fname << " failed";
index_ptr_ = ptr_ + index_offset_;
if (writer_option_.build_type == 0)
{
data_ptr_ = ptr_ + data_offset_;
}
}
~Impl()
{
::munmap(ptr_, length_);
::close(fd_);
}
bool IsNoDataSection() const
{
if (writer_option_.build_type == 1)
return true;
return false;
}
StringPiece GetInternal(const StringPiece& k) const
{
DCHECK(!IsNoDataSection()) << "Invalid Operation, No Value has been load!!!";
StringPiece result("");
if (IsNoDataSection())
{
return result;
}
auto len = k.length();
if (len > slots_.size() || key_counts_[len] == 0)
{
return result;
}
auto hash = util::Hash64(k.data(), k.length());
auto num_slots = slots_[len];
auto slot_size = slots_size_[len];
auto index_offset = index_offsets_[len];
auto data_offset = data_offsets_[len];
for (int32_t probe = 0;probe < num_slots; probe++)
{
auto slot = static_cast<int32_t>((hash + probe) % num_slots);
auto pos = index_ptr_ + index_offset + slot*slot_size;
if (strncmp(pos, k.data(), len))
continue;
size_t offset_length = 0;
auto offset = DecodeVarint(reinterpret_cast<const int8_t*>(pos+len),
reinterpret_cast<const int8_t*>(pos+len+10),
&offset_length);
if (offset == 0)
{
return result;
}
size_t prefix_length = 0;
auto block_ptr = reinterpret_cast<const int8_t*>(data_ptr_ + data_offset + offset);
auto value_length = DecodeVarint(block_ptr, block_ptr + 10, &prefix_length);
result.reset(reinterpret_cast<const char*>(block_ptr + prefix_length), value_length);
break;
}
return result;
}
StringPiece Get(const StringPiece& k) const
{
DCHECK(writer_option_.compress_type) << "API Not Compressed Value, Use GetAsString() Instread!!!";
return GetInternal(k);
}
std::string GetAsString(const StringPiece& k) const
{
DCHECK(!writer_option_.compress_type) << "API Expect only use when value compressed!!!";
auto cv = GetInternal(k);
if (writer_option_.compress_type == 0)
{
return cv.ToString();
}
std::string ucv;
snappy::Uncompress(k.data(), k.length(), &ucv);
return ucv;
}
bool Exist(const StringPiece& k) const
{
auto len = k.length();
if (len > slots_.size() || key_counts_[len] == 0)
{
return false;
}
auto hash = util::Hash64(k.data(), k.length());
auto num_slots = slots_[len];
auto slot_size = slots_size_[len];
auto index_offset = index_offsets_[len];
for (int32_t probe = 0;probe < num_slots; probe++)
{
auto slot = static_cast<int32_t>((hash + probe) % num_slots);
auto pos = index_ptr_ + index_offset + slot*slot_size;
if (strncmp(pos, k.data(), len) == 0)
{
return true;
}
}
return false;
}
private:
Reader::Option option_;
Writer::Option writer_option_;
int fd_;
uint64_t length_;
char* ptr_;
std::vector<int32_t> index_offsets_;
std::vector<int64_t> data_offsets_;
std::vector<int32_t> key_counts_;
std::vector<int32_t> slots_;
std::vector<int32_t> slots_size_;
int32_t index_offset_;
int64_t data_offset_;
const char* index_ptr_;
const char* data_ptr_;
};
HashReader::HashReader(const Reader::Option& option, const std::string& fname)
: impl_(new Impl(option, fname))
{
}
HashReader::~HashReader()
{
}
bool HashReader::Exist(const StringPiece& k) const
{
return impl_->Exist(k);
}
StringPiece HashReader::Get(const StringPiece& k) const
{
return impl_->Get(k);
}
std::string HashReader::GetAsString(const StringPiece& k) const
{
return impl_->GetAsString(k);
}
} // namespace
<|endoftext|> |
<commit_before>/* Copyright (c) 2012 Ben Noordhuis <info@bnoordhuis.nl>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "http_parser.h"
#include "node_buffer.h"
#include "node.h"
#include "v8.h"
#include <stdlib.h>
#include <assert.h>
#define offset_of(type, member) \
((intptr_t) ((char *) &(((type *) 256)->member) - 256))
#define container_of(ptr, type, member) \
((type *) ((char *) (ptr) - offset_of(type, member)))
#define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
#define THROW(s) ThrowException(Exception::Error(String::New(s)))
#define HTTP_CB_DATA_MAP(X) \
X(1, on_url) \
X(2, on_header_field) \
X(3, on_header_value) \
X(5, on_body)
#define HTTP_CB_NODATA_MAP(X) \
X(0, on_message_begin) \
X(4, on_headers_complete) \
X(6, on_message_complete)
#define HTTP_CB_MAP(X) \
HTTP_CB_NODATA_MAP(X) \
HTTP_CB_DATA_MAP(X)
using namespace v8;
namespace
{
struct Parser: public node::ObjectWrap
{
Persistent<Function> callbacks_[7];
Persistent<Object> target_;
Handle<Object> buffer_;
http_parser parser_;
virtual ~Parser();
static Handle<Value> New(const Arguments& args);
};
http_parser_settings settings;
Persistent<FunctionTemplate> clazz;
#define X(num, name) Persistent<String> name##_sym;
HTTP_CB_MAP(X)
#undef X
Parser::~Parser() {
#define X(num, name) \
callbacks_[num].Clear(); \
callbacks_[num].Dispose();
HTTP_CB_MAP(X)
#undef X
}
template <int num>
static int http_cb(http_parser* parser)
{
Parser* self = container_of(parser, Parser, parser_);
Handle<Function> cb = self->callbacks_[num];
if (cb.IsEmpty()) return 0;
HandleScope scope;
TryCatch tc;
Handle<Value> argv[] = { self->handle_ };
Local<Value> r = cb->Call(self->target_, ARRAY_SIZE(argv), argv);
if (tc.HasCaught()) node::FatalException(tc);
if (r.IsEmpty()) return -1;
return r->Int32Value();
}
template <int num>
static int http_cb(http_parser* parser, const char* data, size_t size)
{
Parser* self = container_of(parser, Parser, parser_);
assert(!self->buffer_.IsEmpty());
Handle<Function> cb = self->callbacks_[num];
if (cb.IsEmpty()) return 0;
HandleScope scope;
const char* buf = node::Buffer::Data(self->buffer_);
size_t buflen = node::Buffer::Length(self->buffer_);
assert(data >= buf);
assert(data + size <= buf + buflen);
Handle<Value> argv[] = {
self->handle_,
self->buffer_,
Integer::NewFromUnsigned(data - buf),
Integer::NewFromUnsigned(size)
};
TryCatch tc;
Local<Value> r = cb->Call(self->target_, ARRAY_SIZE(argv), argv);
if (tc.HasCaught()) node::FatalException(tc);
if (r.IsEmpty()) return -1;
return r->Int32Value();
}
void Rebind(Parser* self, Handle<Value> val)
{
self->target_ = Persistent<Object>::New(val->ToObject());
#define X(num, name) \
do { \
Local<Value> val = self->target_->Get(name##_sym); \
if (val->IsFunction()) \
self->callbacks_[num] = Persistent<Function>::New(val.As<Function>()); \
else \
self->callbacks_[num].Clear(); \
} \
while (0);
HTTP_CB_MAP(X)
#undef X
}
Handle<Value> Parser::New(const Arguments& args)
{
HandleScope scope;
assert(args.IsConstructCall());
if (!args[0]->IsObject()) return THROW("Argument must be an object");
Parser* self = new Parser;
self->Wrap(args.This());
http_parser_type type = static_cast<http_parser_type>(args[1]->Uint32Value());
http_parser_init(&self->parser_, type);
Rebind(self, args[0]);
return scope.Close(self->handle_);
}
#define UNWRAP() \
assert(clazz->HasInstance(args.This())); \
Parser* self = static_cast<Parser*>( \
args.This()->GetPointerFromInternalField(0));
Handle<Value> Execute(const Arguments& args)
{
UNWRAP();
HandleScope scope;
Local<Object> obj = args[0]->ToObject();
const char* buf = node::Buffer::Data(obj);
size_t buflen = node::Buffer::Length(obj);
size_t start = args[1]->Uint32Value();
size_t len = args[2]->Uint32Value();
if (start >= buflen || start + len > buflen || start > start + len)
return THROW("Out of bounds");
self->buffer_ = obj;
size_t r = http_parser_execute(&self->parser_, &settings, buf + start, len);
self->buffer_.Clear();
return scope.Close(Integer::NewFromUnsigned(r));
}
template <int action>
Handle<Value> Pause(const Arguments& args)
{
UNWRAP();
http_parser_pause(&self->parser_, action);
return Undefined();
}
Handle<Value> Rebind(const Arguments& args)
{
HandleScope scope;
if (!args[0]->IsObject()) return THROW("Argument must be an object");
UNWRAP();
Rebind(self, args[0]);
return Undefined();
}
Handle<Value> Reset(const Arguments& args)
{
UNWRAP();
http_parser_type type = static_cast<http_parser_type>(args[0]->Uint32Value());
http_parser_init(&self->parser_, type);
return Undefined();
}
Handle<Value> StrError(const Arguments& args)
{
HandleScope scope;
switch (args[0]->Int32Value()) {
#define X(code, err) case HPE_##code: return scope.Close(String::New(#err));
HTTP_ERRNO_MAP(X)
#undef X
}
return scope.Close(String::New("unknown error"));
}
#define X(name) \
Handle<Value> name##_prop(Local<String> name, const AccessorInfo& args) \
{ \
HandleScope scope; \
UNWRAP(); \
return scope.Close(Integer::New(self->parser_.name)); \
}
X(http_major)
X(http_minor)
X(status_code)
X(method)
X(http_errno)
X(upgrade)
#undef X
extern "C" void init(Handle<Object> obj)
{
HandleScope scope;
#define X(num, name) \
name##_sym = Persistent<String>::New(String::NewSymbol(#name)); \
settings.name = http_cb<num>;
HTTP_CB_MAP(X)
#undef X
Local<FunctionTemplate> t = FunctionTemplate::New(Parser::New);
clazz = Persistent<FunctionTemplate>::New(t);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(String::New("Parser"));
Local<ObjectTemplate> proto = t->PrototypeTemplate();
proto->SetInternalFieldCount(1);
proto->Set(String::New("execute"),
FunctionTemplate::New(Execute)->GetFunction());
proto->Set(String::New("pause"),
FunctionTemplate::New(Pause<1>)->GetFunction());
proto->Set(String::New("unpause"),
FunctionTemplate::New(Pause<0>)->GetFunction());
proto->Set(String::New("rebind"),
FunctionTemplate::New(Rebind)->GetFunction());
proto->Set(String::New("reset"),
FunctionTemplate::New(Reset)->GetFunction());
#define X(name) proto->SetAccessor(String::New(#name), name##_prop);
X(http_major)
X(http_minor)
X(status_code)
X(method)
X(http_errno)
X(upgrade)
#undef X
#define X(num, name) \
obj->Set(String::NewSymbol("M_" # name), Integer::New(num));
HTTP_METHOD_MAP(X)
#undef X
obj->Set(String::NewSymbol("Parser"), t->GetFunction());
obj->Set(String::NewSymbol("HTTP_BOTH"), Integer::New(HTTP_BOTH));
obj->Set(String::NewSymbol("HTTP_REQUEST"), Integer::New(HTTP_REQUEST));
obj->Set(String::NewSymbol("HTTP_RESPONSE"), Integer::New(HTTP_RESPONSE));
obj->Set(String::NewSymbol("strerror"),
FunctionTemplate::New(StrError)->GetFunction());
}
} // anonymous namespace
<commit_msg>Expose HTTP errno enum.<commit_after>/* Copyright (c) 2012 Ben Noordhuis <info@bnoordhuis.nl>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "http_parser.h"
#include "node_buffer.h"
#include "node.h"
#include "v8.h"
#include <stdlib.h>
#include <assert.h>
#define offset_of(type, member) \
((intptr_t) ((char *) &(((type *) 256)->member) - 256))
#define container_of(ptr, type, member) \
((type *) ((char *) (ptr) - offset_of(type, member)))
#define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0]))
#define THROW(s) ThrowException(Exception::Error(String::New(s)))
#define HTTP_CB_DATA_MAP(X) \
X(1, on_url) \
X(2, on_header_field) \
X(3, on_header_value) \
X(5, on_body)
#define HTTP_CB_NODATA_MAP(X) \
X(0, on_message_begin) \
X(4, on_headers_complete) \
X(6, on_message_complete)
#define HTTP_CB_MAP(X) \
HTTP_CB_NODATA_MAP(X) \
HTTP_CB_DATA_MAP(X)
using namespace v8;
namespace
{
struct Parser: public node::ObjectWrap
{
Persistent<Function> callbacks_[7];
Persistent<Object> target_;
Handle<Object> buffer_;
http_parser parser_;
virtual ~Parser();
static Handle<Value> New(const Arguments& args);
};
http_parser_settings settings;
Persistent<FunctionTemplate> clazz;
#define X(num, name) Persistent<String> name##_sym;
HTTP_CB_MAP(X)
#undef X
Parser::~Parser() {
#define X(num, name) \
callbacks_[num].Clear(); \
callbacks_[num].Dispose();
HTTP_CB_MAP(X)
#undef X
}
template <int num>
static int http_cb(http_parser* parser)
{
Parser* self = container_of(parser, Parser, parser_);
Handle<Function> cb = self->callbacks_[num];
if (cb.IsEmpty()) return 0;
HandleScope scope;
TryCatch tc;
Handle<Value> argv[] = { self->handle_ };
Local<Value> r = cb->Call(self->target_, ARRAY_SIZE(argv), argv);
if (tc.HasCaught()) node::FatalException(tc);
if (r.IsEmpty()) return -1;
return r->Int32Value();
}
template <int num>
static int http_cb(http_parser* parser, const char* data, size_t size)
{
Parser* self = container_of(parser, Parser, parser_);
assert(!self->buffer_.IsEmpty());
Handle<Function> cb = self->callbacks_[num];
if (cb.IsEmpty()) return 0;
HandleScope scope;
const char* buf = node::Buffer::Data(self->buffer_);
size_t buflen = node::Buffer::Length(self->buffer_);
assert(data >= buf);
assert(data + size <= buf + buflen);
Handle<Value> argv[] = {
self->handle_,
self->buffer_,
Integer::NewFromUnsigned(data - buf),
Integer::NewFromUnsigned(size)
};
TryCatch tc;
Local<Value> r = cb->Call(self->target_, ARRAY_SIZE(argv), argv);
if (tc.HasCaught()) node::FatalException(tc);
if (r.IsEmpty()) return -1;
return r->Int32Value();
}
void Rebind(Parser* self, Handle<Value> val)
{
self->target_ = Persistent<Object>::New(val->ToObject());
#define X(num, name) \
do { \
Local<Value> val = self->target_->Get(name##_sym); \
if (val->IsFunction()) \
self->callbacks_[num] = Persistent<Function>::New(val.As<Function>()); \
else \
self->callbacks_[num].Clear(); \
} \
while (0);
HTTP_CB_MAP(X)
#undef X
}
Handle<Value> Parser::New(const Arguments& args)
{
HandleScope scope;
assert(args.IsConstructCall());
if (!args[0]->IsObject()) return THROW("Argument must be an object");
Parser* self = new Parser;
self->Wrap(args.This());
http_parser_type type = static_cast<http_parser_type>(args[1]->Uint32Value());
http_parser_init(&self->parser_, type);
Rebind(self, args[0]);
return scope.Close(self->handle_);
}
#define UNWRAP() \
assert(clazz->HasInstance(args.This())); \
Parser* self = static_cast<Parser*>( \
args.This()->GetPointerFromInternalField(0));
Handle<Value> Execute(const Arguments& args)
{
UNWRAP();
HandleScope scope;
Local<Object> obj = args[0]->ToObject();
const char* buf = node::Buffer::Data(obj);
size_t buflen = node::Buffer::Length(obj);
size_t start = args[1]->Uint32Value();
size_t len = args[2]->Uint32Value();
if (start >= buflen || start + len > buflen || start > start + len)
return THROW("Out of bounds");
self->buffer_ = obj;
size_t r = http_parser_execute(&self->parser_, &settings, buf + start, len);
self->buffer_.Clear();
return scope.Close(Integer::NewFromUnsigned(r));
}
template <int action>
Handle<Value> Pause(const Arguments& args)
{
UNWRAP();
http_parser_pause(&self->parser_, action);
return Undefined();
}
Handle<Value> Rebind(const Arguments& args)
{
HandleScope scope;
if (!args[0]->IsObject()) return THROW("Argument must be an object");
UNWRAP();
Rebind(self, args[0]);
return Undefined();
}
Handle<Value> Reset(const Arguments& args)
{
UNWRAP();
http_parser_type type = static_cast<http_parser_type>(args[0]->Uint32Value());
http_parser_init(&self->parser_, type);
return Undefined();
}
Handle<Value> StrError(const Arguments& args)
{
HandleScope scope;
switch (args[0]->Int32Value()) {
#define X(code, err) case HPE_##code: return scope.Close(String::New(#err));
HTTP_ERRNO_MAP(X)
#undef X
}
return scope.Close(String::New("unknown error"));
}
#define X(name) \
Handle<Value> name##_prop(Local<String> name, const AccessorInfo& args) \
{ \
HandleScope scope; \
UNWRAP(); \
return scope.Close(Integer::New(self->parser_.name)); \
}
X(http_major)
X(http_minor)
X(status_code)
X(method)
X(http_errno)
X(upgrade)
#undef X
extern "C" void init(Handle<Object> obj)
{
HandleScope scope;
#define X(num, name) \
name##_sym = Persistent<String>::New(String::NewSymbol(#name)); \
settings.name = http_cb<num>;
HTTP_CB_MAP(X)
#undef X
Local<FunctionTemplate> t = FunctionTemplate::New(Parser::New);
clazz = Persistent<FunctionTemplate>::New(t);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(String::New("Parser"));
Local<ObjectTemplate> proto = t->PrototypeTemplate();
proto->SetInternalFieldCount(1);
proto->Set(String::New("execute"),
FunctionTemplate::New(Execute)->GetFunction());
proto->Set(String::New("pause"),
FunctionTemplate::New(Pause<1>)->GetFunction());
proto->Set(String::New("unpause"),
FunctionTemplate::New(Pause<0>)->GetFunction());
proto->Set(String::New("rebind"),
FunctionTemplate::New(Rebind)->GetFunction());
proto->Set(String::New("reset"),
FunctionTemplate::New(Reset)->GetFunction());
#define X(name) proto->SetAccessor(String::New(#name), name##_prop);
X(http_major)
X(http_minor)
X(status_code)
X(method)
X(http_errno)
X(upgrade)
#undef X
#define X(num, name) \
obj->Set(String::NewSymbol("M_" # name), Integer::New(num));
HTTP_METHOD_MAP(X)
#undef X
#define X(code, msg) \
obj->Set(String::NewSymbol("E_" # code), Integer::New(HPE_##code));
HTTP_ERRNO_MAP(X)
#undef X
obj->Set(String::NewSymbol("Parser"), t->GetFunction());
obj->Set(String::NewSymbol("HTTP_BOTH"), Integer::New(HTTP_BOTH));
obj->Set(String::NewSymbol("HTTP_REQUEST"), Integer::New(HTTP_REQUEST));
obj->Set(String::NewSymbol("HTTP_RESPONSE"), Integer::New(HTTP_RESPONSE));
obj->Set(String::NewSymbol("strerror"),
FunctionTemplate::New(StrError)->GetFunction());
}
} // anonymous namespace
<|endoftext|> |
<commit_before><commit_msg>in singleArmFinalPosture return false if the target is unreacheable<commit_after><|endoftext|> |
<commit_before>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Infomap software package 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include "version.h"
namespace infomap {
const char* INFOMAP_VERSION = "1.0.0-beta.10";
}
<commit_msg>v1.0.0-beta.11<commit_after>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Infomap software package 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include "version.h"
namespace infomap {
const char* INFOMAP_VERSION = "1.0.0-beta.11";
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008 Larry Gritz
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// (this is the MIT license)
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include "imageviewer.h"
#include "strutil.h"
IvImage::IvImage (const std::string &filename)
: m_name(filename), m_pixels(NULL), m_thumbnail(NULL),
m_spec_valid(false), m_pixels_valid(false), m_thumbnail_valid(false),
m_badfile(false), m_gamma(1), m_exposure(0)
{
}
IvImage::~IvImage ()
{
delete [] m_pixels;
delete [] m_thumbnail;
}
bool
IvImage::init_spec (const std::string &filename)
{
m_name = filename;
ImageInput *in = ImageInput::create (filename.c_str(), "" /* searchpath */);
if (! in) {
std::cerr << OpenImageIO::error_message() << "\n";
}
if (in && in->open (filename.c_str(), m_spec)) {
in->close ();
m_badfile = false;
m_spec_valid = true;
} else {
m_badfile = true;
m_spec_valid = false;
delete in;
}
m_shortinfo.clear(); // invalidate info strings
m_longinfo.clear();
return !m_badfile;
}
bool
IvImage::read (bool force, OpenImageIO::ProgressCallback progress_callback,
void *progress_callback_data)
{
// Don't read if we already have it in memory, unless force is true.
// FIXME: should we also check the time on the file to see if it's
// been updated since we last loaded?
if (m_pixels && m_pixels_valid && !force)
return true;
// invalidate info strings
m_shortinfo.clear();
m_longinfo.clear();
// Find an ImageIO plugin that can open the input file, and open it.
boost::scoped_ptr<ImageInput> in (ImageInput::create (m_name.c_str(), "" /* searchpath */));
if (! in) {
m_err = OpenImageIO::error_message().c_str();
return false;
}
if (! in->open (m_name.c_str(), m_spec)) {
m_err = in->error_message();
return false;
}
delete [] m_pixels;
m_pixels = new char [m_spec.image_bytes()];
const OpenImageIO::stride_t as = OpenImageIO::AutoStride;
bool ok = in->read_image (m_spec.format, m_pixels, as, as, as,
progress_callback, progress_callback_data);
if (ok)
m_pixels_valid = true;
else {
m_err = in->error_message();
}
in->close ();
if (progress_callback)
progress_callback (progress_callback_data, 0);
return ok;
}
std::string
IvImage::shortinfo () const
{
if (m_shortinfo.empty()) {
m_shortinfo = Strutil::format ("%d x %d", m_spec.width, m_spec.height);
if (m_spec.depth > 1)
m_shortinfo += Strutil::format (" x %d", m_spec.depth);
m_shortinfo += Strutil::format (" x %d channel %s (%.2f MB)",
m_spec.nchannels,
ParamBaseTypeNameString(m_spec.format),
(float)m_spec.image_bytes() / (1024.0*1024.0));
}
return m_shortinfo;
}
// Format name/value pairs as HTML table entries.
static std::string
infoline (const char *name, const std::string &value)
{
std::string line = Strutil::format ("<tr><td><i>%s</i> : </td>",
name);
line += Strutil::format ("<td>%s</td></tr>\n", value.c_str());
return line;
}
static std::string
infoline (const char *name, int value)
{
return infoline (name, Strutil::format ("%d", value));
}
std::string
IvImage::longinfo () const
{
using Strutil::format; // shorthand
if (m_longinfo.empty()) {
m_longinfo += "<table>";
// m_longinfo += infoline (format("<b>%s</b>", m_name.c_str()).c_str(),
// std::string());
if (m_spec.depth <= 1)
m_longinfo += infoline ("Dimensions",
format ("%d x %d pixels", m_spec.width, m_spec.height));
else
m_longinfo += infoline ("Dimensions",
format ("%d x %d x %d pixels",
m_spec.width, m_spec.height, m_spec.depth));
m_longinfo += infoline ("Channels", m_spec.nchannels);
// FIXME: put all channel names in the table
m_longinfo += infoline ("Data format", ParamBaseTypeNameString(m_spec.format));
m_longinfo += infoline ("Data size",
format("%.2f MB", (float)m_spec.image_bytes() / (1024.0*1024.0)));
m_longinfo += infoline ("Image origin",
format ("%d, %d, %d", m_spec.x, m_spec.y, m_spec.z));
m_longinfo += infoline ("Full uncropped size",
format ("%d x %d x %d", m_spec.full_width, m_spec.full_height, m_spec.full_depth));
if (m_spec.tile_width)
m_longinfo += infoline ("Scanline/tile",
format ("tiled %d x %d x %d", m_spec.tile_width,
m_spec.tile_height, m_spec.tile_depth));
else
m_longinfo += infoline ("Scanline/tile", "scanline");
if (m_spec.alpha_channel >= 0)
m_longinfo += infoline ("Alpha channel", m_spec.alpha_channel);
if (m_spec.z_channel >= 0)
m_longinfo += infoline ("Depth (z) channel", m_spec.z_channel);
// gamma
// image format
BOOST_FOREACH (const ImageIOParameter &p, m_spec.extra_params) {
if (p.type == PT_STRING)
m_longinfo += infoline (p.name.c_str(), *(const char **)p.data());
else if (p.type == PT_FLOAT)
m_longinfo += infoline (p.name.c_str(), format("%g",*(const float *)p.data()));
else if (p.type == PT_INT)
m_longinfo += infoline (p.name.c_str(), *(const int *)p.data());
else if (p.type == PT_UINT)
m_longinfo += infoline (p.name.c_str(), format("%u",*(const unsigned int *)p.data()));
else
m_longinfo += infoline (p.name.c_str(), "<unknown data type>");
}
m_longinfo += "</table>";
}
return m_longinfo;
}
<commit_msg>Print actual channel names from the file instead of hard-coded ones<commit_after>/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008 Larry Gritz
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// (this is the MIT license)
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include "imageviewer.h"
#include "strutil.h"
IvImage::IvImage (const std::string &filename)
: m_name(filename), m_pixels(NULL), m_thumbnail(NULL),
m_spec_valid(false), m_pixels_valid(false), m_thumbnail_valid(false),
m_badfile(false), m_gamma(1), m_exposure(0)
{
}
IvImage::~IvImage ()
{
delete [] m_pixels;
delete [] m_thumbnail;
}
bool
IvImage::init_spec (const std::string &filename)
{
m_name = filename;
ImageInput *in = ImageInput::create (filename.c_str(), "" /* searchpath */);
if (! in) {
std::cerr << OpenImageIO::error_message() << "\n";
}
if (in && in->open (filename.c_str(), m_spec)) {
in->close ();
m_badfile = false;
m_spec_valid = true;
} else {
m_badfile = true;
m_spec_valid = false;
delete in;
}
m_shortinfo.clear(); // invalidate info strings
m_longinfo.clear();
return !m_badfile;
}
bool
IvImage::read (bool force, OpenImageIO::ProgressCallback progress_callback,
void *progress_callback_data)
{
// Don't read if we already have it in memory, unless force is true.
// FIXME: should we also check the time on the file to see if it's
// been updated since we last loaded?
if (m_pixels && m_pixels_valid && !force)
return true;
// invalidate info strings
m_shortinfo.clear();
m_longinfo.clear();
// Find an ImageIO plugin that can open the input file, and open it.
boost::scoped_ptr<ImageInput> in (ImageInput::create (m_name.c_str(), "" /* searchpath */));
if (! in) {
m_err = OpenImageIO::error_message().c_str();
return false;
}
if (! in->open (m_name.c_str(), m_spec)) {
m_err = in->error_message();
return false;
}
delete [] m_pixels;
m_pixels = new char [m_spec.image_bytes()];
const OpenImageIO::stride_t as = OpenImageIO::AutoStride;
bool ok = in->read_image (m_spec.format, m_pixels, as, as, as,
progress_callback, progress_callback_data);
if (ok)
m_pixels_valid = true;
else {
m_err = in->error_message();
}
in->close ();
if (progress_callback)
progress_callback (progress_callback_data, 0);
return ok;
}
std::string
IvImage::shortinfo () const
{
if (m_shortinfo.empty()) {
m_shortinfo = Strutil::format ("%d x %d", m_spec.width, m_spec.height);
if (m_spec.depth > 1)
m_shortinfo += Strutil::format (" x %d", m_spec.depth);
m_shortinfo += Strutil::format (" x %d channel %s (%.2f MB)",
m_spec.nchannels,
ParamBaseTypeNameString(m_spec.format),
(float)m_spec.image_bytes() / (1024.0*1024.0));
}
return m_shortinfo;
}
// Format name/value pairs as HTML table entries.
static std::string
infoline (const char *name, const std::string &value)
{
std::string line = Strutil::format ("<tr><td><i>%s</i> : </td>",
name);
line += Strutil::format ("<td>%s</td></tr>\n", value.c_str());
return line;
}
static std::string
infoline (const char *name, int value)
{
return infoline (name, Strutil::format ("%d", value));
}
std::string
IvImage::longinfo () const
{
using Strutil::format; // shorthand
if (m_longinfo.empty()) {
m_longinfo += "<table>";
// m_longinfo += infoline (format("<b>%s</b>", m_name.c_str()).c_str(),
// std::string());
if (m_spec.depth <= 1)
m_longinfo += infoline ("Dimensions",
format ("%d x %d pixels", m_spec.width, m_spec.height));
else
m_longinfo += infoline ("Dimensions",
format ("%d x %d x %d pixels",
m_spec.width, m_spec.height, m_spec.depth));
m_longinfo += infoline ("Channels", m_spec.nchannels);
std::string chanlist;
for (int i = 0; i < m_spec.nchannels; ++i) {
chanlist += m_spec.channelnames[i].c_str();
if (i != m_spec.nchannels-1)
chanlist += ", ";
}
m_longinfo += infoline ("Channel list", chanlist);
m_longinfo += infoline ("Data format", ParamBaseTypeNameString(m_spec.format));
m_longinfo += infoline ("Data size",
format("%.2f MB", (float)m_spec.image_bytes() / (1024.0*1024.0)));
m_longinfo += infoline ("Image origin",
format ("%d, %d, %d", m_spec.x, m_spec.y, m_spec.z));
m_longinfo += infoline ("Full uncropped size",
format ("%d x %d x %d", m_spec.full_width, m_spec.full_height, m_spec.full_depth));
if (m_spec.tile_width)
m_longinfo += infoline ("Scanline/tile",
format ("tiled %d x %d x %d", m_spec.tile_width,
m_spec.tile_height, m_spec.tile_depth));
else
m_longinfo += infoline ("Scanline/tile", "scanline");
if (m_spec.alpha_channel >= 0)
m_longinfo += infoline ("Alpha channel", m_spec.alpha_channel);
if (m_spec.z_channel >= 0)
m_longinfo += infoline ("Depth (z) channel", m_spec.z_channel);
// gamma
// image format
BOOST_FOREACH (const ImageIOParameter &p, m_spec.extra_params) {
if (p.type == PT_STRING)
m_longinfo += infoline (p.name.c_str(), *(const char **)p.data());
else if (p.type == PT_FLOAT)
m_longinfo += infoline (p.name.c_str(), format("%g",*(const float *)p.data()));
else if (p.type == PT_INT)
m_longinfo += infoline (p.name.c_str(), *(const int *)p.data());
else if (p.type == PT_UINT)
m_longinfo += infoline (p.name.c_str(), format("%u",*(const unsigned int *)p.data()));
else
m_longinfo += infoline (p.name.c_str(), "<unknown data type>");
}
m_longinfo += "</table>";
}
return m_longinfo;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 Tommi Maekitalo
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cxxtools/jsonparser.h>
#include <cxxtools/jsondeserializer.h>
#include <cxxtools/serializationerror.h>
#include <cxxtools/utf8codec.h>
#include <cxxtools/log.h>
#include <cctype>
#include <sstream>
log_define("cxxtools.json.parser")
namespace cxxtools
{
const char* JsonParserError::what() const throw()
{
if (_msg.empty())
{
try
{
std::ostringstream s;
s << "parsing json failed in line " << _lineNo << ": " << SerializationError::what();
_msg = s.str();
}
catch (...)
{
return SerializationError::what();
}
}
return _msg.c_str();
}
void JsonParser::doThrow(const std::string& msg)
{
throw JsonParserError(msg, _lineNo);
}
void JsonParser::throwInvalidCharacter(Char ch)
{
log_debug("invalid character '" << ch << "' in state " << _state);
doThrow((std::string("invalid character '") + ch.narrow() + '\''));
}
bool JsonParser::JsonStringParser::advance(Char ch)
{
switch (_state)
{
case state_0:
if (ch == '\\')
_state = state_esc;
else if (ch == '"')
return true;
else
_str += ch;
break;
case state_esc:
_state = state_0;
if (ch == '"' || ch == '\\' || ch == '/')
_str += ch;
else if (ch == 'b')
_str += '\b';
else if (ch == 'f')
_str += '\f';
else if (ch == 'n')
_str += '\n';
else if (ch == 'r')
_str += '\r';
else if (ch == 't')
_str += '\t';
else if (ch == 'u')
{
_value = 0;
_count = 4;
_state = state_hex;
}
else
_jsonParser->doThrow(std::string("invalid character '") + ch.narrow() + "' in string");
break;
case state_hex:
if (ch >= '0' && ch <= '9')
_value = (_value << 4) | (ch.value() - '0');
else if (ch >= 'a' && ch <= 'f')
_value = (_value << 4) | (ch.value() - 'a' + 10);
else if (ch >= 'A' && ch <= 'F')
_value = (_value << 4) | (ch.value() - 'A' + 10);
else
_jsonParser->doThrow(std::string("invalid character '") + ch.narrow() + "' in hex sequence");
if (--_count == 0)
{
_str += Char(static_cast<wchar_t>(_value));
_state = state_0;
}
break;
}
return false;
}
JsonParser::JsonParser()
: _deserializer(0),
_stringParser(this),
_next(0),
_lineNo(1)
{ }
JsonParser::~JsonParser()
{
delete _next;
}
int JsonParser::advance(Char ch)
{
int ret;
if (ch == '\n')
++_lineNo;
try
{
switch (_state)
{
case state_0:
if (ch == '{')
{
_state = state_object;
_deserializer->setCategory(SerializationInfo::Object);
}
else if (ch == '[')
{
_state = state_array;
_deserializer->setCategory(SerializationInfo::Array);
}
else if (ch == '"')
{
_state = state_string;
_deserializer->setCategory(SerializationInfo::Value);
}
else if ((ch >= '0' && ch <= '9') || ch == '+' || ch == '-')
{
_token = ch;
_state = state_number;
_deserializer->setCategory(SerializationInfo::Value);
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
{
_token = ch;
_state = state_token;
}
break;
case state_object:
if (ch == '"')
{
_state = state_object_name;
_stringParser.clear();
}
else if (ch == '}')
{
_state = state_end;
return 1;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (std::isalpha(ch.value()))
{
_token = ch;
_state = state_object_plainname;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_object_plainname:
if (std::isalnum(ch.value()) || ch == 'l')
_token += ch;
else if (std::isspace(ch.value()))
{
_stringParser.str(_token);
_state = state_object_after_name;
}
else if (ch == ':')
{
_stringParser.str(_token);
if (_next == 0)
_next = new JsonParser();
log_debug("begin object member " << _stringParser.str());
_deserializer->beginMember(Utf8Codec::encode(_stringParser.str()),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_stringParser.clear();
_state = state_object_value;
}
else
throwInvalidCharacter(ch);
break;
case state_object_name:
if (_stringParser.advance(ch))
_state = state_object_after_name;
break;
case state_object_after_name:
if (ch == ':')
{
if (_next == 0)
_next = new JsonParser();
log_debug("begin object member " << _stringParser.str());
_deserializer->beginMember(Utf8Codec::encode(_stringParser.str()),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_stringParser.clear();
_state = state_object_value;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_object_value:
ret = _next->advance(ch);
if (ret != 0)
{
log_debug("leave object member");
_deserializer->leaveMember();
_state = state_object_e;
}
if (ret != -1)
break;
case state_object_e:
if (ch == ',')
_state = state_object_next_member0;
else if (ch == '}')
{
_state = state_end;
return 1;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_object_next_member0:
if (ch == '}')
{
_state = state_end;
return 1;
}
else if (std::isspace(ch.value()))
{
return 0;
}
_state = state_object_next_member;
// no break
case state_object_next_member:
if (ch == '"')
{
_state = state_object_name;
_stringParser.clear();
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (std::isalpha(ch.value()))
{
_token = ch;
_state = state_object_plainname;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_array:
if (ch == ']')
{
_state = state_end;
return 1;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
{
if (_next == 0)
_next = new JsonParser();
log_debug("begin array member");
_deserializer->beginMember(std::string(),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_next->advance(ch);
_state = state_array_value;
}
break;
case state_array_value0:
if (ch == ']')
{
_state = state_end;
return 1;
}
else if (std::isspace(ch.value()))
{
return 0;
}
log_debug("begin array member");
_deserializer->beginMember(std::string(),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_state = state_array_value;
// no break
case state_array_value:
ret = _next->advance(ch);
if (ret != 0)
_state = state_array_e;
if (ret != -1)
break;
case state_array_e:
if (ch == ']')
{
log_debug("leave array member");
_deserializer->leaveMember();
_state = state_end;
return 1;
}
else if (ch == ',')
{
log_debug("leave array member");
_deserializer->leaveMember();
_state = state_array_value0;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_string:
if (_stringParser.advance(ch))
{
log_debug("set string value \"" << _stringParser.str() << '"');
_deserializer->setValue(_stringParser.str());
_deserializer->setTypeName("string");
_stringParser.clear();
_state = state_end;
return 1;
}
break;
case state_number:
if (std::isspace(ch.value()))
{
log_debug("set int value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("int");
_token.clear();
return 1;
}
else if (ch == '.' || ch == 'e' || ch == 'E')
{
_token += ch;
_state = state_float;
}
else if (ch >= '0' && ch <= '9')
{
_token += ch;
}
else
{
log_debug("set int value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("int");
_token.clear();
return -1;
}
break;
case state_float:
if (std::isspace(ch.value()))
{
log_debug("set double value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("double");
_token.clear();
return 1;
}
else if ((ch >= '0' && ch <= '9') || ch == '+' || ch == '-'
|| ch == '.' || ch == 'e' || ch == 'E')
_token += ch;
else
{
log_debug("set double value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("double");
_token.clear();
return -1;
}
break;
case state_token:
if (std::isalpha(ch.value()))
_token += Char(std::tolower(ch));
else
{
if (_token == "true" || _token == "false")
{
log_debug("set bool value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("bool");
_token.clear();
}
else if (_token == "null")
{
log_debug("set null value \"" << _token << '"');
_deserializer->setTypeName("null");
_deserializer->setNull();
_token.clear();
}
return -1;
}
break;
case state_comment0:
if (ch == '/')
_state = state_commentline;
else if (ch == '*')
_state = state_comment;
else
throwInvalidCharacter(ch);
break;
case state_commentline:
if (ch == '\n')
_state = _nextState;
break;
case state_comment:
if (ch == '*')
_state = state_comment_e;
break;
case state_comment_e:
if (ch == '/')
_state = _nextState;
else if (ch != '*')
_state = state_comment;
break;
case state_end:
if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
doThrow(std::string("unexpected character '") + ch.narrow() + "\' after end in json parser");
break;
}
}
catch (JsonParserError& e)
{
e._lineNo = _lineNo;
throw;
}
return 0;
}
void JsonParser::finish()
{
if (_state == state_commentline)
_state = _nextState;
switch (_state)
{
case state_0:
case state_object:
case state_object_plainname:
case state_object_name:
case state_object_after_name:
case state_object_value:
case state_object_e:
case state_object_next_member0:
case state_object_next_member:
case state_array:
case state_array_value0:
case state_array_value:
case state_array_e:
case state_string:
case state_comment0:
case state_commentline:
case state_comment:
case state_comment_e:
log_warn("unexpected end of json; state=" << _state);
SerializationError::doThrow("unexpected end of json");
case state_number:
_deserializer->setValue(_token);
_deserializer->setTypeName("int");
_token.clear();
break;
case state_float:
_deserializer->setValue(_token);
_deserializer->setTypeName("double");
_token.clear();
break;
case state_token:
if (_token == "true" || _token == "false")
{
_deserializer->setValue(_token);
_deserializer->setTypeName("bool");
_token.clear();
}
else if (_token == "null")
{
_deserializer->setTypeName("null");
_deserializer->setNull();
_token.clear();
}
break;
case state_end:
break;
}
}
}
<commit_msg>throw right exception type in json parser (JsonParserError instead of SerializationError)<commit_after>/*
* Copyright (C) 2011 Tommi Maekitalo
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cxxtools/jsonparser.h>
#include <cxxtools/jsondeserializer.h>
#include <cxxtools/serializationerror.h>
#include <cxxtools/utf8codec.h>
#include <cxxtools/log.h>
#include <cctype>
#include <sstream>
log_define("cxxtools.json.parser")
namespace cxxtools
{
const char* JsonParserError::what() const throw()
{
if (_msg.empty())
{
try
{
std::ostringstream s;
s << "parsing json failed in line " << _lineNo << ": " << SerializationError::what();
_msg = s.str();
}
catch (...)
{
return SerializationError::what();
}
}
return _msg.c_str();
}
void JsonParser::doThrow(const std::string& msg)
{
throw JsonParserError(msg, _lineNo);
}
void JsonParser::throwInvalidCharacter(Char ch)
{
log_debug("invalid character '" << ch << "' in state " << _state);
doThrow((std::string("invalid character '") + ch.narrow() + '\''));
}
bool JsonParser::JsonStringParser::advance(Char ch)
{
switch (_state)
{
case state_0:
if (ch == '\\')
_state = state_esc;
else if (ch == '"')
return true;
else
_str += ch;
break;
case state_esc:
_state = state_0;
if (ch == '"' || ch == '\\' || ch == '/')
_str += ch;
else if (ch == 'b')
_str += '\b';
else if (ch == 'f')
_str += '\f';
else if (ch == 'n')
_str += '\n';
else if (ch == 'r')
_str += '\r';
else if (ch == 't')
_str += '\t';
else if (ch == 'u')
{
_value = 0;
_count = 4;
_state = state_hex;
}
else
_jsonParser->doThrow(std::string("invalid character '") + ch.narrow() + "' in string");
break;
case state_hex:
if (ch >= '0' && ch <= '9')
_value = (_value << 4) | (ch.value() - '0');
else if (ch >= 'a' && ch <= 'f')
_value = (_value << 4) | (ch.value() - 'a' + 10);
else if (ch >= 'A' && ch <= 'F')
_value = (_value << 4) | (ch.value() - 'A' + 10);
else
_jsonParser->doThrow(std::string("invalid character '") + ch.narrow() + "' in hex sequence");
if (--_count == 0)
{
_str += Char(static_cast<wchar_t>(_value));
_state = state_0;
}
break;
}
return false;
}
JsonParser::JsonParser()
: _deserializer(0),
_stringParser(this),
_next(0),
_lineNo(1)
{ }
JsonParser::~JsonParser()
{
delete _next;
}
int JsonParser::advance(Char ch)
{
int ret;
if (ch == '\n')
++_lineNo;
try
{
switch (_state)
{
case state_0:
if (ch == '{')
{
_state = state_object;
_deserializer->setCategory(SerializationInfo::Object);
}
else if (ch == '[')
{
_state = state_array;
_deserializer->setCategory(SerializationInfo::Array);
}
else if (ch == '"')
{
_state = state_string;
_deserializer->setCategory(SerializationInfo::Value);
}
else if ((ch >= '0' && ch <= '9') || ch == '+' || ch == '-')
{
_token = ch;
_state = state_number;
_deserializer->setCategory(SerializationInfo::Value);
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
{
_token = ch;
_state = state_token;
}
break;
case state_object:
if (ch == '"')
{
_state = state_object_name;
_stringParser.clear();
}
else if (ch == '}')
{
_state = state_end;
return 1;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (std::isalpha(ch.value()))
{
_token = ch;
_state = state_object_plainname;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_object_plainname:
if (std::isalnum(ch.value()) || ch == 'l')
_token += ch;
else if (std::isspace(ch.value()))
{
_stringParser.str(_token);
_state = state_object_after_name;
}
else if (ch == ':')
{
_stringParser.str(_token);
if (_next == 0)
_next = new JsonParser();
log_debug("begin object member " << _stringParser.str());
_deserializer->beginMember(Utf8Codec::encode(_stringParser.str()),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_stringParser.clear();
_state = state_object_value;
}
else
throwInvalidCharacter(ch);
break;
case state_object_name:
if (_stringParser.advance(ch))
_state = state_object_after_name;
break;
case state_object_after_name:
if (ch == ':')
{
if (_next == 0)
_next = new JsonParser();
log_debug("begin object member " << _stringParser.str());
_deserializer->beginMember(Utf8Codec::encode(_stringParser.str()),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_stringParser.clear();
_state = state_object_value;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_object_value:
ret = _next->advance(ch);
if (ret != 0)
{
log_debug("leave object member");
_deserializer->leaveMember();
_state = state_object_e;
}
if (ret != -1)
break;
case state_object_e:
if (ch == ',')
_state = state_object_next_member0;
else if (ch == '}')
{
_state = state_end;
return 1;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_object_next_member0:
if (ch == '}')
{
_state = state_end;
return 1;
}
else if (std::isspace(ch.value()))
{
return 0;
}
_state = state_object_next_member;
// no break
case state_object_next_member:
if (ch == '"')
{
_state = state_object_name;
_stringParser.clear();
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (std::isalpha(ch.value()))
{
_token = ch;
_state = state_object_plainname;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_array:
if (ch == ']')
{
_state = state_end;
return 1;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
{
if (_next == 0)
_next = new JsonParser();
log_debug("begin array member");
_deserializer->beginMember(std::string(),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_next->advance(ch);
_state = state_array_value;
}
break;
case state_array_value0:
if (ch == ']')
{
_state = state_end;
return 1;
}
else if (std::isspace(ch.value()))
{
return 0;
}
log_debug("begin array member");
_deserializer->beginMember(std::string(),
std::string(), SerializationInfo::Void);
_next->begin(*_deserializer);
_state = state_array_value;
// no break
case state_array_value:
ret = _next->advance(ch);
if (ret != 0)
_state = state_array_e;
if (ret != -1)
break;
case state_array_e:
if (ch == ']')
{
log_debug("leave array member");
_deserializer->leaveMember();
_state = state_end;
return 1;
}
else if (ch == ',')
{
log_debug("leave array member");
_deserializer->leaveMember();
_state = state_array_value0;
}
else if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
throwInvalidCharacter(ch);
break;
case state_string:
if (_stringParser.advance(ch))
{
log_debug("set string value \"" << _stringParser.str() << '"');
_deserializer->setValue(_stringParser.str());
_deserializer->setTypeName("string");
_stringParser.clear();
_state = state_end;
return 1;
}
break;
case state_number:
if (std::isspace(ch.value()))
{
log_debug("set int value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("int");
_token.clear();
return 1;
}
else if (ch == '.' || ch == 'e' || ch == 'E')
{
_token += ch;
_state = state_float;
}
else if (ch >= '0' && ch <= '9')
{
_token += ch;
}
else
{
log_debug("set int value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("int");
_token.clear();
return -1;
}
break;
case state_float:
if (std::isspace(ch.value()))
{
log_debug("set double value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("double");
_token.clear();
return 1;
}
else if ((ch >= '0' && ch <= '9') || ch == '+' || ch == '-'
|| ch == '.' || ch == 'e' || ch == 'E')
_token += ch;
else
{
log_debug("set double value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("double");
_token.clear();
return -1;
}
break;
case state_token:
if (std::isalpha(ch.value()))
_token += Char(std::tolower(ch));
else
{
if (_token == "true" || _token == "false")
{
log_debug("set bool value \"" << _token << '"');
_deserializer->setValue(_token);
_deserializer->setTypeName("bool");
_token.clear();
}
else if (_token == "null")
{
log_debug("set null value \"" << _token << '"');
_deserializer->setTypeName("null");
_deserializer->setNull();
_token.clear();
}
return -1;
}
break;
case state_comment0:
if (ch == '/')
_state = state_commentline;
else if (ch == '*')
_state = state_comment;
else
throwInvalidCharacter(ch);
break;
case state_commentline:
if (ch == '\n')
_state = _nextState;
break;
case state_comment:
if (ch == '*')
_state = state_comment_e;
break;
case state_comment_e:
if (ch == '/')
_state = _nextState;
else if (ch != '*')
_state = state_comment;
break;
case state_end:
if (ch == '/')
{
_nextState = _state;
_state = state_comment0;
}
else if (!std::isspace(ch.value()))
doThrow(std::string("unexpected character '") + ch.narrow() + "\' after end in json parser");
break;
}
}
catch (JsonParserError& e)
{
e._lineNo = _lineNo;
throw;
}
return 0;
}
void JsonParser::finish()
{
if (_state == state_commentline)
_state = _nextState;
switch (_state)
{
case state_0:
case state_object:
case state_object_plainname:
case state_object_name:
case state_object_after_name:
case state_object_value:
case state_object_e:
case state_object_next_member0:
case state_object_next_member:
case state_array:
case state_array_value0:
case state_array_value:
case state_array_e:
case state_string:
case state_comment0:
case state_commentline:
case state_comment:
case state_comment_e:
log_warn("unexpected end of json; state=" << _state);
doThrow("unexpected end of json");
case state_number:
_deserializer->setValue(_token);
_deserializer->setTypeName("int");
_token.clear();
break;
case state_float:
_deserializer->setValue(_token);
_deserializer->setTypeName("double");
_token.clear();
break;
case state_token:
if (_token == "true" || _token == "false")
{
_deserializer->setValue(_token);
_deserializer->setTypeName("bool");
_token.clear();
}
else if (_token == "null")
{
_deserializer->setTypeName("null");
_deserializer->setNull();
_token.clear();
}
break;
case state_end:
break;
}
}
}
<|endoftext|> |
<commit_before>#include "sp_segmenter/klttracker.h"
#include <iostream>
#include <algorithm>
using namespace Eigen;
using namespace cv;
KLTTracker::KLTTracker(unsigned int max_kps)
{
m_nextID = 0;
m_maxNumberOfPoints = max_kps;
m_fastDetector = cv::FastFeatureDetector::create(std::string("FAST"));
}
unsigned int KLTTracker::getNumPointsTracked()
{
return m_ptIDs.size();
}
bool KLTTracker::hasTracking()
{
return m_ptIDs.size() > 0 && m_prevPts.size() > 0;
}
void KLTTracker::clear()
{
m_prevPts.clear();
m_nextPts.clear();
m_tracked3dPts.clear();
m_ptIDs.clear();
m_prevImg = Mat(0,0,CV_8UC1);
}
cv::Mat KLTTracker::getLastImage()
{
return m_prevImg;
}
std::vector<unsigned char> KLTTracker::filterMatchesEpipolarContraint(
const std::vector<cv::Point2f>& pts1,
const std::vector<cv::Point2f>& pts2)
{
std::vector<unsigned char> status;
findFundamentalMat(pts1, pts2, CV_FM_RANSAC, 3, .99, status);
return status;
}
void KLTTracker::initPointsAndFastforward(const std::vector<cv::Mat>& inputFrames, const cv::Mat& depth,
const Eigen::Matrix3f& K,
const Eigen::Matrix4f& inputTf, const cv::Mat& mask)
{
if(inputFrames.size() == 0)
{
std::cout << "KLTTracker: number of input frames = 0" << std::endl;
return;
}
if(m_ptIDs.size() == m_maxNumberOfPoints)
{
std::cout << "KLTTracker: Max keypoints reached" << std::endl;
return;
}
std::vector<cv::KeyPoint> detected_pts;
std::vector<cv::Point2f> new_pts;
std::vector<cv::Point3f> new_3d_pts;
// Detect new points
m_fastDetector->detect(inputFrames.at(0), detected_pts, mask);
std::sort(detected_pts.begin(), detected_pts.end(),
[](const cv::KeyPoint &a, const cv::KeyPoint& b) -> bool
{
return a.response > b.response;
}
);
//std::random_shuffle(detected_pts.begin(), detected_pts.end());
unsigned int num_new_pts = m_maxNumberOfPoints; //min(detected_pts.size(), m_maxNumberOfPoints - m_ptIDs.size());
std::cout << "detected " << num_new_pts << " new pts" << std::endl;
// Backproject points to 3D using depth data
// TODO: try with model instead???
for (size_t i=0; i<num_new_pts; i++)
{
Eigen::Vector3f hkp(detected_pts[i].pt.x, detected_pts[i].pt.y, 1);
// TODO: DOUBLE CHECK DEPTH IS IN METERS
double pt_depth = depth.at<float>(int(hkp(1)), int(hkp(0)));
if(pt_depth == 0 || pt_depth == -1 || std::isnan(pt_depth))
continue;
std::cout << pt_depth << std::endl;
Eigen::Vector3f backproj = K.inverse()*hkp;
backproj /= backproj(2);
backproj *= pt_depth;
Eigen::Vector4f backproj_h(backproj(0), backproj(1), backproj(2), 1);
backproj_h = inputTf*backproj_h;
new_3d_pts.push_back(Point3f(backproj_h(0), backproj_h(1), backproj_h(2)));
new_pts.push_back(detected_pts.at(i).pt);
}
std::cout << "backprojected " << new_pts.size() << " pts" << std::endl;
// Fastforward tracked points to current frame
std::vector<cv::Point2f> prev_pts = new_pts;
std::vector<cv::Point2f> next_pts;
std::vector<cv::Point3f> valid_3dpts;
std::vector<unsigned char> status;
for(unsigned int i = 1; i < inputFrames.size(); i++)
{
if(prev_pts.size() == 0)
{
std::cout << "KLTTracker: Fastforward failed" << std::endl;
break;
}
processFrameInternal(inputFrames.at(i-1), inputFrames.at(i), prev_pts, next_pts, status);
prev_pts.clear();
valid_3dpts.clear();
for(unsigned int j = 0; j < status.size(); j++)
{
if(status[j])
{
prev_pts.push_back(next_pts.at(j));
valid_3dpts.push_back(new_3d_pts.at(j));
}
}
//std::cout << "frame " << i << "/" << inputFrames.size() << " " << next_pts.size() << " pts"
// << std::endl;
new_3d_pts = valid_3dpts;
}
assert(new_3dpts.size() == prev_pts.size());
// Add prev image if initializing
if(m_prevImg.cols == 0)
m_prevImg = inputFrames.back();
// Add new points to tracker
std::cout <<"adding " << prev_pts.size() << " new pts" << std::endl;
m_tracked3dPts = new_3d_pts;
m_prevPts = prev_pts;
//m_tracked3dPts.insert(m_tracked3dPts.end(), new_3d_pts.begin(), new_3d_pts.end());
//m_prevPts.insert(m_prevPts.end(), prev_pts.begin(), prev_pts.end());
std::cout <<"pts_size=" << m_prevPts.size() << std::endl;
m_ptIDs.clear();
for(unsigned int i = 0; i < new_3d_pts.size(); i++)
{
m_ptIDs.push_back(m_nextID++);
}
}
bool KLTTracker::processFrameInternal(const cv::Mat& prev_image, const cv::Mat& next_image,
const std::vector<cv::Point2f>& prev_pts, std::vector<cv::Point2f>& next_pts,
std::vector<unsigned char>& status)
{
next_pts.clear();
status.clear();
std::vector<float> error;
if (prev_pts.size() > 0)
{
cv::calcOpticalFlowPyrLK(prev_image, next_image, prev_pts, next_pts, status, error);
}
else
{
std::cout << "prev_points.size()=0" << std::endl;
return false;
}
std::vector<cv::Point2f> lkPrevPts, lkNextPts;
std::vector<int> lkIds;
for (size_t i=0; i<status.size(); i++)
{
if (status[i])
{
lkPrevPts.push_back(prev_pts[i]);
lkNextPts.push_back(next_pts[i]);
lkIds.push_back(i);
}
}
std::vector<unsigned char> epStatus;
std::vector<int> epIds;
if(lkPrevPts.size() > 0)
epStatus = filterMatchesEpipolarContraint(lkPrevPts, lkNextPts);
std::vector<cv::Point2f> trackedPts;
for (size_t i=0; i<epStatus.size(); i++)
{
if (epStatus[i])
{
trackedPts.push_back(lkNextPts.at(i));
epIds.push_back(lkIds.at(i));
}
}
status = std::vector<unsigned char>(next_pts.size(), false);
for(unsigned int i = 0; i < epIds.size(); i++)
{
status.at(epIds.at(i)) = true;
next_pts.at(epIds.at(i)) = trackedPts.at(i);
}
return true;
}
//!// Processes a frame and returns output image
bool KLTTracker::processFrame(const cv::Mat& inputFrame, cv::Mat& outputFrame,
std::vector<cv::Point2f>& pts2d, std::vector<cv::Point3f>& pts3d, std::vector<int>& ptIDs)
{
pts2d.clear();
pts3d.clear();
inputFrame.copyTo(m_nextImg);
inputFrame.copyTo(outputFrame);
//cv::cvtColor(inputFrame, outputFrame, CV_GRAY2BGR);
std::vector<unsigned char> status;
//std::cout << "processing internal..." << std::endl;
//std::cout <<"next dim=" << m_nextImg.rows << "x" << m_nextImg.cols << std::endl;
//std::cout <<"prev dim=" << m_prevImg.rows << "x" << m_prevImg.cols << std::endl;
//imshow("next_img", m_nextImg);
//imshow("prev_img", m_prevImg);
//waitKey(1);
processFrameInternal(m_prevImg, m_nextImg, m_prevPts, m_nextPts, status);
//std::cout << "processed internal..." << std::endl;
std::vector<cv::Point2f> trackedPts;
std::vector<cv::Point3f> tracked3dPts;
std::vector<int> trackedPtIDs;
for (size_t i=0; i<status.size(); i++)
{
if (status[i])
{
tracked3dPts.push_back(m_tracked3dPts[i]);
trackedPts.push_back(m_nextPts[i]);
trackedPtIDs.push_back(m_ptIDs[i]);
cv::line(outputFrame, m_prevPts[i], m_nextPts[i], cv::Scalar(0,250,0));
cv::circle(outputFrame, m_nextPts[i], 3, cv::Scalar(0,250,0), -1);
cv::putText(outputFrame, std::to_string(m_ptIDs[i]), m_nextPts[i],
cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar::all(255));
}
}
pts2d = trackedPts;
pts3d = tracked3dPts;
ptIDs = trackedPtIDs;
m_tracked3dPts = tracked3dPts;
m_prevPts = trackedPts;
m_ptIDs = trackedPtIDs;
m_nextImg.copyTo(m_prevImg);
return true;
}
<commit_msg>Fixed compilation error<commit_after>#include "sp_segmenter/klttracker.h"
#include <iostream>
#include <algorithm>
using namespace Eigen;
using namespace cv;
KLTTracker::KLTTracker(unsigned int max_kps)
{
m_nextID = 0;
m_maxNumberOfPoints = max_kps;
m_fastDetector = cv::FastFeatureDetector::create(std::string("FAST"));
}
unsigned int KLTTracker::getNumPointsTracked()
{
return m_ptIDs.size();
}
bool KLTTracker::hasTracking()
{
return m_ptIDs.size() > 0 && m_prevPts.size() > 0;
}
void KLTTracker::clear()
{
m_prevPts.clear();
m_nextPts.clear();
m_tracked3dPts.clear();
m_ptIDs.clear();
m_prevImg = Mat(0,0,CV_8UC1);
}
cv::Mat KLTTracker::getLastImage()
{
return m_prevImg;
}
std::vector<unsigned char> KLTTracker::filterMatchesEpipolarContraint(
const std::vector<cv::Point2f>& pts1,
const std::vector<cv::Point2f>& pts2)
{
std::vector<unsigned char> status;
findFundamentalMat(pts1, pts2, CV_FM_RANSAC, 3, .99, status);
return status;
}
void KLTTracker::initPointsAndFastforward(const std::vector<cv::Mat>& inputFrames, const cv::Mat& depth,
const Eigen::Matrix3f& K,
const Eigen::Matrix4f& inputTf, const cv::Mat& mask)
{
if(inputFrames.size() == 0)
{
std::cout << "KLTTracker: number of input frames = 0" << std::endl;
return;
}
if(m_ptIDs.size() == m_maxNumberOfPoints)
{
std::cout << "KLTTracker: Max keypoints reached" << std::endl;
return;
}
std::vector<cv::KeyPoint> detected_pts;
std::vector<cv::Point2f> new_pts;
std::vector<cv::Point3f> new_3d_pts;
// Detect new points
m_fastDetector->detect(inputFrames.at(0), detected_pts, mask);
std::sort(detected_pts.begin(), detected_pts.end(),
[](const cv::KeyPoint &a, const cv::KeyPoint& b) -> bool
{
return a.response > b.response;
}
);
//std::random_shuffle(detected_pts.begin(), detected_pts.end());
unsigned int num_new_pts = m_maxNumberOfPoints; //min(detected_pts.size(), m_maxNumberOfPoints - m_ptIDs.size());
std::cout << "detected " << num_new_pts << " new pts" << std::endl;
// Backproject points to 3D using depth data
// TODO: try with model instead???
for (size_t i=0; i<num_new_pts; i++)
{
Eigen::Vector3f hkp(detected_pts[i].pt.x, detected_pts[i].pt.y, 1);
// TODO: DOUBLE CHECK DEPTH IS IN METERS
double pt_depth = depth.at<float>(int(hkp(1)), int(hkp(0)));
if(pt_depth == 0 || pt_depth == -1 || std::isnan(pt_depth))
continue;
std::cout << pt_depth << std::endl;
Eigen::Vector3f backproj = K.inverse()*hkp;
backproj /= backproj(2);
backproj *= pt_depth;
Eigen::Vector4f backproj_h(backproj(0), backproj(1), backproj(2), 1);
backproj_h = inputTf*backproj_h;
new_3d_pts.push_back(Point3f(backproj_h(0), backproj_h(1), backproj_h(2)));
new_pts.push_back(detected_pts.at(i).pt);
}
std::cout << "backprojected " << new_pts.size() << " pts" << std::endl;
// Fastforward tracked points to current frame
std::vector<cv::Point2f> prev_pts = new_pts;
std::vector<cv::Point2f> next_pts;
std::vector<cv::Point3f> valid_3dpts;
std::vector<unsigned char> status;
for(unsigned int i = 1; i < inputFrames.size(); i++)
{
if(prev_pts.size() == 0)
{
std::cout << "KLTTracker: Fastforward failed" << std::endl;
break;
}
processFrameInternal(inputFrames.at(i-1), inputFrames.at(i), prev_pts, next_pts, status);
prev_pts.clear();
valid_3dpts.clear();
for(unsigned int j = 0; j < status.size(); j++)
{
if(status[j])
{
prev_pts.push_back(next_pts.at(j));
valid_3dpts.push_back(new_3d_pts.at(j));
}
}
//std::cout << "frame " << i << "/" << inputFrames.size() << " " << next_pts.size() << " pts"
// << std::endl;
new_3d_pts = valid_3dpts;
}
assert(new_3d_pts.size() == prev_pts.size());
// Add prev image if initializing
if(m_prevImg.cols == 0)
m_prevImg = inputFrames.back();
// Add new points to tracker
std::cout <<"adding " << prev_pts.size() << " new pts" << std::endl;
m_tracked3dPts = new_3d_pts;
m_prevPts = prev_pts;
//m_tracked3dPts.insert(m_tracked3dPts.end(), new_3d_pts.begin(), new_3d_pts.end());
//m_prevPts.insert(m_prevPts.end(), prev_pts.begin(), prev_pts.end());
std::cout <<"pts_size=" << m_prevPts.size() << std::endl;
m_ptIDs.clear();
for(unsigned int i = 0; i < new_3d_pts.size(); i++)
{
m_ptIDs.push_back(m_nextID++);
}
}
bool KLTTracker::processFrameInternal(const cv::Mat& prev_image, const cv::Mat& next_image,
const std::vector<cv::Point2f>& prev_pts, std::vector<cv::Point2f>& next_pts,
std::vector<unsigned char>& status)
{
next_pts.clear();
status.clear();
std::vector<float> error;
if (prev_pts.size() > 0)
{
cv::calcOpticalFlowPyrLK(prev_image, next_image, prev_pts, next_pts, status, error);
}
else
{
std::cout << "prev_points.size()=0" << std::endl;
return false;
}
std::vector<cv::Point2f> lkPrevPts, lkNextPts;
std::vector<int> lkIds;
for (size_t i=0; i<status.size(); i++)
{
if (status[i])
{
lkPrevPts.push_back(prev_pts[i]);
lkNextPts.push_back(next_pts[i]);
lkIds.push_back(i);
}
}
std::vector<unsigned char> epStatus;
std::vector<int> epIds;
if(lkPrevPts.size() > 0)
epStatus = filterMatchesEpipolarContraint(lkPrevPts, lkNextPts);
std::vector<cv::Point2f> trackedPts;
for (size_t i=0; i<epStatus.size(); i++)
{
if (epStatus[i])
{
trackedPts.push_back(lkNextPts.at(i));
epIds.push_back(lkIds.at(i));
}
}
status = std::vector<unsigned char>(next_pts.size(), false);
for(unsigned int i = 0; i < epIds.size(); i++)
{
status.at(epIds.at(i)) = true;
next_pts.at(epIds.at(i)) = trackedPts.at(i);
}
return true;
}
//!// Processes a frame and returns output image
bool KLTTracker::processFrame(const cv::Mat& inputFrame, cv::Mat& outputFrame,
std::vector<cv::Point2f>& pts2d, std::vector<cv::Point3f>& pts3d, std::vector<int>& ptIDs)
{
pts2d.clear();
pts3d.clear();
inputFrame.copyTo(m_nextImg);
inputFrame.copyTo(outputFrame);
//cv::cvtColor(inputFrame, outputFrame, CV_GRAY2BGR);
std::vector<unsigned char> status;
//std::cout << "processing internal..." << std::endl;
//std::cout <<"next dim=" << m_nextImg.rows << "x" << m_nextImg.cols << std::endl;
//std::cout <<"prev dim=" << m_prevImg.rows << "x" << m_prevImg.cols << std::endl;
//imshow("next_img", m_nextImg);
//imshow("prev_img", m_prevImg);
//waitKey(1);
processFrameInternal(m_prevImg, m_nextImg, m_prevPts, m_nextPts, status);
//std::cout << "processed internal..." << std::endl;
std::vector<cv::Point2f> trackedPts;
std::vector<cv::Point3f> tracked3dPts;
std::vector<int> trackedPtIDs;
for (size_t i=0; i<status.size(); i++)
{
if (status[i])
{
tracked3dPts.push_back(m_tracked3dPts[i]);
trackedPts.push_back(m_nextPts[i]);
trackedPtIDs.push_back(m_ptIDs[i]);
cv::line(outputFrame, m_prevPts[i], m_nextPts[i], cv::Scalar(0,250,0));
cv::circle(outputFrame, m_nextPts[i], 3, cv::Scalar(0,250,0), -1);
cv::putText(outputFrame, std::to_string(m_ptIDs[i]), m_nextPts[i],
cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar::all(255));
}
}
pts2d = trackedPts;
pts3d = tracked3dPts;
ptIDs = trackedPtIDs;
m_tracked3dPts = tracked3dPts;
m_prevPts = trackedPts;
m_ptIDs = trackedPtIDs;
m_nextImg.copyTo(m_prevImg);
return true;
}
<|endoftext|> |
<commit_before>#include "lexer/lexer.h"
Lexer::Lexer(const char *file, bool f) {
file_ = true;
std::ifstream infile(file);
file_name_ = file;
int length = 0;
if (infile.fail()) {
ERROR(std::string, "cannot open file");
f = false;
err_msg_ = file + std::string(": file doesn't exist\n");
return;
}
infile.seekg(0, infile.end);
length = (size_t)infile.tellg();
infile.seekg(0, infile.beg);
code_.resize(length + 2, ' ');
infile.read(&*(code_.begin()), length);
infile.close();
size_ = length;
end_ = length;
seek_ = 0;
tok_ = nullptr;
eos_ = false;
}
Token *Lexer::NextToken() {
char ch, ch2, ch3;
TokenType tok;
Position pos;
if (!buffer_.empty()) {
Token *tok = buffer_.back();
buffer_.pop_back();
return tok;
}
ch = NextCharacter();
// skip whitespaces
while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
ch = NextCharacter();
// skip comments
while (ch != EOF &&
((ch == '/' && LookAhead() == '/') || (ch == '/' && LookAhead() == '*')))
StripComments(ch);
// note the current position as we are about to parse
// a valid(may be) token from this position
pos = position_;
if (ch != EOF) {
// handle keywords, identifiers and numbers
while (isalnum(ch) || ch == '_')
return Characterize(ch, pos);
if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
LookAhead() == '\t' || LookAhead() == '\n')
goto one;
// else ch is a symbol
ch2 = NextCharacter();
if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
LookAhead() == '\t' || LookAhead() == '\n')
goto two;
ch3 = NextCharacter();
// check if there is a three character symbol
tok = ThreeCharacterSymbol(ch, ch2, ch3);
if (tok != INVALID) {
return new Token(std::string({ch, ch2, ch3}), tok,
TOKENS[tok].precedance_, pos);
}
// as we have gone ahead one character so time to go back
GoBack();
two:
// so now check whether we are at position of two character symbol
tok = TwoCharacterSymbol(ch, ch2);
if (tok != INVALID) {
return new Token(std::string({ch, ch2}), tok, TOKENS[tok].precedance_,
pos);
}
// No! Let's go back one character
GoBack();
one:
// Only possibility left
tok = OneCharacterSymbol(ch);
if (tok != INVALID) {
return new Token(std::string({ch}), tok, TOKENS[tok].precedance_, pos);
} else // oops! something went wrong, token is invalid!
return new Token(std::string({ch}), INVALID, 0, pos);
}
// finally reached at the end of the given string
return new Token(std::string({ch}), EOS, -1, pos);
}
void Lexer::StripComments(char &ch) { // skips all the comments from the string
char last = '\0';
// skip the comments - single line comment
if (ch != EOF && (ch == '/' && LookAhead() == '/')) {
ch = NextCharacter();
while (ch != '\n' || ch == EOF)
ch = NextCharacter();
ch = NextCharacter();
}
// multiline comment, /* */ type
if (ch != EOF && (ch == '/' && LookAhead() == '*')) {
last = ch;
ch = NextCharacter();
while (ch != EOF && !(last == '*' && ch == '/')) {
last = ch;
ch = NextCharacter();
}
ch = NextCharacter();
}
while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
ch = NextCharacter();
}
void Lexer::GoBack() { // go back one character back
--seek_;
if (position_.col_ - 1 < 0) { // we don't want our col_ to be negative
position_.row_--; // needed
position_.col_ = lastColNumber_;
} else { // okay, so simply decrement col_ member
position_.col_--;
}
}
char Lexer::NextCharacter() { // returns the next character from the string
if (seek_ <= end_) { // if eos_ flag has not been set
char ch = code_[seek_++];
if (ch == '\0') { // if we are not processing EOF file character
ch = EOF;
eos_ = true;
}
if (ch == '\n') { // change the position
position_.row_++;
lastColNumber_ = position_.col_;
position_.col_ = 0;
} else {
position_.col_++;
}
return ch;
}
return EOF;
}
Token *Lexer::Characterize(char ch,
Position &pos)
{
std::string buffer;
if (isdigit(ch))
return ParseNumber(ch, pos);
if (isalpha(ch) || ch == '_' || ch == '$')
return ParseIdentifierOrKeyWord(ch, pos);
// if none of both then we have to return a invalid token
return new Token(std::string(""), INVALID, -1, pos);
}
Token *
Lexer::ParseNumber(char ch,
Position &pos) { // parses the number from the current position
std::string buffer; // buffer to store the parsed number
while (isdigit(ch)) {
buffer += ch;
ch = NextCharacter();
}
// possible floating point number
if (ch == '.' || ch == 'e' || ch == 'E') {
buffer += ch;
ch = NextCharacter();
while (isdigit(ch)) {
buffer += ch;
ch = NextCharacter();
}
}
// we've gone one character ahead, so go back
GoBack();
return new Token(buffer, DIGIT, -1, pos);
}
Token *Lexer::ParseIdentifierOrKeyWord(
char ch,
Position &
pos) { // parses the identifier or a keyword from the current position
std::string buffer;
// possibly it is an identifier
while (isalnum(ch) || ch == '_' || ch == '$') {
buffer += ch;
ch = NextCharacter();
}
// again went a character ahead
GoBack();
// check for KeyWord
if (buffer[0] != '_' || buffer[0] != '$') {
for (int i = LET; i <= RET; i++)
if (buffer[0] == TOKENS[i].value_[0] && buffer == TOKENS[i].value_)
return new Token(buffer, i, 0, pos);
}
return new Token(buffer, IDENT, -1, pos);
}
// although not required because of no use
Token *Lexer::ParseStringLiteral(
char ch, Position &pos) { // parses the string literal from the string
std::string str = "";
if (ch == '"') { // string surrounded by "
ch = NextCharacter();
while (ch != '"') {
str += ch;
ch = NextCharacter();
}
} else if (ch == '\'') { // string surrounded by '
ch = NextCharacter();
while (ch != '\'') {
str += ch;
ch = NextCharacter();
}
}
return new Token(str, STRING, -1, pos);
}
char parsehex(char ch) {
if (ch >= '0' && ch <= '9')
return ch - '0';
else if ((ch >= 'a' && ch <= 'f')) {
return 10 + ch - 'a';
} else if (ch >= 'A' && ch <= 'F') {
return 10 + ch - 'A';
}
throw std::runtime_error("wrong hexadecimal digits");
}
char parseoct(char ch) {
if (ch >= '0' && ch <= '8')
return ch - '0';
throw std::runtime_error("wrong octal digits");
}
char escape_code(std::string str) {
if (str[0] != '\\')
return str[0];
if (str[1] == 'x') {
char ret = 0;
ret |= parsehex(str[2]);
ret <<= 4;
ret |= parsehex(str[3]);
return ret;
} else if (str[1] == 'n')
return '\n';
else if (str[1] == 'b')
return '\b';
else if (str[1] == 'r')
return '\r';
else if (str[1] == 'a')
return '\a';
else if (str[1] == 't')
return '\t';
else if (str[1] == '"')
return '"';
else if (str[1] == '\'')
return '\'';
else throw std::runtime_error("unknown escape code");
}
// this function should be used instead of above function
// when we found a token of " or ' that means we are about
// to parse the string from the current position
std::string Lexer::GetStringLiteral() { // returns all the string until it finds "
// create a buffer
std::string str = "";
char ch = NextCharacter();
while (ch != EOF && (ch != '"' && ch != '\'')) {
if (ch == '\\') {
// a possible escape code
std::string tmp = "";
tmp += ch;
ch = NextCharacter();
tmp += ch;
if (ch == 'x') {
ch = NextCharacter();
tmp += ch;
ch = NextCharacter();
tmp += ch;
}
ch = escape_code(tmp);
}
str += ch; // fill the buffer
ch = NextCharacter();
}
return str;
}
TokenType Lexer::OneCharacterSymbol(
char ch) { // returns the type of token from the given symbol
switch (ch) {
case '(':
return LPAR;
case ')':
return RPAR;
case '{':
return LBRACE;
case '}':
return RBRACE;
case '[':
return LSQB;
case ']':
return RSQB;
case ':':
return COLON;
case ';':
return SCOLON;
case '"':
case '\'':
return STRING;
case '.':
return DOT;
case ',':
return COMMA;
case '?':
return CONDITION;
case '+':
return PLUS;
case '-':
return MINUS;
case '/':
return DIV;
case '*':
return MUL;
case '%':
return MOD;
case '>':
return GT;
case '<':
return LT;
case '=':
return ASSIGN;
case '^':
return XOR;
case '|':
return BOR;
case '&':
return BAND;
case '!':
return NOT;
case '~':
return BNOT;
default:
return INVALID;
}
}
TokenType
Lexer::TwoCharacterSymbol(char ch1,
char ch2) { // returns the type of symbol of two characters
switch (ch2) {
case '=':
switch (ch1) {
case '+':
return PLUSEQ;
case '-':
return MINUSEQ;
case '*':
return MULEQ;
case '/':
return DIVEQ;
case '%':
return MODEQ;
case '^':
return XOREQ;
case '&':
return BANDEQ;
case '|':
return BOREQ;
case '>':
return GTE;
case '<':
return LTE;
case '=':
return EQUAL;
case '!':
return NOTEQ;
}
return INVALID;
case '|':
if (ch1 == '|')
return OR;
return INVALID;
case '&':
if (ch1 == '&')
return AND;
return INVALID;
case '+':
if (ch1 == '+')
return INC;
return INVALID;
case '-':
if (ch1 == '-')
return DEC;
return INVALID;
case '<':
if (ch1 == '<')
return SHL;
return INVALID;
case '>':
if (ch1 == '>')
return SHR;
default:
return INVALID;
}
}
bool Lexer::IsFile() const { return file_; }
std::string Lexer::GetFileName() { return file_name_; }
TokenType Lexer::ThreeCharacterSymbol(
char ch1, char ch2,
char ch3) { // returns the type of symbol of three characters
switch (ch3) {
case '=':
if (ch1 == '>' && ch2 == '>')
return SHREQ;
if (ch1 == '<' && ch2 == '<')
return SHLEQ;
default:
return INVALID;
}
}
void Lexer::PutBack(Token *tok) { // put in the buffer for one token lookahead
// required by parser
buffer_.push_back(tok);
}
// move to next token
void Lexer::advance()
{
tok_ = NextToken();
}
double Lexer::GetNumber()
{
double result = 0.0;
try {
result = std::stod(tok_->GetValue());
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return result;
}
<commit_msg>Add another check for EOF<commit_after>#include "lexer/lexer.h"
#include <stdexcept>
Lexer::Lexer(const char *file, bool f) {
file_ = true;
std::ifstream infile(file);
file_name_ = file;
int length = 0;
if (infile.fail()) {
ERROR(std::string, "cannot open file");
f = false;
err_msg_ = file + std::string(": file doesn't exist\n");
return;
}
infile.seekg(0, infile.end);
length = (size_t)infile.tellg();
infile.seekg(0, infile.beg);
code_.resize(length + 2, ' ');
infile.read(&*(code_.begin()), length);
infile.close();
size_ = length;
end_ = length;
seek_ = 0;
tok_ = nullptr;
eos_ = false;
}
Token *Lexer::NextToken() {
char ch, ch2, ch3;
TokenType tok;
Position pos;
if (!buffer_.empty()) {
Token *tok = buffer_.back();
buffer_.pop_back();
return tok;
}
ch = NextCharacter();
// skip whitespaces
while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
ch = NextCharacter();
// skip comments
while (ch != EOF &&
((ch == '/' && LookAhead() == '/') || (ch == '/' && LookAhead() == '*')))
StripComments(ch);
// note the current position as we are about to parse
// a valid(may be) token from this position
pos = position_;
if (ch == EOF || ch == 255)
return new Token(std::string("EOS"), EOS, -1, pos);
// handle keywords, identifiers and numbers
while (isalnum(ch) || ch == '_')
return Characterize(ch, pos);
if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
LookAhead() == '\t' || LookAhead() == '\n')
goto one;
// else ch is a symbol
ch2 = NextCharacter();
if (LookAhead() == EOF || LookAhead() == '\0' || LookAhead() == ' ' ||
LookAhead() == '\t' || LookAhead() == '\n')
goto two;
ch3 = NextCharacter();
// check if there is a three character symbol
tok = ThreeCharacterSymbol(ch, ch2, ch3);
if (tok != INVALID) {
return new Token(std::string({ch, ch2, ch3}), tok,
TOKENS[tok].precedance_, pos);
}
// as we have gone ahead one character so time to go back
GoBack();
two:
// so now check whether we are at position of two character symbol
tok = TwoCharacterSymbol(ch, ch2);
if (tok != INVALID) {
return new Token(std::string({ch, ch2}), tok, TOKENS[tok].precedance_,
pos);
}
// No! Let's go back one character
GoBack();
one:
// Only possibility left
tok = OneCharacterSymbol(ch);
if (tok != INVALID) {
return new Token(std::string({ch}), tok, TOKENS[tok].precedance_, pos);
} else // oops! something went wrong, token is invalid!
return new Token(std::string({ch}), INVALID, 0, pos);
// finally reached at the end of the given string
return new Token(std::string({ch}), EOS, -1, pos);
}
void Lexer::StripComments(char &ch) { // skips all the comments from the string
char last = '\0';
// skip the comments - single line comment
if (ch != EOF && (ch == '/' && LookAhead() == '/')) {
ch = NextCharacter();
while (ch != '\n' || ch == EOF)
ch = NextCharacter();
ch = NextCharacter();
}
// multiline comment, /* */ type
if (ch != EOF && (ch == '/' && LookAhead() == '*')) {
last = ch;
ch = NextCharacter();
while (ch != EOF && !(last == '*' && ch == '/')) {
last = ch;
ch = NextCharacter();
}
ch = NextCharacter();
}
while (ch != EOF && (ch == ' ' || ch == '\n' || ch == '\t'))
ch = NextCharacter();
}
void Lexer::GoBack() { // go back one character back
--seek_;
if (position_.col_ - 1 < 0) { // we don't want our col_ to be negative
position_.row_--; // needed
position_.col_ = lastColNumber_;
} else { // okay, so simply decrement col_ member
position_.col_--;
}
}
char Lexer::NextCharacter() { // returns the next character from the string
if (seek_ <= end_) { // if eos_ flag has not been set
char ch = code_[seek_++];
if (ch == '\0') { // if we are not processing EOF file character
ch = EOF;
eos_ = true;
}
if (ch == '\n') { // change the position
position_.row_++;
lastColNumber_ = position_.col_;
position_.col_ = 0;
} else {
position_.col_++;
}
return ch;
}
return EOF;
}
Token *Lexer::Characterize(char ch,
Position &pos)
{
std::string buffer;
if (isdigit(ch))
return ParseNumber(ch, pos);
if (isalpha(ch) || ch == '_' || ch == '$')
return ParseIdentifierOrKeyWord(ch, pos);
// if none of both then we have to return a invalid token
return new Token(std::string(""), INVALID, -1, pos);
}
Token *
Lexer::ParseNumber(char ch,
Position &pos) { // parses the number from the current position
std::string buffer; // buffer to store the parsed number
while (isdigit(ch)) {
buffer += ch;
ch = NextCharacter();
}
// possible floating point number
if (ch == '.' || ch == 'e' || ch == 'E') {
buffer += ch;
ch = NextCharacter();
while (isdigit(ch)) {
buffer += ch;
ch = NextCharacter();
}
}
// we've gone one character ahead, so go back
GoBack();
return new Token(buffer, DIGIT, -1, pos);
}
Token *Lexer::ParseIdentifierOrKeyWord(
char ch,
Position &
pos) { // parses the identifier or a keyword from the current position
std::string buffer;
// possibly it is an identifier
while (isalnum(ch) || ch == '_' || ch == '$') {
buffer += ch;
ch = NextCharacter();
}
// again went a character ahead
GoBack();
// check for KeyWord
if (buffer[0] != '_' || buffer[0] != '$') {
for (int i = LET; i <= RET; i++)
if (buffer[0] == TOKENS[i].value_[0] && buffer == TOKENS[i].value_)
return new Token(buffer, i, 0, pos);
}
return new Token(buffer, IDENT, -1, pos);
}
// although not required because of no use
Token *Lexer::ParseStringLiteral(
char ch, Position &pos) { // parses the string literal from the string
std::string str = "";
if (ch == '"') { // string surrounded by "
ch = NextCharacter();
while (ch != '"') {
str += ch;
ch = NextCharacter();
}
} else if (ch == '\'') { // string surrounded by '
ch = NextCharacter();
while (ch != '\'') {
str += ch;
ch = NextCharacter();
}
}
return new Token(str, STRING, -1, pos);
}
char parsehex(char ch) {
if (ch >= '0' && ch <= '9')
return ch - '0';
else if ((ch >= 'a' && ch <= 'f')) {
return 10 + ch - 'a';
} else if (ch >= 'A' && ch <= 'F') {
return 10 + ch - 'A';
}
throw std::runtime_error("wrong hexadecimal digits");
}
char parseoct(char ch) {
if (ch >= '0' && ch <= '8')
return ch - '0';
throw std::runtime_error("wrong octal digits");
}
char escape_code(std::string str) {
if (str[0] != '\\')
return str[0];
if (str[1] == 'x') {
char ret = 0;
ret |= parsehex(str[2]);
ret <<= 4;
ret |= parsehex(str[3]);
return ret;
} else if (str[1] == 'n')
return '\n';
else if (str[1] == 'b')
return '\b';
else if (str[1] == 'r')
return '\r';
else if (str[1] == 'a')
return '\a';
else if (str[1] == 't')
return '\t';
else if (str[1] == '"')
return '"';
else if (str[1] == '\'')
return '\'';
else throw std::runtime_error("unknown escape code");
}
// this function should be used instead of above function
// when we found a token of " or ' that means we are about
// to parse the string from the current position
std::string Lexer::GetStringLiteral() { // returns all the string until it finds "
// create a buffer
std::string str = "";
char ch = NextCharacter();
while (ch != EOF && (ch != '"' && ch != '\'')) {
if (ch == '\\') {
// a possible escape code
std::string tmp = "";
tmp += ch;
ch = NextCharacter();
tmp += ch;
if (ch == 'x') {
ch = NextCharacter();
tmp += ch;
ch = NextCharacter();
tmp += ch;
}
ch = escape_code(tmp);
}
str += ch; // fill the buffer
ch = NextCharacter();
}
return str;
}
TokenType Lexer::OneCharacterSymbol(
char ch) { // returns the type of token from the given symbol
switch (ch) {
case '(':
return LPAR;
case ')':
return RPAR;
case '{':
return LBRACE;
case '}':
return RBRACE;
case '[':
return LSQB;
case ']':
return RSQB;
case ':':
return COLON;
case ';':
return SCOLON;
case '"':
case '\'':
return STRING;
case '.':
return DOT;
case ',':
return COMMA;
case '?':
return CONDITION;
case '+':
return PLUS;
case '-':
return MINUS;
case '/':
return DIV;
case '*':
return MUL;
case '%':
return MOD;
case '>':
return GT;
case '<':
return LT;
case '=':
return ASSIGN;
case '^':
return XOR;
case '|':
return BOR;
case '&':
return BAND;
case '!':
return NOT;
case '~':
return BNOT;
default:
return INVALID;
}
}
TokenType
Lexer::TwoCharacterSymbol(char ch1,
char ch2) { // returns the type of symbol of two characters
switch (ch2) {
case '=':
switch (ch1) {
case '+':
return PLUSEQ;
case '-':
return MINUSEQ;
case '*':
return MULEQ;
case '/':
return DIVEQ;
case '%':
return MODEQ;
case '^':
return XOREQ;
case '&':
return BANDEQ;
case '|':
return BOREQ;
case '>':
return GTE;
case '<':
return LTE;
case '=':
return EQUAL;
case '!':
return NOTEQ;
}
return INVALID;
case '|':
if (ch1 == '|')
return OR;
return INVALID;
case '&':
if (ch1 == '&')
return AND;
return INVALID;
case '+':
if (ch1 == '+')
return INC;
return INVALID;
case '-':
if (ch1 == '-')
return DEC;
return INVALID;
case '<':
if (ch1 == '<')
return SHL;
return INVALID;
case '>':
if (ch1 == '>')
return SHR;
default:
return INVALID;
}
}
bool Lexer::IsFile() const { return file_; }
std::string Lexer::GetFileName() { return file_name_; }
TokenType Lexer::ThreeCharacterSymbol(
char ch1, char ch2,
char ch3) { // returns the type of symbol of three characters
switch (ch3) {
case '=':
if (ch1 == '>' && ch2 == '>')
return SHREQ;
if (ch1 == '<' && ch2 == '<')
return SHLEQ;
default:
return INVALID;
}
}
void Lexer::PutBack(Token *tok) { // put in the buffer for one token lookahead
// required by parser
buffer_.push_back(tok);
}
// move to next token
void Lexer::advance()
{
tok_ = NextToken();
}
double Lexer::GetNumber()
{
double result = 0.0;
try {
result = std::stod(tok_->GetValue());
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return result;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* Copyright (c) 2009 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Daniel Sanchez
* Brad Beckmann
*/
#include <iostream>
#include <fstream>
#include "arch/isa_traits.hh"
#include "base/output.hh"
#include "base/str.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "mem/ruby/common/Debug.hh"
#include "mem/ruby/libruby.hh"
#include "mem/ruby/system/RubyPort.hh"
#include "mem/ruby/system/Sequencer.hh"
#include "mem/ruby/system/System.hh"
#include "mem/rubymem.hh"
#include "sim/eventq.hh"
#include "sim/sim_exit.hh"
using namespace std;
using namespace TheISA;
map<int64_t, PacketPtr> RubyMemory::pending_requests;
RubyMemory::RubyMemory(const Params *p)
: PhysicalMemory(p)
{
ruby_clock = p->clock;
ruby_phase = p->phase;
ifstream config(p->config_file.c_str());
vector<RubyObjConf> sys_conf;
while (!config.eof()) {
char buffer[65536];
config.getline(buffer, sizeof(buffer));
string line = buffer;
DPRINTF(Ruby, "%s %d\n", line, line.empty());
if (line.empty())
continue;
vector<string> tokens;
tokenize(tokens, line, ' ');
assert(tokens.size() >= 2);
vector<string> argv;
for (size_t i=2; i<tokens.size(); i++) {
std::replace(tokens[i].begin(), tokens[i].end(), '%', ' ');
std::replace(tokens[i].begin(), tokens[i].end(), '#', '\n');
argv.push_back(tokens[i]);
}
sys_conf.push_back(RubyObjConf(tokens[0], tokens[1], argv));
tokens.clear();
argv.clear();
}
RubySystem::create(sys_conf);
//
// Create the necessary ruby_ports to connect to the sequencers.
// This code should be fixed when the configuration systems are unified
// and the ruby configuration text files no longer exist. Also,
// it would be great to remove the single ruby_hit_callback func with
// separate pointers to particular ports to rubymem. However, functional
// access currently prevent the improvement.
//
for (int i = 0; i < params()->num_cpus; i++) {
RubyPort *p = RubySystem::getPort(csprintf("Sequencer_%d", i),
ruby_hit_callback);
ruby_ports.push_back(p);
}
for (int i = 0; i < params()->num_dmas; i++) {
RubyPort *p = RubySystem::getPort(csprintf("DMASequencer_%d", i),
ruby_hit_callback);
ruby_dma_ports.push_back(p);
}
pio_port = NULL;
}
void
RubyMemory::init()
{
if (params()->debug) {
g_debug_ptr->setVerbosityString("high");
g_debug_ptr->setDebugTime(1);
if (!params()->debug_file.empty()) {
g_debug_ptr->setDebugOutputFile(params()->debug_file.c_str());
}
}
//You may want to set some other options...
//g_debug_ptr->setVerbosityString("med");
//g_debug_ptr->setFilterString("lsNqST");
//g_debug_ptr->setFilterString("lsNST");
//g_debug_ptr->setDebugTime(1);
//g_debug_ptr->setDebugOutputFile("ruby.debug");
g_system_ptr->clearStats();
if (ports.size() == 0) {
fatal("RubyMemory object %s is unconnected!", name());
}
for (PortIterator pi = ports.begin(); pi != ports.end(); ++pi) {
if (*pi)
(*pi)->sendStatusChange(Port::RangeChange);
}
for (PortIterator pi = dma_ports.begin(); pi != dma_ports.end(); ++pi) {
if (*pi)
(*pi)->sendStatusChange(Port::RangeChange);
}
if (pio_port != NULL) {
pio_port->sendStatusChange(Port::RangeChange);
}
//Print stats at exit
rubyExitCB = new RubyExitCallback(this);
registerExitCallback(rubyExitCB);
//Sched RubyEvent, automatically reschedules to advance ruby cycles
rubyTickEvent = new RubyEvent(this);
schedule(rubyTickEvent, curTick + ruby_clock + ruby_phase);
}
//called by rubyTickEvent
void
RubyMemory::tick()
{
RubyEventQueue *eq = RubySystem::getEventQueue();
eq->triggerEvents(eq->getTime() + 1);
schedule(rubyTickEvent, curTick + ruby_clock);
}
RubyMemory::~RubyMemory()
{
delete g_system_ptr;
}
Port *
RubyMemory::getPort(const std::string &if_name, int idx)
{
DPRINTF(Ruby, "getting port %d %s\n", idx, if_name);
DPRINTF(Ruby,
"number of ruby ports %d and dma ports %d\n",
ruby_ports.size(),
ruby_dma_ports.size());
// Accept request for "functional" port for backwards compatibility
// with places where this function is called from C++. I'd prefer
// to move all these into Python someday.
if (if_name == "functional") {
return new Port(csprintf("%s-functional", name()),
this,
ruby_ports[idx]);
}
//
// if dma port request, allocate the appropriate prot
//
if (if_name == "dma_port") {
assert(idx < ruby_dma_ports.size());
RubyMemory::Port* dma_port =
new Port(csprintf("%s-dma_port%d", name(), idx),
this,
ruby_dma_ports[idx]);
dma_ports.push_back(dma_port);
return dma_port;
}
//
// if pio port, ensure that there is only one
//
if (if_name == "pio_port") {
assert(pio_port == NULL);
pio_port =
new RubyMemory::Port("ruby_pio_port", this, NULL);
return pio_port;
}
if (if_name != "port") {
panic("RubyMemory::getPort: unknown port %s requested", if_name);
}
if (idx >= (int)ports.size()) {
ports.resize(idx+1);
}
if (ports[idx] != NULL) {
panic("RubyMemory::getPort: port %d already assigned", idx);
}
//
// Currently this code assumes that each cpu has both a
// icache and dcache port and therefore divides by two. This will be
// fixed once we unify the configuration systems and Ruby sequencers
// directly support M5 ports.
//
assert(idx/2 < ruby_ports.size());
Port *port = new Port(csprintf("%s-port%d", name(), idx),
this,
ruby_ports[idx/2]);
ports[idx] = port;
return port;
}
RubyMemory::Port::Port(const std::string &_name,
RubyMemory *_memory,
RubyPort *_port)
: PhysicalMemory::MemoryPort::MemoryPort(_name, _memory)
{
DPRINTF(Ruby, "creating port to ruby memory %s\n", _name);
ruby_mem = _memory;
ruby_port = _port;
}
bool
RubyMemory::Port::recvTiming(PacketPtr pkt)
{
DPRINTF(MemoryAccess,
"Timing access caught for address %#x\n",
pkt->getAddr());
//dsm: based on SimpleTimingPort::recvTiming(pkt);
//
// In FS mode, ruby memory will receive pio responses from devices and
// it must forward these responses back to the particular CPU.
//
if (pkt->isResponse() != false && isPioAddress(pkt->getAddr()) != false) {
DPRINTF(MemoryAccess,
"Pio Response callback %#x\n",
pkt->getAddr());
RubyMemory::SenderState *senderState =
safe_cast<RubyMemory::SenderState *>(pkt->senderState);
RubyMemory::Port *port = senderState->port;
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->sendTiming(pkt);
return true;
}
//
// After checking for pio responses, the remainder of packets
// received by ruby should only be M5 requests, which should never
// get nacked. There used to be code to hanldle nacks here, but
// I'm pretty sure it didn't work correctly with the drain code,
// so that would need to be fixed if we ever added it back.
//
assert(pkt->isRequest());
if (pkt->memInhibitAsserted()) {
warn("memInhibitAsserted???");
// snooper will supply based on copy of packet
// still target's responsibility to delete packet
delete pkt;
return true;
}
// Save the port in the sender state object
pkt->senderState = new SenderState(this, pkt->senderState);
//
// Check for pio requests and directly send them to the dedicated
// pio_port.
//
if (isPioAddress(pkt->getAddr()) != false) {
return ruby_mem->pio_port->sendTiming(pkt);
}
//
// For DMA and CPU requests, translate them to ruby requests before
// sending them to our assigned ruby port.
//
RubyRequestType type = RubyRequestType_NULL;
Addr pc = 0;
if (pkt->isRead()) {
if (pkt->req->isInstFetch()) {
type = RubyRequestType_IFETCH;
pc = pkt->req->getPC();
} else {
type = RubyRequestType_LD;
}
} else if (pkt->isWrite()) {
type = RubyRequestType_ST;
} else if (pkt->isReadWrite()) {
// type = RubyRequestType_RMW;
}
RubyRequest ruby_request(pkt->getAddr(), pkt->getPtr<uint8_t>(),
pkt->getSize(), pc, type,
RubyAccessMode_Supervisor);
// Submit the ruby request
int64_t req_id = ruby_port->makeRequest(ruby_request);
if (req_id == -1) {
RubyMemory::SenderState *senderState =
safe_cast<RubyMemory::SenderState *>(pkt->senderState);
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
return false;
}
// Save the request for the callback
RubyMemory::pending_requests[req_id] = pkt;
return true;
}
void
ruby_hit_callback(int64_t req_id)
{
//
// Note: This single fuction can be called by cpu and dma ports,
// as well as the functional port. The functional port prevents
// us from replacing this single function with separate port
// functions.
//
typedef map<int64_t, PacketPtr> map_t;
map_t &prm = RubyMemory::pending_requests;
map_t::iterator i = prm.find(req_id);
if (i == prm.end())
panic("could not find pending request %d\n", req_id);
PacketPtr pkt = i->second;
prm.erase(i);
RubyMemory::SenderState *senderState =
safe_cast<RubyMemory::SenderState *>(pkt->senderState);
RubyMemory::Port *port = senderState->port;
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->hitCallback(pkt);
}
void
RubyMemory::Port::hitCallback(PacketPtr pkt)
{
bool needsResponse = pkt->needsResponse();
DPRINTF(MemoryAccess, "Hit callback needs response %d\n",
needsResponse);
ruby_mem->doAtomicAccess(pkt);
// turn packet around to go back to requester if response expected
if (needsResponse) {
// recvAtomic() should already have turned packet into
// atomic response
assert(pkt->isResponse());
DPRINTF(MemoryAccess, "Sending packet back over port\n");
sendTiming(pkt);
} else {
delete pkt;
}
DPRINTF(MemoryAccess, "Hit callback done!\n");
}
bool
RubyMemory::Port::sendTiming(PacketPtr pkt)
{
schedSendTiming(pkt, curTick + 1); //minimum latency, must be > 0
return true;
}
bool
RubyMemory::Port::isPioAddress(Addr addr)
{
AddrRangeList pioAddrList;
bool snoop = false;
if (ruby_mem->pio_port == NULL) {
return false;
}
ruby_mem->pio_port->getPeerAddressRanges(pioAddrList, snoop);
for(AddrRangeIter iter = pioAddrList.begin(); iter != pioAddrList.end(); iter++) {
if (addr >= iter->start && addr <= iter->end) {
DPRINTF(MemoryAccess, "Pio request found in %#llx - %#llx range\n",
iter->start, iter->end);
return true;
}
}
return false;
}
void RubyMemory::printConfigStats()
{
std::ostream *os = simout.create(params()->stats_file);
RubySystem::printConfig(*os);
*os << endl;
RubySystem::printStats(*os);
}
//Right now these functions seem to be called by RubySystem. If they do calls
// to RubySystem perform it intended actions, you'll get into an inf loop
//FIXME what's the purpose of these here?
void RubyMemory::printStats(std::ostream & out) const {
//g_system_ptr->printConfig(out);
}
void RubyMemory::clearStats() {
//g_system_ptr->clearStats();
}
void RubyMemory::printConfig(std::ostream & out) const {
//g_system_ptr->printConfig(out);
}
void RubyMemory::serialize(ostream &os)
{
PhysicalMemory::serialize(os);
}
void RubyMemory::unserialize(Checkpoint *cp, const string §ion)
{
DPRINTF(Config, "Ruby memory being restored\n");
reschedule(rubyTickEvent, curTick + ruby_clock + ruby_phase);
PhysicalMemory::unserialize(cp, section);
}
//Python-interface code
RubyMemory *
RubyMemoryParams::create()
{
return new RubyMemory(this);
}
<commit_msg>ruby: Added error check for openning the ruby config file<commit_after>/*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* Copyright (c) 2009 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Daniel Sanchez
* Brad Beckmann
*/
#include <iostream>
#include <fstream>
#include "arch/isa_traits.hh"
#include "base/output.hh"
#include "base/str.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "mem/ruby/common/Debug.hh"
#include "mem/ruby/libruby.hh"
#include "mem/ruby/system/RubyPort.hh"
#include "mem/ruby/system/Sequencer.hh"
#include "mem/ruby/system/System.hh"
#include "mem/rubymem.hh"
#include "sim/eventq.hh"
#include "sim/sim_exit.hh"
using namespace std;
using namespace TheISA;
map<int64_t, PacketPtr> RubyMemory::pending_requests;
RubyMemory::RubyMemory(const Params *p)
: PhysicalMemory(p)
{
ruby_clock = p->clock;
ruby_phase = p->phase;
DPRINTF(Ruby, "creating Ruby Memory from file %s\n",
p->config_file.c_str());
ifstream config(p->config_file.c_str());
if (config.good() == false) {
fatal("Did not successfully open %s.\n", p->config_file.c_str());
}
vector<RubyObjConf> sys_conf;
while (!config.eof()) {
char buffer[65536];
config.getline(buffer, sizeof(buffer));
string line = buffer;
DPRINTF(Ruby, "%s %d\n", line, line.empty());
if (line.empty())
continue;
vector<string> tokens;
tokenize(tokens, line, ' ');
assert(tokens.size() >= 2);
vector<string> argv;
for (size_t i=2; i<tokens.size(); i++) {
std::replace(tokens[i].begin(), tokens[i].end(), '%', ' ');
std::replace(tokens[i].begin(), tokens[i].end(), '#', '\n');
argv.push_back(tokens[i]);
}
sys_conf.push_back(RubyObjConf(tokens[0], tokens[1], argv));
tokens.clear();
argv.clear();
}
RubySystem::create(sys_conf);
//
// Create the necessary ruby_ports to connect to the sequencers.
// This code should be fixed when the configuration systems are unified
// and the ruby configuration text files no longer exist. Also,
// it would be great to remove the single ruby_hit_callback func with
// separate pointers to particular ports to rubymem. However, functional
// access currently prevent the improvement.
//
for (int i = 0; i < params()->num_cpus; i++) {
RubyPort *p = RubySystem::getPort(csprintf("Sequencer_%d", i),
ruby_hit_callback);
ruby_ports.push_back(p);
}
for (int i = 0; i < params()->num_dmas; i++) {
RubyPort *p = RubySystem::getPort(csprintf("DMASequencer_%d", i),
ruby_hit_callback);
ruby_dma_ports.push_back(p);
}
pio_port = NULL;
}
void
RubyMemory::init()
{
if (params()->debug) {
g_debug_ptr->setVerbosityString("high");
g_debug_ptr->setDebugTime(1);
if (!params()->debug_file.empty()) {
g_debug_ptr->setDebugOutputFile(params()->debug_file.c_str());
}
}
//You may want to set some other options...
//g_debug_ptr->setVerbosityString("med");
//g_debug_ptr->setFilterString("lsNqST");
//g_debug_ptr->setFilterString("lsNST");
//g_debug_ptr->setDebugTime(1);
//g_debug_ptr->setDebugOutputFile("ruby.debug");
g_system_ptr->clearStats();
if (ports.size() == 0) {
fatal("RubyMemory object %s is unconnected!", name());
}
for (PortIterator pi = ports.begin(); pi != ports.end(); ++pi) {
if (*pi)
(*pi)->sendStatusChange(Port::RangeChange);
}
for (PortIterator pi = dma_ports.begin(); pi != dma_ports.end(); ++pi) {
if (*pi)
(*pi)->sendStatusChange(Port::RangeChange);
}
if (pio_port != NULL) {
pio_port->sendStatusChange(Port::RangeChange);
}
//Print stats at exit
rubyExitCB = new RubyExitCallback(this);
registerExitCallback(rubyExitCB);
//Sched RubyEvent, automatically reschedules to advance ruby cycles
rubyTickEvent = new RubyEvent(this);
schedule(rubyTickEvent, curTick + ruby_clock + ruby_phase);
}
//called by rubyTickEvent
void
RubyMemory::tick()
{
RubyEventQueue *eq = RubySystem::getEventQueue();
eq->triggerEvents(eq->getTime() + 1);
schedule(rubyTickEvent, curTick + ruby_clock);
}
RubyMemory::~RubyMemory()
{
delete g_system_ptr;
}
Port *
RubyMemory::getPort(const std::string &if_name, int idx)
{
DPRINTF(Ruby, "getting port %d %s\n", idx, if_name);
DPRINTF(Ruby,
"number of ruby ports %d and dma ports %d\n",
ruby_ports.size(),
ruby_dma_ports.size());
// Accept request for "functional" port for backwards compatibility
// with places where this function is called from C++. I'd prefer
// to move all these into Python someday.
if (if_name == "functional") {
return new Port(csprintf("%s-functional", name()),
this,
ruby_ports[idx]);
}
//
// if dma port request, allocate the appropriate prot
//
if (if_name == "dma_port") {
assert(idx < ruby_dma_ports.size());
RubyMemory::Port* dma_port =
new Port(csprintf("%s-dma_port%d", name(), idx),
this,
ruby_dma_ports[idx]);
dma_ports.push_back(dma_port);
return dma_port;
}
//
// if pio port, ensure that there is only one
//
if (if_name == "pio_port") {
assert(pio_port == NULL);
pio_port =
new RubyMemory::Port("ruby_pio_port", this, NULL);
return pio_port;
}
if (if_name != "port") {
panic("RubyMemory::getPort: unknown port %s requested", if_name);
}
if (idx >= (int)ports.size()) {
ports.resize(idx+1);
}
if (ports[idx] != NULL) {
panic("RubyMemory::getPort: port %d already assigned", idx);
}
//
// Currently this code assumes that each cpu has both a
// icache and dcache port and therefore divides by two. This will be
// fixed once we unify the configuration systems and Ruby sequencers
// directly support M5 ports.
//
assert(idx/2 < ruby_ports.size());
Port *port = new Port(csprintf("%s-port%d", name(), idx),
this,
ruby_ports[idx/2]);
ports[idx] = port;
return port;
}
RubyMemory::Port::Port(const std::string &_name,
RubyMemory *_memory,
RubyPort *_port)
: PhysicalMemory::MemoryPort::MemoryPort(_name, _memory)
{
DPRINTF(Ruby, "creating port to ruby memory %s\n", _name);
ruby_mem = _memory;
ruby_port = _port;
}
bool
RubyMemory::Port::recvTiming(PacketPtr pkt)
{
DPRINTF(MemoryAccess,
"Timing access caught for address %#x\n",
pkt->getAddr());
//dsm: based on SimpleTimingPort::recvTiming(pkt);
//
// In FS mode, ruby memory will receive pio responses from devices and
// it must forward these responses back to the particular CPU.
//
if (pkt->isResponse() != false && isPioAddress(pkt->getAddr()) != false) {
DPRINTF(MemoryAccess,
"Pio Response callback %#x\n",
pkt->getAddr());
RubyMemory::SenderState *senderState =
safe_cast<RubyMemory::SenderState *>(pkt->senderState);
RubyMemory::Port *port = senderState->port;
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->sendTiming(pkt);
return true;
}
//
// After checking for pio responses, the remainder of packets
// received by ruby should only be M5 requests, which should never
// get nacked. There used to be code to hanldle nacks here, but
// I'm pretty sure it didn't work correctly with the drain code,
// so that would need to be fixed if we ever added it back.
//
assert(pkt->isRequest());
if (pkt->memInhibitAsserted()) {
warn("memInhibitAsserted???");
// snooper will supply based on copy of packet
// still target's responsibility to delete packet
delete pkt;
return true;
}
// Save the port in the sender state object
pkt->senderState = new SenderState(this, pkt->senderState);
//
// Check for pio requests and directly send them to the dedicated
// pio_port.
//
if (isPioAddress(pkt->getAddr()) != false) {
return ruby_mem->pio_port->sendTiming(pkt);
}
//
// For DMA and CPU requests, translate them to ruby requests before
// sending them to our assigned ruby port.
//
RubyRequestType type = RubyRequestType_NULL;
Addr pc = 0;
if (pkt->isRead()) {
if (pkt->req->isInstFetch()) {
type = RubyRequestType_IFETCH;
pc = pkt->req->getPC();
} else {
type = RubyRequestType_LD;
}
} else if (pkt->isWrite()) {
type = RubyRequestType_ST;
} else if (pkt->isReadWrite()) {
// type = RubyRequestType_RMW;
}
RubyRequest ruby_request(pkt->getAddr(), pkt->getPtr<uint8_t>(),
pkt->getSize(), pc, type,
RubyAccessMode_Supervisor);
// Submit the ruby request
int64_t req_id = ruby_port->makeRequest(ruby_request);
if (req_id == -1) {
RubyMemory::SenderState *senderState =
safe_cast<RubyMemory::SenderState *>(pkt->senderState);
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
return false;
}
// Save the request for the callback
RubyMemory::pending_requests[req_id] = pkt;
return true;
}
void
ruby_hit_callback(int64_t req_id)
{
//
// Note: This single fuction can be called by cpu and dma ports,
// as well as the functional port. The functional port prevents
// us from replacing this single function with separate port
// functions.
//
typedef map<int64_t, PacketPtr> map_t;
map_t &prm = RubyMemory::pending_requests;
map_t::iterator i = prm.find(req_id);
if (i == prm.end())
panic("could not find pending request %d\n", req_id);
PacketPtr pkt = i->second;
prm.erase(i);
RubyMemory::SenderState *senderState =
safe_cast<RubyMemory::SenderState *>(pkt->senderState);
RubyMemory::Port *port = senderState->port;
// pop the sender state from the packet
pkt->senderState = senderState->saved;
delete senderState;
port->hitCallback(pkt);
}
void
RubyMemory::Port::hitCallback(PacketPtr pkt)
{
bool needsResponse = pkt->needsResponse();
DPRINTF(MemoryAccess, "Hit callback needs response %d\n",
needsResponse);
ruby_mem->doAtomicAccess(pkt);
// turn packet around to go back to requester if response expected
if (needsResponse) {
// recvAtomic() should already have turned packet into
// atomic response
assert(pkt->isResponse());
DPRINTF(MemoryAccess, "Sending packet back over port\n");
sendTiming(pkt);
} else {
delete pkt;
}
DPRINTF(MemoryAccess, "Hit callback done!\n");
}
bool
RubyMemory::Port::sendTiming(PacketPtr pkt)
{
schedSendTiming(pkt, curTick + 1); //minimum latency, must be > 0
return true;
}
bool
RubyMemory::Port::isPioAddress(Addr addr)
{
AddrRangeList pioAddrList;
bool snoop = false;
if (ruby_mem->pio_port == NULL) {
return false;
}
ruby_mem->pio_port->getPeerAddressRanges(pioAddrList, snoop);
for(AddrRangeIter iter = pioAddrList.begin(); iter != pioAddrList.end(); iter++) {
if (addr >= iter->start && addr <= iter->end) {
DPRINTF(MemoryAccess, "Pio request found in %#llx - %#llx range\n",
iter->start, iter->end);
return true;
}
}
return false;
}
void RubyMemory::printConfigStats()
{
std::ostream *os = simout.create(params()->stats_file);
RubySystem::printConfig(*os);
*os << endl;
RubySystem::printStats(*os);
}
//Right now these functions seem to be called by RubySystem. If they do calls
// to RubySystem perform it intended actions, you'll get into an inf loop
//FIXME what's the purpose of these here?
void RubyMemory::printStats(std::ostream & out) const {
//g_system_ptr->printConfig(out);
}
void RubyMemory::clearStats() {
//g_system_ptr->clearStats();
}
void RubyMemory::printConfig(std::ostream & out) const {
//g_system_ptr->printConfig(out);
}
void RubyMemory::serialize(ostream &os)
{
PhysicalMemory::serialize(os);
}
void RubyMemory::unserialize(Checkpoint *cp, const string §ion)
{
DPRINTF(Config, "Ruby memory being restored\n");
reschedule(rubyTickEvent, curTick + ruby_clock + ruby_phase);
PhysicalMemory::unserialize(cp, section);
}
//Python-interface code
RubyMemory *
RubyMemoryParams::create()
{
return new RubyMemory(this);
}
<|endoftext|> |
<commit_before>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <httpd.h>
#include <http_config.h>
#include <http_request.h>
#include <http_protocol.h>
#include <http_connection.h>
#include <apr_pools.h>
#include <apr_hooks.h>
#include "apr_strings.h"
#include <unistd.h>
#include <curl/curl.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <exception>
#include <set>
#include <sstream>
#include <sys/syscall.h>
#include "mod_migrate.hh"
#define MOD_REWRITE_NAME "mod_rewrite.c"
#define MOD_PROXY_NAME "mod_proxy.c"
#define MOD_PROXY_HTTP_NAME "mod_proxy_http.c"
namespace alg = boost::algorithm;
namespace MigrateModule {
const char *gNameBody2Brigade = "MigrateBody2Brigade";
const char* c_COMPONENT_VERSION = "Migrate/1.0";
const char* setActive(cmd_parms* pParams, void* pCfg) {
struct MigrateConf *lConf = reinterpret_cast<MigrateConf *>(pCfg);
if (!lConf) {
return "No per_dir conf defined. This should never happen!";
}
// No dir name initialized
if (!(lConf->mDirName)) {
lConf->mDirName = (char *) apr_pcalloc(pParams->pool, sizeof(char) * (strlen(pParams->path) + 1));
strcpy(lConf->mDirName, pParams->path);
}
#ifndef UNIT_TESTING
if (!ap_find_linked_module(MOD_REWRITE_NAME)) {
return "'mod_rewrite' is not loaded, Enable mod_rewrite to use mod_migrate";
}
if (!ap_find_linked_module(MOD_PROXY_NAME)) {
return "'mod_proxy' is not loaded, Enable mod_proxy to use mod_migrate";
}
if (!ap_find_linked_module(MOD_PROXY_HTTP_NAME)) {
return "'mod_proxy_http' is not loaded, Enable mod_proxy_http to use mod_migrate";
}
#endif
return NULL;
}
const char* setApplicationScope(cmd_parms* pParams, void* pCfg, const char* pAppScope) {
const char *lErrorMsg = setActive(pParams, pCfg);
if (lErrorMsg) {
return lErrorMsg;
}
struct MigrateConf *tC = reinterpret_cast<MigrateConf *>(pCfg);
try {
tC->mCurrentApplicationScope = MigrateModule::ApplicationScope::stringToEnum(pAppScope);
} catch (std::exception& e) {
return MigrateModule::ApplicationScope::c_ERROR_ON_STRING_VALUE;
}
return NULL;
}
const char* setMigrateEnv(cmd_parms* pParams, void* pCfg, const char *pVarName, const char* pMatchRegex, const char* pSetValue) {
const char *lErrorMsg = setActive(pParams, pCfg);
if (lErrorMsg) {
return lErrorMsg;
}
struct MigrateConf *conf = reinterpret_cast<MigrateConf *>(pCfg);
assert(conf);
MigrateConf::MigrateEnv env{pVarName,boost::regex(pMatchRegex),pSetValue,conf->mCurrentApplicationScope};
conf->mEnvLists[pParams->path].push_back(env);
return NULL;
}
/**
* @brief allocate a pointer to a string which will hold the path for the dir config if mod_compare is active on it
* @param pPool the apache pool on which to allocate data
* @param pDirName the directory name for which to create data
* @return a void pointer to newly allocated object
*/
void* createDirConfig(apr_pool_t *pPool, char *pDirName)
{
void *addr= apr_pcalloc(pPool, sizeof(class MigrateConf));
new (addr) MigrateConf();
apr_pool_cleanup_register(pPool, addr, cleaner<MigrateConf>, apr_pool_cleanup_null);
return addr;
}
/**
* @brief Initialize logging post-config
* @param pPool the apache pool
* @param pServer the corresponding server record
* @return Always OK
*/
int postConfig(apr_pool_t * pPool, apr_pool_t * pLog, apr_pool_t * pTemp, server_rec * pServer) {
Log::init();
ap_add_version_component(pPool, c_COMPONENT_VERSION) ;
return APR_SUCCESS;
}
/** @brief Declaration of configuration commands */
command_rec gCmds[] = {
// AP_INIT_(directive,
// function,
// void * extra data,
// overrides to allow in order to enable,
// help message),
AP_INIT_TAKE1("MigrateApplicationScope",
reinterpret_cast<const char *(*)()>(&setApplicationScope),
0,
ACCESS_CONF,
"Sets the application scope of the filters and subsitution rules that follow this declaration"),
AP_INIT_TAKE3("MigrateEnv",
reinterpret_cast<const char *(*)()>(&setMigrateEnv),
0,
ACCESS_CONF,
"Enrich apache context with some variable."
"Usage: DupEnrichContext VarName MatchRegex SetRegex"
"VarName: The name of the variable to define"
"MatchRegex: The regex that must match to define the variable"
"SetRegex: The value to set if MatchRegex matches"),
{0}
};
#ifndef UNIT_TESTING
static void insertInputFilter(request_rec *pRequest) {
MigrateConf *lConf = reinterpret_cast<MigrateConf *>(ap_get_module_config(pRequest->per_dir_config, &migrate_module));
assert(lConf);
if (lConf->mDirName){
ap_add_input_filter(gNameBody2Brigade, NULL, pRequest, pRequest->connection);
}
}
#endif
/**
* @brief register hooks in apache
* @param pPool the apache pool
*/
void registerHooks(apr_pool_t *pPool) {
#ifndef UNIT_TESTING
ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE);
// Here we want to be almost the last filter
ap_register_input_filter(gNameBody2Brigade, inputFilterBody2Brigade, NULL, AP_FTYPE_CONTENT_SET);
static const char * const beforeRewrite[] = {MOD_REWRITE_NAME, NULL};
ap_hook_translate_name(&translateHook, NULL, beforeRewrite, APR_HOOK_MIDDLE);
ap_hook_insert_filter(&insertInputFilter, NULL, NULL, APR_HOOK_FIRST);
#endif
}
} // End namespace
/// Apache module declaration
module AP_MODULE_DECLARE_DATA migrate_module = {
STANDARD20_MODULE_STUFF,
MigrateModule::createDirConfig,
0, // merge_dir_config
0, // create_server_config
0, // merge_server_config
MigrateModule::gCmds,
MigrateModule::registerHooks
};
<commit_msg>Now regex is case insensitive<commit_after>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <httpd.h>
#include <http_config.h>
#include <http_request.h>
#include <http_protocol.h>
#include <http_connection.h>
#include <apr_pools.h>
#include <apr_hooks.h>
#include "apr_strings.h"
#include <unistd.h>
#include <curl/curl.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <exception>
#include <set>
#include <sstream>
#include <sys/syscall.h>
#include "mod_migrate.hh"
#define MOD_REWRITE_NAME "mod_rewrite.c"
#define MOD_PROXY_NAME "mod_proxy.c"
#define MOD_PROXY_HTTP_NAME "mod_proxy_http.c"
namespace alg = boost::algorithm;
namespace MigrateModule {
const char *gNameBody2Brigade = "MigrateBody2Brigade";
const char* c_COMPONENT_VERSION = "Migrate/1.0";
const char* setActive(cmd_parms* pParams, void* pCfg) {
struct MigrateConf *lConf = reinterpret_cast<MigrateConf *>(pCfg);
if (!lConf) {
return "No per_dir conf defined. This should never happen!";
}
// No dir name initialized
if (!(lConf->mDirName)) {
lConf->mDirName = (char *) apr_pcalloc(pParams->pool, sizeof(char) * (strlen(pParams->path) + 1));
strcpy(lConf->mDirName, pParams->path);
}
#ifndef UNIT_TESTING
if (!ap_find_linked_module(MOD_REWRITE_NAME)) {
return "'mod_rewrite' is not loaded, Enable mod_rewrite to use mod_migrate";
}
if (!ap_find_linked_module(MOD_PROXY_NAME)) {
return "'mod_proxy' is not loaded, Enable mod_proxy to use mod_migrate";
}
if (!ap_find_linked_module(MOD_PROXY_HTTP_NAME)) {
return "'mod_proxy_http' is not loaded, Enable mod_proxy_http to use mod_migrate";
}
#endif
return NULL;
}
const char* setApplicationScope(cmd_parms* pParams, void* pCfg, const char* pAppScope) {
const char *lErrorMsg = setActive(pParams, pCfg);
if (lErrorMsg) {
return lErrorMsg;
}
struct MigrateConf *tC = reinterpret_cast<MigrateConf *>(pCfg);
try {
tC->mCurrentApplicationScope = MigrateModule::ApplicationScope::stringToEnum(pAppScope);
} catch (std::exception& e) {
return MigrateModule::ApplicationScope::c_ERROR_ON_STRING_VALUE;
}
return NULL;
}
const char* setMigrateEnv(cmd_parms* pParams, void* pCfg, const char *pVarName, const char* pMatchRegex, const char* pSetValue) {
const char *lErrorMsg = setActive(pParams, pCfg);
if (lErrorMsg) {
return lErrorMsg;
}
struct MigrateConf *conf = reinterpret_cast<MigrateConf *>(pCfg);
assert(conf);
MigrateConf::MigrateEnv env{pVarName,boost::regex(pMatchRegex,boost::regex_constants::icase),pSetValue,conf->mCurrentApplicationScope};
conf->mEnvLists[pParams->path].push_back(env);
return NULL;
}
/**
* @brief allocate a pointer to a string which will hold the path for the dir config if mod_compare is active on it
* @param pPool the apache pool on which to allocate data
* @param pDirName the directory name for which to create data
* @return a void pointer to newly allocated object
*/
void* createDirConfig(apr_pool_t *pPool, char *pDirName)
{
void *addr= apr_pcalloc(pPool, sizeof(class MigrateConf));
new (addr) MigrateConf();
apr_pool_cleanup_register(pPool, addr, cleaner<MigrateConf>, apr_pool_cleanup_null);
return addr;
}
/**
* @brief Initialize logging post-config
* @param pPool the apache pool
* @param pServer the corresponding server record
* @return Always OK
*/
int postConfig(apr_pool_t * pPool, apr_pool_t * pLog, apr_pool_t * pTemp, server_rec * pServer) {
Log::init();
ap_add_version_component(pPool, c_COMPONENT_VERSION) ;
return APR_SUCCESS;
}
/** @brief Declaration of configuration commands */
command_rec gCmds[] = {
// AP_INIT_(directive,
// function,
// void * extra data,
// overrides to allow in order to enable,
// help message),
AP_INIT_TAKE1("MigrateApplicationScope",
reinterpret_cast<const char *(*)()>(&setApplicationScope),
0,
ACCESS_CONF,
"Sets the application scope of the filters and subsitution rules that follow this declaration"),
AP_INIT_TAKE3("MigrateEnv",
reinterpret_cast<const char *(*)()>(&setMigrateEnv),
0,
ACCESS_CONF,
"Enrich apache context with some variable."
"Usage: DupEnrichContext VarName MatchRegex SetRegex"
"VarName: The name of the variable to define"
"MatchRegex: The regex that must match to define the variable"
"SetRegex: The value to set if MatchRegex matches"),
{0}
};
#ifndef UNIT_TESTING
static void insertInputFilter(request_rec *pRequest) {
MigrateConf *lConf = reinterpret_cast<MigrateConf *>(ap_get_module_config(pRequest->per_dir_config, &migrate_module));
assert(lConf);
if (lConf->mDirName){
ap_add_input_filter(gNameBody2Brigade, NULL, pRequest, pRequest->connection);
}
}
#endif
/**
* @brief register hooks in apache
* @param pPool the apache pool
*/
void registerHooks(apr_pool_t *pPool) {
#ifndef UNIT_TESTING
ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE);
// Here we want to be almost the last filter
ap_register_input_filter(gNameBody2Brigade, inputFilterBody2Brigade, NULL, AP_FTYPE_CONTENT_SET);
static const char * const beforeRewrite[] = {MOD_REWRITE_NAME, NULL};
ap_hook_translate_name(&translateHook, NULL, beforeRewrite, APR_HOOK_MIDDLE);
ap_hook_insert_filter(&insertInputFilter, NULL, NULL, APR_HOOK_FIRST);
#endif
}
} // End namespace
/// Apache module declaration
module AP_MODULE_DECLARE_DATA migrate_module = {
STANDARD20_MODULE_STUFF,
MigrateModule::createDirConfig,
0, // merge_dir_config
0, // create_server_config
0, // merge_server_config
MigrateModule::gCmds,
MigrateModule::registerHooks
};
<|endoftext|> |
<commit_before>///
/// @file P2_mpi.cpp
/// @brief 2nd partial sieve function.
/// P2(x, y) counts the numbers <= x that have exactly 2 prime
/// factors each exceeding the a-th prime.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <BitSieve.hpp>
#include <generate.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <mpi_reduce_sum.hpp>
#include <pmath.hpp>
#include <print.hpp>
#include <Wheel.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
/// Calculate the segments per thread.
/// The idea is to gradually increase the segments per thread (based
/// on elapsed time) in order to keep all CPU cores busy.
///
int64_t balanceLoad(int64_t segments_per_thread, double start_time)
{
double seconds = get_wtime() - start_time;
if (seconds < 30)
segments_per_thread *= 2;
else if (segments_per_thread >= 4)
segments_per_thread -= segments_per_thread / 4;
return segments_per_thread;
}
/// Cross-off the multiples inside [low, high[
/// of the primes <= sqrt(high - 1).
///
void cross_off(BitSieve& sieve,
vector<int32_t> primes,
Wheel& wheel,
int64_t c,
int64_t low,
int64_t high)
{
int64_t pi_sqrt_high = pi_bsearch(primes, isqrt(high - 1));
for (int64_t i = c + 1; i <= pi_sqrt_high; i++)
{
int64_t prime = primes[i];
int64_t m = wheel[i].next_multiple;
int64_t wheel_index = wheel[i].wheel_index;
// cross-off the multiples of prime inside [low, high[
for (; m < high; m += prime * Wheel::next_multiple_factor(&wheel_index))
sieve.unset(m - low);
wheel[i].set(m, wheel_index);
}
}
template <typename T>
T P2_OpenMP_thread(T x,
int64_t y,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
int64_t& pix,
int64_t& pix_count,
vector<int32_t>& primes)
{
pix = 0;
pix_count = 0;
low += thread_num * segments_per_thread * segment_size;
limit = min(low + segments_per_thread * segment_size, limit);
int64_t size = pi_bsearch(primes, isqrt(limit)) + 1;
int64_t start = (int64_t) max(x / limit + 1, y);
int64_t stop = (int64_t) min(x / low, isqrt(x));
T P2_thread = 0;
// P2_thread = \sum_{i = pi[start]}^{pi[stop]} pi(x / primes[i]) - pi(low - 1)
// We use a reverse prime iterator to calculate P2_thread
primesieve::iterator pi(stop + 1, start);
int64_t prime = pi.previous_prime();
bool sieve_primes = true;
Wheel wheel(primes, size, low, sieve_primes);
BitSieve sieve(segment_size);
// segmented sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t x_div_prime = 0;
int64_t j = 0;
int64_t c = 6;
// pre-sieve the multiples of the first c primes
sieve.pre_sieve(c, low, sieve_primes);
// cross-off the multiples of the primes <= sqrt(high - 1)
cross_off(sieve, primes, wheel, c, low, high);
while (prime >= start &&
(x_div_prime = (int64_t) (x / prime)) < high)
{
int64_t next_count = x_div_prime - low;
pix += sieve.count(j, next_count);
j = next_count + 1;
pix_count++;
P2_thread += pix;
prime = pi.previous_prime();
}
pix += sieve.count(j, (high - 1) - low);
}
return P2_thread;
}
/// P2_mpi_master(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime, a = pi(y).
/// Space complexity: O((x / y)^(1/2)).
///
template <typename T>
T P2_mpi_master(T x, int64_t y, int threads)
{
#if __cplusplus >= 201103L
static_assert(prt::is_signed<T>::value,
"P2(T x, ...): T must be signed integer type");
#endif
if (x < 4)
return 0;
T a = pi_legendre(y, threads);
T b = pi_legendre((int64_t) isqrt(x), threads);
if (a >= b)
return 0;
int64_t low = 2;
int64_t limit = (int64_t)(x / max(y, 1));
int64_t sqrt_limit = isqrt(limit);
int64_t segment_size = max(sqrt_limit, 1 << 12);
int64_t segments_per_thread = 64;
threads = validate_threads(threads, limit);
vector<int32_t> primes = generate_primes(sqrt_limit);
aligned_vector<int64_t> pix(threads);
aligned_vector<int64_t> pix_counts(threads);
int proc_id = mpi_proc_id();
int procs = mpi_num_procs();
int64_t interval = limit - low;
int64_t interval_per_proc = ceil_div(interval, procs);
low += interval_per_proc * proc_id;
limit = min(low + interval_per_proc, limit);
// \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1)
T p2 = 0;
// \sum_{i=a+1}^{b} -(i - 1)
if (is_mpi_master_proc())
p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;
// temporarily disable printing for pi()
bool is_print = print_status();
set_print_status(false);
T pix_total = pi(low - 1, threads);
set_print_status(is_print);
// \sum_{i=a+1}^{b} pi(x / primes[i])
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
double time = get_wtime();
#pragma omp parallel for \
num_threads(threads) reduction(+: p2)
for (int i = 0; i < threads; i++)
p2 += P2_OpenMP_thread(x, y, segment_size, segments_per_thread,
i, low, limit, pix[i], pix_counts[i], primes);
low += segments_per_thread * threads * segment_size;
segments_per_thread = balanceLoad(segments_per_thread, time);
// Add missing sum contributions in order
for (int i = 0; i < threads; i++)
{
p2 += pix_total * pix_counts[i];
pix_total += pix[i];
}
if (print_status())
{
double percent = get_percent((double) low, (double) limit);
cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
<< percent << '%' << flush;
}
}
p2 = mpi_reduce_sum(p2);
return p2;
}
} // namespace
namespace primecount {
int64_t P2_mpi(int64_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int64_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#ifdef HAVE_INT128_T
int128_t P2_mpi(int128_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int128_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#endif
} // namespace primecount
<commit_msg>Simplify MPI code<commit_after>///
/// @file P2_mpi.cpp
/// @brief 2nd partial sieve function.
/// P2(x, y) counts the numbers <= x that have exactly 2 prime
/// factors each exceeding the a-th prime.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <BitSieve.hpp>
#include <generate.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <mpi_reduce_sum.hpp>
#include <pmath.hpp>
#include <print.hpp>
#include <Wheel.hpp>
#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
using namespace primecount;
namespace {
/// Calculate the segments per thread.
/// The idea is to gradually increase the segments per thread (based
/// on elapsed time) in order to keep all CPU cores busy.
///
int64_t balanceLoad(int64_t segments_per_thread, double start_time)
{
double seconds = get_wtime() - start_time;
if (seconds < 30)
segments_per_thread *= 2;
else if (segments_per_thread >= 4)
segments_per_thread -= segments_per_thread / 4;
return segments_per_thread;
}
/// Cross-off the multiples inside [low, high[
/// of the primes <= sqrt(high - 1).
///
void cross_off(BitSieve& sieve,
vector<int32_t> primes,
Wheel& wheel,
int64_t c,
int64_t low,
int64_t high)
{
int64_t pi_sqrt_high = pi_bsearch(primes, isqrt(high - 1));
for (int64_t i = c + 1; i <= pi_sqrt_high; i++)
{
int64_t prime = primes[i];
int64_t m = wheel[i].next_multiple;
int64_t wheel_index = wheel[i].wheel_index;
// cross-off the multiples of prime inside [low, high[
for (; m < high; m += prime * Wheel::next_multiple_factor(&wheel_index))
sieve.unset(m - low);
wheel[i].set(m, wheel_index);
}
}
template <typename T>
T P2_OpenMP_thread(T x,
int64_t y,
int64_t segment_size,
int64_t segments_per_thread,
int64_t thread_num,
int64_t low,
int64_t limit,
int64_t& pix,
int64_t& pix_count,
vector<int32_t>& primes)
{
pix = 0;
pix_count = 0;
low += thread_num * segments_per_thread * segment_size;
limit = min(low + segments_per_thread * segment_size, limit);
int64_t size = pi_bsearch(primes, isqrt(limit)) + 1;
int64_t start = (int64_t) max(x / limit + 1, y);
int64_t stop = (int64_t) min(x / low, isqrt(x));
T P2_thread = 0;
// P2_thread = \sum_{i = pi[start]}^{pi[stop]} pi(x / primes[i]) - pi(low - 1)
// We use a reverse prime iterator to calculate P2_thread
primesieve::iterator pi(stop + 1, start);
int64_t prime = pi.previous_prime();
bool sieve_primes = true;
Wheel wheel(primes, size, low, sieve_primes);
BitSieve sieve(segment_size);
// segmented sieve of Eratosthenes
for (; low < limit; low += segment_size)
{
// current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t x_div_prime = 0;
int64_t j = 0;
int64_t c = 6;
// pre-sieve the multiples of the first c primes
sieve.pre_sieve(c, low, sieve_primes);
// cross-off the multiples of the primes <= sqrt(high - 1)
cross_off(sieve, primes, wheel, c, low, high);
while (prime >= start &&
(x_div_prime = (int64_t) (x / prime)) < high)
{
int64_t next_count = x_div_prime - low;
pix += sieve.count(j, next_count);
j = next_count + 1;
pix_count++;
P2_thread += pix;
prime = pi.previous_prime();
}
pix += sieve.count(j, (high - 1) - low);
}
return P2_thread;
}
/// P2_mpi_master(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime, a = pi(y).
/// Space complexity: O((x / y)^(1/2)).
///
template <typename T>
T P2_mpi_master(T x, int64_t y, int threads)
{
#if __cplusplus >= 201103L
static_assert(prt::is_signed<T>::value,
"P2(T x, ...): T must be signed integer type");
#endif
if (x < 4)
return 0;
T a = pi_legendre(y, threads);
T b = pi_legendre((int64_t) isqrt(x), threads);
if (a >= b)
return 0;
int64_t low = 2;
int64_t limit = (int64_t)(x / max(y, 1));
int64_t sqrt_limit = isqrt(limit);
int64_t segment_size = max(sqrt_limit, 1 << 12);
int64_t segments_per_thread = 64;
threads = validate_threads(threads, limit);
vector<int32_t> primes = generate_primes(sqrt_limit);
aligned_vector<int64_t> pix(threads);
aligned_vector<int64_t> pix_counts(threads);
int proc_id = mpi_proc_id();
int procs = mpi_num_procs();
int64_t interval = limit - low;
int64_t interval_per_proc = ceil_div(interval, procs);
low += interval_per_proc * proc_id;
limit = min(low + interval_per_proc, limit);
// \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1)
T p2 = 0;
// \sum_{i=a+1}^{b} -(i - 1)
if (is_mpi_master_proc())
p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;
T pix_total = pi_legendre(low - 1, threads);
// \sum_{i=a+1}^{b} pi(x / primes[i])
while (low < limit)
{
int64_t segments = ceil_div(limit - low, segment_size);
threads = in_between(1, threads, segments);
segments_per_thread = in_between(1, segments_per_thread, ceil_div(segments, threads));
double time = get_wtime();
#pragma omp parallel for \
num_threads(threads) reduction(+: p2)
for (int i = 0; i < threads; i++)
p2 += P2_OpenMP_thread(x, y, segment_size, segments_per_thread,
i, low, limit, pix[i], pix_counts[i], primes);
low += segments_per_thread * threads * segment_size;
segments_per_thread = balanceLoad(segments_per_thread, time);
// Add missing sum contributions in order
for (int i = 0; i < threads; i++)
{
p2 += pix_total * pix_counts[i];
pix_total += pix[i];
}
if (print_status())
{
double percent = get_percent((double) low, (double) limit);
cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
<< percent << '%' << flush;
}
}
p2 = mpi_reduce_sum(p2);
return p2;
}
} // namespace
namespace primecount {
int64_t P2_mpi(int64_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int64_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#ifdef HAVE_INT128_T
int128_t P2_mpi(int128_t x, int64_t y, int threads)
{
print("");
print("=== P2_mpi(x, y) ===");
print("Computation of the 2nd partial sieve function");
print(x, y, threads);
double time = get_wtime();
int128_t p2 = P2_mpi_master(x, y, threads);
print("P2", p2, time);
return p2;
}
#endif
} // namespace primecount
<|endoftext|> |
<commit_before>/*
Segments are organized into a list (vector) such that any object that serves
as a center (reference) for a body appears earlier
a 'center' appears earlier in the list than any object tha
(such as barycenters) are placed before any bodies that are computed
with reference to them.
For this reason body 3 (Earth-Moon barycenter)
referenced to the solar system barycenter 0, is placed before 399 (Earth)
or 301 (moon). This sorting is done by placing bodies <= 10 at the begining
of the list. The order of succeeding bodies is irrelevant
*/
#include <fstream>
#include "spk.hpp"
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"
namespace orrery {
namespace daffile {
void SpkSegment::compute(double jd, OrreryBody& body)
{
}
//8sII60sIII8s603s28s297s
// (locidw, self.nd, self.n_integers, self.internal_name, self.initial_record, self.final_record,
// self.free, numeric_format, self.prenul, self._validation_ftpstr, self.pstnul
const std::string ftp_validation_template = "FTPSTR:\r:\n:\r\n:\r\x00:\x81:\x10\xce:ENDFTP";
struct FileRecord {
char file_architecture[8];
u_int32_t n_double_precision;
u_int32_t n_integers;
char internal_name[60];
u_int32_t initial_record;
u_int32_t final_record;
u_int32_t first_free_address;
char numeric_format[8];
char zeros_1[603];
char ftp_validation_str[28];
char zeros_2[297];
};
bool load_file_record(std::ifstream& nasa_spk_file, FileRecord& hdr)
{
nasa_spk_file.read((char*)(FileRecord*)&hdr, sizeof(hdr));
LOG_S(INFO) << "File architecture: " << hdr.file_architecture;
LOG_S(INFO) << "Internal name: " << hdr.internal_name;
LOG_S(INFO) << "Numeric format: " << hdr.numeric_format;
if (ftp_validation_template.compare(hdr.ftp_validation_str) != 0) {
LOG_S(ERROR) << "This file is likely corrupted: FTP validation fails";
return false;
}
return true;
}
//TODO: Handle files of both endian-ness
bool SpkOrrery::load_orrery_model(std::string fname)
{
std::ifstream nasa_spk_file(fname, std::ios::binary);
if (!nasa_spk_file) {
LOG_S(ERROR) << "Could not open " << fname;
ok = false;
return false;
}
FileRecord hdr;
if (!load_file_record(nasa_spk_file, hdr)) {
ok = false;
return false;
}
return true;
}
// Fill out the (x, y, z) of each Orrery body and return us an immutable
// vector containing this information.
const OrreryBodyVec& SpkOrrery::get_orrery_at(double jd)
{
for (int i = 0; i < bodies.size(); i++) {
segments[i].compute(jd, bodies[i]);
if (segments[i].center != 0) {
bodies[i].pos += bodies[segments[i].center_i].pos;
}
}
return bodies;
}
}
}
<commit_msg>added SPK comment processing<commit_after>/*
Segments are organized into a list (vector) such that any object that serves
as a center (reference) for a body appears earlier
a 'center' appears earlier in the list than any object tha
(such as barycenters) are placed before any bodies that are computed
with reference to them.
For this reason body 3 (Earth-Moon barycenter)
referenced to the solar system barycenter 0, is placed before 399 (Earth)
or 301 (moon). This sorting is done by placing bodies <= 10 at the begining
of the list. The order of succeeding bodies is irrelevant
Thanks go to JPL/NASA NAIF docs
ftp://naif.jpl.nasa.gov/pub/naif/toolkit_docs/FORTRAN/req/daf.html
And jplemphem Python code by Brandon Rhodes
https://github.com/brandon-rhodes/python-jplephem
*/
#include <fstream>
#include "spk.hpp"
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"
namespace orrery {
namespace daffile {
const size_t block_size = 1024;
void SpkSegment::compute(double jd, OrreryBody& body)
{
}
const std::string ftp_validation_template = "FTPSTR:\r:\n:\r\n:\r\x00:\x81:\x10\xce:ENDFTP";
struct FileRecord {
char file_architecture[8]; // LOCIDW
u_int32_t n_double_precision; // ND
u_int32_t n_integers; // NI
char internal_name[60]; // LOCIFN
u_int32_t n_initial_summary; // FWARD
u_int32_t n_final_summary; // BWARD
u_int32_t first_free_address; // FREE
char numeric_format[8]; // LOCFMT
char zeros_1[603]; //PRENUL
char ftp_validation_str[28]; //FTPSTR
char zeros_2[297]; //PSTNUL
};
bool read_file_record(std::ifstream& nasa_spk_file, FileRecord& hdr)
{
nasa_spk_file.read((char*)(FileRecord*)&hdr, sizeof(hdr));
LOG_S(INFO) << "File architecture: " << hdr.file_architecture;
LOG_S(INFO) << "Internal name: " << hdr.internal_name;
LOG_S(INFO) << "Numeric format: " << hdr.numeric_format;
if (ftp_validation_template.compare(hdr.ftp_validation_str) != 0) {
LOG_S(ERROR) << "This file is likely corrupted: FTP validation fails";
return false;
}
return true;
}
void parse_daf_comment(char a[block_size])
{
for(int i = 0; i < 1000; i++) {
switch (a[i]) {
case '\0': a[i] = '\n'; break;
case '\4': a[i] = '\0';
i = 1000;
break;
default: break;
}
}
}
std::string read_comment_blocks(std::ifstream& nasa_spk_file, size_t n_initial_summary)
{
std::string comment;
nasa_spk_file.seekg( block_size );
for(int i = 1; i < n_initial_summary - 1; i++) {
char raw_comment[block_size];
nasa_spk_file.read(raw_comment, block_size);
parse_daf_comment(raw_comment);
comment += raw_comment;
}
return comment;
}
//TODO: Handle files of both endian-ness
bool SpkOrrery::load_orrery_model(std::string fname)
{
std::ifstream nasa_spk_file(fname, std::ios::binary);
if (!nasa_spk_file) {
LOG_S(ERROR) << "Could not open " << fname;
ok = false;
return false;
}
FileRecord hdr;
if (!read_file_record(nasa_spk_file, hdr)) {
ok = false;
return false;
}
std::string comment = read_comment_blocks(nasa_spk_file, hdr.n_initial_summary);
//std::cout << comment;
ok = true;
return ok;
}
// Fill out the (x, y, z) of each Orrery body and return us an immutable
// vector containing this information.
const OrreryBodyVec& SpkOrrery::get_orrery_at(double jd)
{
for (int i = 0; i < bodies.size(); i++) {
segments[i].compute(jd, bodies[i]);
if (segments[i].center != 0) {
bodies[i].pos += bodies[segments[i].center_i].pos;
}
}
return bodies;
}
}
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetHaddTest.cpp
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHaddTest
#include "JPetBarrelSlot/JPetBarrelSlot.h"
#include "JPetEvent/JPetEvent.h"
#include "JPetReader/JPetReader.h"
#include "JPetScin/JPetScin.h"
#include "JPetTimeWindow/JPetTimeWindow.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
BOOST_AUTO_TEST_SUITE(JPetHaddTestSuite)
std::string exec(std::string cmd)
{
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
BOOST_AUTO_TEST_CASE(hadd_test)
{
std::string resultFileName = "";
std::string firstFileName = "unitTestData/JPetHaddTest/dabc_17237091818.hadd.test.root";
std::string secondFileName = "unitTestData/JPetHaddTest/dabc_17237093844.hadd.test.root";
#if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0)
resultFileName = "unitTestData/JPetHaddTest/result_root5.hadd.test.root";
#else
resultFileName = "unitTestData/JPetHaddTest/result_root6.hadd.test.root";
#endif
exec("hadd -f " + resultFileName + " " + firstFileName + " " + secondFileName);
JPetReader readerFirstFile("unitTestData/JPetHaddTest/dabc_17237091818.hadd.test.root");
JPetReader readerSecondFile("unitTestData/JPetHaddTest/dabc_17237093844.hadd.test.root");
JPetReader readerResultFile(resultFileName.c_str());
BOOST_REQUIRE(readerFirstFile.isOpen());
BOOST_REQUIRE(readerSecondFile.isOpen());
BOOST_REQUIRE(readerResultFile.isOpen());
BOOST_REQUIRE_EQUAL(std::string(readerFirstFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerSecondFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerResultFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
long long firstFileNumberOfEntries = readerFirstFile.getNbOfAllEntries();
long long secondFileNumberOfEntries = readerSecondFile.getNbOfAllEntries();
long long resultFileNumberOfEntires = readerResultFile.getNbOfAllEntries();
BOOST_REQUIRE_EQUAL(resultFileNumberOfEntires, firstFileNumberOfEntries + secondFileNumberOfEntries);
for (long long i = 0; i < resultFileNumberOfEntires; i++) {
const auto& timeWindow = static_cast<const JPetTimeWindow&>(readerResultFile.getCurrentEntry());
const auto& secondTimeWindow = i < firstFileNumberOfEntries ? static_cast<const JPetTimeWindow&>(readerFirstFile.getCurrentEntry())
: static_cast<const JPetTimeWindow&>(readerSecondFile.getCurrentEntry());
BOOST_REQUIRE_EQUAL(timeWindow.getNumberOfEvents(), secondTimeWindow.getNumberOfEvents());
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (timeWindow.getNumberOfEvents())(0));
for (size_t i = 0; i < timeWindow.getNumberOfEvents(); i++) {
const auto& event = static_cast<const JPetEvent&>(timeWindow[i]);
const auto& secondEvent = static_cast<const JPetEvent&>(secondTimeWindow[i]);
const auto& hits = event.getHits();
const auto& secondHits = secondEvent.getHits();
BOOST_REQUIRE_EQUAL(hits.size(), secondHits.size());
for (unsigned int i = 0; i < hits.size(); i++) {
BOOST_REQUIRE_EQUAL(hits[i].getPosX(), secondHits[i].getPosX());
BOOST_REQUIRE_EQUAL(hits[i].getPosY(), secondHits[i].getPosY());
BOOST_REQUIRE_EQUAL(hits[i].getPosZ(), secondHits[i].getPosZ());
BOOST_REQUIRE_EQUAL(hits[i].getEnergy(), secondHits[i].getEnergy());
BOOST_REQUIRE_EQUAL(hits[i].getQualityOfEnergy(), secondHits[i].getQualityOfEnergy());
BOOST_REQUIRE_EQUAL(hits[i].getTime(), secondHits[i].getTime());
BOOST_REQUIRE_EQUAL(hits[i].getTimeDiff(), secondHits[i].getTimeDiff());
BOOST_REQUIRE_EQUAL(hits[i].getQualityOfTime(), secondHits[i].getQualityOfTime());
BOOST_REQUIRE_EQUAL(hits[i].getQualityOfTimeDiff(), secondHits[i].getQualityOfTimeDiff());
BOOST_REQUIRE(hits[i].getScintillator() == secondHits[i].getScintillator());
BOOST_REQUIRE(hits[i].getBarrelSlot() == secondHits[i].getBarrelSlot());
}
}
readerResultFile.nextEntry();
if (i < firstFileNumberOfEntries)
readerFirstFile.nextEntry();
else
readerSecondFile.nextEntry();
}
}
BOOST_AUTO_TEST_SUITE_END()<commit_msg>Change path to test file<commit_after>/**
* @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetHaddTest.cpp
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHaddTest
#include "JPetBarrelSlot/JPetBarrelSlot.h"
#include "JPetEvent/JPetEvent.h"
#include "JPetReader/JPetReader.h"
#include "JPetScin/JPetScin.h"
#include "JPetTimeWindow/JPetTimeWindow.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
BOOST_AUTO_TEST_SUITE(JPetHaddTestSuite)
std::string exec(std::string cmd)
{
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
BOOST_AUTO_TEST_CASE(hadd_test)
{
std::string resultFileName = "";
std::string firstFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237091818.hadd.test.root";
std::string secondFileName = "unitTestData/JPetHaddTest/single_link_def/dabc_17237093844.hadd.test.root";
#if ROOT_VERSION_CODE < ROOT_VERSION(6, 0, 0)
resultFileName = "unitTestData/JPetHaddTest/result_root5.hadd.test.root";
#else
resultFileName = "unitTestData/JPetHaddTest/result_root6.hadd.test.root";
#endif
exec("hadd -f " + resultFileName + " " + firstFileName + " " + secondFileName);
JPetReader readerFirstFile(firstFileName);
JPetReader readerSecondFile(secondFileName);
JPetReader readerResultFile(resultFileName.c_str());
BOOST_REQUIRE(readerFirstFile.isOpen());
BOOST_REQUIRE(readerSecondFile.isOpen());
BOOST_REQUIRE(readerResultFile.isOpen());
BOOST_REQUIRE_EQUAL(std::string(readerFirstFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerSecondFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(std::string(readerResultFile.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
long long firstFileNumberOfEntries = readerFirstFile.getNbOfAllEntries();
long long secondFileNumberOfEntries = readerSecondFile.getNbOfAllEntries();
long long resultFileNumberOfEntires = readerResultFile.getNbOfAllEntries();
BOOST_REQUIRE_EQUAL(resultFileNumberOfEntires, firstFileNumberOfEntries + secondFileNumberOfEntries);
for (long long i = 0; i < resultFileNumberOfEntires; i++) {
const auto& timeWindow = static_cast<const JPetTimeWindow&>(readerResultFile.getCurrentEntry());
const auto& secondTimeWindow = i < firstFileNumberOfEntries ? static_cast<const JPetTimeWindow&>(readerFirstFile.getCurrentEntry())
: static_cast<const JPetTimeWindow&>(readerSecondFile.getCurrentEntry());
BOOST_REQUIRE_EQUAL(timeWindow.getNumberOfEvents(), secondTimeWindow.getNumberOfEvents());
BOOST_CHECK_PREDICATE(std::not_equal_to<size_t>(), (timeWindow.getNumberOfEvents())(0));
for (size_t i = 0; i < timeWindow.getNumberOfEvents(); i++) {
const auto& event = static_cast<const JPetEvent&>(timeWindow[i]);
const auto& secondEvent = static_cast<const JPetEvent&>(secondTimeWindow[i]);
const auto& hits = event.getHits();
const auto& secondHits = secondEvent.getHits();
BOOST_REQUIRE_EQUAL(hits.size(), secondHits.size());
for (unsigned int i = 0; i < hits.size(); i++) {
BOOST_REQUIRE_EQUAL(hits[i].getPosX(), secondHits[i].getPosX());
BOOST_REQUIRE_EQUAL(hits[i].getPosY(), secondHits[i].getPosY());
BOOST_REQUIRE_EQUAL(hits[i].getPosZ(), secondHits[i].getPosZ());
BOOST_REQUIRE_EQUAL(hits[i].getEnergy(), secondHits[i].getEnergy());
BOOST_REQUIRE_EQUAL(hits[i].getQualityOfEnergy(), secondHits[i].getQualityOfEnergy());
BOOST_REQUIRE_EQUAL(hits[i].getTime(), secondHits[i].getTime());
BOOST_REQUIRE_EQUAL(hits[i].getTimeDiff(), secondHits[i].getTimeDiff());
BOOST_REQUIRE_EQUAL(hits[i].getQualityOfTime(), secondHits[i].getQualityOfTime());
BOOST_REQUIRE_EQUAL(hits[i].getQualityOfTimeDiff(), secondHits[i].getQualityOfTimeDiff());
BOOST_REQUIRE(hits[i].getScintillator() == secondHits[i].getScintillator());
BOOST_REQUIRE(hits[i].getBarrelSlot() == secondHits[i].getBarrelSlot());
}
}
readerResultFile.nextEntry();
if (i < firstFileNumberOfEntries)
readerFirstFile.nextEntry();
else
readerSecondFile.nextEntry();
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "headers.h"
#include "init.h"
#include "qtipcserver.h"
#include "util.h"
#include <QApplication>
#include <QMessageBox>
#include <QThread>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
// Need a global reference for the notifications to find the GUI
BitcoinGUI *guiref;
QSplashScreen *splashref;
int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
// Message from AppInit2(), always in main thread before main window is constructed
QMessageBox::critical(0, QString::fromStdString(caption),
QString::fromStdString(message),
QMessageBox::Ok, QMessageBox::Ok);
return 4;
}
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
bool modal = style & wxMODAL;
if (modal)
while (!guiref)
Sleep(1000);
// Message from network thread
if(guiref)
{
QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
// Call slot on GUI thread.
// If called from another thread, use a blocking QueuedConnection.
Qt::ConnectionType connectionType = Qt::DirectConnection;
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
connectionType = Qt::BlockingQueuedConnection;
}
QMetaObject::invokeMethod(guiref, "askFee", connectionType,
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
// Call slot on GUI thread.
// If called from another thread, use a blocking QueuedConnection.
Qt::ConnectionType connectionType = Qt::DirectConnection;
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
connectionType = Qt::BlockingQueuedConnection;
}
QMetaObject::invokeMethod(guiref, "handleURI", connectionType,
Q_ARG(QString, QString::fromStdString(strURI)));
}
void CalledSetStatusBar(const std::string& strText, int nField)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void UIThreadCall(boost::function0<void> fn)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void MainFrameRepaint()
{
if(guiref)
QMetaObject::invokeMethod(guiref, "refreshStatusBar", Qt::QueuedConnection);
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if(mq.try_send(strURI, strlen(strURI), 0))
exit(0);
else
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
break;
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!ReadConfigFile(mapArgs, mapMultiArgs))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
return 1;
}
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Bitcoin");
app.setOrganizationDomain("bitcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Bitcoin-Qt-testnet");
else
app.setApplicationName("Bitcoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale ("en_US") from command line or system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_')); // "en"
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
if (!qtTranslatorBase.isEmpty())
app.installTranslator(&qtTranslatorBase);
qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
if (!qtTranslator.isEmpty())
app.installTranslator(&qtTranslator);
translatorBase.load(":/translations/"+lang);
if (!translatorBase.isEmpty())
app.installTranslator(&translatorBase);
translator.load(":/translations/"+lang_territory);
if (!translator.isEmpty())
app.installTranslator(&translator);
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that BitcoinGUI is cleaned up properly before
// calling Shutdown() in case of exceptions.
optionsModel.Upgrade(); // Must be done after AppInit2
BitcoinGUI window;
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
guiref = &window;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit();
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
}
}
}
#endif
app.exec();
window.hide();
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<commit_msg>When datadir missing, show messagebox instead of printing error to stderr<commit_after>/*
* W.J. van der Laan 2011-2012
*/
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "headers.h"
#include "init.h"
#include "qtipcserver.h"
#include "util.h"
#include <QApplication>
#include <QMessageBox>
#include <QThread>
#include <QTextCodec>
#include <QLocale>
#include <QTranslator>
#include <QSplashScreen>
#include <QLibraryInfo>
#include <boost/interprocess/ipc/message_queue.hpp>
// Need a global reference for the notifications to find the GUI
BitcoinGUI *guiref;
QSplashScreen *splashref;
int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
// Message from AppInit2(), always in main thread before main window is constructed
QMessageBox::critical(0, QString::fromStdString(caption),
QString::fromStdString(message),
QMessageBox::Ok, QMessageBox::Ok);
return 4;
}
int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y)
{
bool modal = style & wxMODAL;
if (modal)
while (!guiref)
Sleep(1000);
// Message from network thread
if(guiref)
{
QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(bool, modal));
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
}
return 4;
}
bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent)
{
if(!guiref)
return false;
if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
// Call slot on GUI thread.
// If called from another thread, use a blocking QueuedConnection.
Qt::ConnectionType connectionType = Qt::DirectConnection;
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
connectionType = Qt::BlockingQueuedConnection;
}
QMetaObject::invokeMethod(guiref, "askFee", connectionType,
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
void ThreadSafeHandleURI(const std::string& strURI)
{
if(!guiref)
return;
// Call slot on GUI thread.
// If called from another thread, use a blocking QueuedConnection.
Qt::ConnectionType connectionType = Qt::DirectConnection;
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
connectionType = Qt::BlockingQueuedConnection;
}
QMetaObject::invokeMethod(guiref, "handleURI", connectionType,
Q_ARG(QString, QString::fromStdString(strURI)));
}
void CalledSetStatusBar(const std::string& strText, int nField)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void UIThreadCall(boost::function0<void> fn)
{
// Only used for built-in mining, which is disabled, simple ignore
}
void MainFrameRepaint()
{
if(guiref)
QMetaObject::invokeMethod(guiref, "refreshStatusBar", Qt::QueuedConnection);
}
void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
QApplication::instance()->processEvents();
}
}
void QueueShutdown()
{
QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
}
/*
Translate string to current locale using Qt.
*/
std::string _(const char* psz)
{
return QCoreApplication::translate("bitcoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Do this early as we don't want to bother initializing if we are just calling IPC
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if(mq.try_send(strURI, strlen(strURI), 0))
exit(0);
else
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
break;
}
}
}
#endif
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Command-line options take precedence:
ParseParameters(argc, argv);
// ... then bitcoin.conf:
if (!ReadConfigFile(mapArgs, mapMultiArgs))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, "Bitcoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
app.setOrganizationName("Bitcoin");
app.setOrganizationDomain("bitcoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
app.setApplicationName("Bitcoin-Qt-testnet");
else
app.setApplicationName("Bitcoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale ("en_US") from command line or system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_')); // "en"
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang);
if (!qtTranslatorBase.isEmpty())
app.installTranslator(&qtTranslatorBase);
qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory);
if (!qtTranslator.isEmpty())
app.installTranslator(&qtTranslator);
translatorBase.load(":/translations/"+lang);
if (!translatorBase.isEmpty())
app.installTranslator(&translatorBase);
translator.load(":/translations/"+lang_territory);
if (!translator.isEmpty())
app.installTranslator(&translator);
QSplashScreen splash(QPixmap(":/images/splash"), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
if(AppInit2(argc, argv))
{
{
// Put this in a block, so that BitcoinGUI is cleaned up properly before
// calling Shutdown() in case of exceptions.
optionsModel.Upgrade(); // Must be done after AppInit2
BitcoinGUI window;
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
guiref = &window;
window.setClientModel(&clientModel);
window.setWalletModel(&walletModel);
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Place this here as guiref has to be defined if we don't want to lose URIs
ipcInit();
#if !defined(MAC_OSX) && !defined(WIN32)
// TODO: implement qtipcserver.cpp for Mac and Windows
// Check for URI in argv
for (int i = 1; i < argc; i++)
{
if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0)
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
mq.try_send(strURI, strlen(strURI), 0);
}
catch (boost::interprocess::interprocess_exception &ex) {
}
}
}
#endif
app.exec();
window.hide();
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Bitcoin-Qt here
Shutdown(NULL);
}
else
{
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
<|endoftext|> |
<commit_before>/* This file is part of qjson
*
* Copyright (C) 2009 Till Adam <adam@kde.org>
* Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "serializer.h"
#include <QtCore/QDataStream>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
#include <cmath>
using namespace QJson;
class Serializer::SerializerPrivate {
public:
SerializerPrivate() : specialNumbersAllowed(false) {}
bool specialNumbersAllowed;
QString sanitizeString( QString str );
};
QString Serializer::SerializerPrivate::sanitizeString( QString str )
{
str.replace( QLatin1String( "\\" ), QLatin1String( "\\\\" ) );
// escape unicode chars
QString result;
const ushort* unicode = str.utf16();
unsigned int i = 0;
while ( unicode[ i ] ) {
if ( unicode[ i ] < 128 ) {
result.append( QChar( unicode[ i ] ) );
}
else {
QString hexCode = QString::number( unicode[ i ], 16 ).rightJustified( 4,
QLatin1Char('0') );
result.append( QLatin1String ("\\u") ).append( hexCode );
}
++i;
}
str = result;
str.replace( QLatin1String( "\"" ), QLatin1String( "\\\"" ) );
str.replace( QLatin1String( "\b" ), QLatin1String( "\\b" ) );
str.replace( QLatin1String( "\f" ), QLatin1String( "\\f" ) );
str.replace( QLatin1String( "\n" ), QLatin1String( "\\n" ) );
str.replace( QLatin1String( "\r" ), QLatin1String( "\\r" ) );
str.replace( QLatin1String( "\t" ), QLatin1String( "\\t" ) );
return QString( QLatin1String( "\"%1\"" ) ).arg( str );
}
Serializer::Serializer()
: d( new SerializerPrivate )
{
}
Serializer::~Serializer() {
delete d;
}
void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
Q_ASSERT( io );
if (!io->isOpen()) {
if (!io->open(QIODevice::WriteOnly)) {
if ( ok != 0 )
*ok = false;
qCritical ("Error opening device");
return;
}
}
if (!io->isWritable()) {
if (ok != 0)
*ok = false;
qCritical ("Device is not readable");
io->close();
return;
}
const QByteArray str = serialize( v );
if ( !str.isNull() ) {
QDataStream stream( io );
stream << str;
} else {
if ( ok )
*ok = false;
}
}
static QByteArray join( const QList<QByteArray>& list, const QByteArray& sep ) {
QByteArray res;
Q_FOREACH( const QByteArray& i, list ) {
if ( !res.isEmpty() )
res += sep;
res += i;
}
return res;
}
QByteArray Serializer::serialize( const QVariant &v )
{
QByteArray str;
bool error = false;
if ( ! v.isValid() ) { // invalid or null?
str = "null";
} else if (( v.type() == QVariant::List ) || ( v.type() == QVariant::StringList )){ // an array or a stringlist?
const QVariantList list = v.toList();
QList<QByteArray> values;
Q_FOREACH( const QVariant& v, list )
{
QByteArray serializedValue = serialize( v );
if ( serializedValue.isNull() ) {
error = true;
break;
}
values << serializedValue;
}
str = "[ " + join( values, ", " ) + " ]";
} else if ( v.type() == QVariant::Map ) { // variant is a map?
const QVariantMap vmap = v.toMap();
QMapIterator<QString, QVariant> it( vmap );
str = "{ ";
QList<QByteArray> pairs;
while ( it.hasNext() ) {
it.next();
QByteArray serializedValue = serialize( it.value() );
if ( serializedValue.isNull() ) {
error = true;
break;
}
pairs << d->sanitizeString( it.key() ).toUtf8() + " : " + serializedValue;
}
str += join( pairs, ", " );
str += " }";
} else if (( v.type() == QVariant::String ) || ( v.type() == QVariant::ByteArray )) { // a string or a byte array?
str = d->sanitizeString( v.toString() ).toUtf8();
} else if (( v.type() == QVariant::Double) || (v.type() == QMetaType::Float)) { // a double or a float?
const double value = v.toDouble();
const bool special = std::isnan(value) || std::isinf(value);
if (special) {
if (specialNumbersAllowed()) {
if (std::isnan(value)) {
str += "NaN";
} else {
if (value<0) {
str += "-";
}
str += "Infinity";
}
} else {
qCritical("Attempt to write NaN or infinity, which is not supported by json");
error = true;
}
} else {
str = QByteArray::number( value );
if( ! str.contains( "." ) && ! str.contains( "e" ) ) {
str += ".0";
}
}
} else if ( v.type() == QVariant::Bool ) { // boolean value?
str = ( v.toBool() ? "true" : "false" );
} else if ( v.type() == QVariant::ULongLong ) { // large unsigned number?
str = QByteArray::number( v.value<qulonglong>() );
} else if ( v.canConvert<qlonglong>() ) { // any signed number?
str = QByteArray::number( v.value<qlonglong>() );
} else if ( v.canConvert<QString>() ){ // can value be converted to string?
// this will catch QDate, QDateTime, QUrl, ...
str = d->sanitizeString( v.toString() ).toUtf8();
//TODO: catch other values like QImage, QRect, ...
} else {
error = true;
}
if ( !error )
return str;
else
return QByteArray();
}
void QJson::Serializer::allowSpecialNumbers(bool allow) {
d->specialNumbersAllowed = allow;
}
bool QJson::Serializer::specialNumbersAllowed() const {
return d->specialNumbersAllowed;
}
<commit_msg>Fixed compilation on Visual Studio 2010 (and probably also 2008/2005). Patch provided by Toni Jovanoski.<commit_after>/* This file is part of qjson
*
* Copyright (C) 2009 Till Adam <adam@kde.org>
* Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "serializer.h"
#include <QtCore/QDataStream>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
#include <cmath>
using namespace QJson;
class Serializer::SerializerPrivate {
public:
SerializerPrivate() : specialNumbersAllowed(false) {}
bool specialNumbersAllowed;
QString sanitizeString( QString str );
};
QString Serializer::SerializerPrivate::sanitizeString( QString str )
{
str.replace( QLatin1String( "\\" ), QLatin1String( "\\\\" ) );
// escape unicode chars
QString result;
const ushort* unicode = str.utf16();
unsigned int i = 0;
while ( unicode[ i ] ) {
if ( unicode[ i ] < 128 ) {
result.append( QChar( unicode[ i ] ) );
}
else {
QString hexCode = QString::number( unicode[ i ], 16 ).rightJustified( 4,
QLatin1Char('0') );
result.append( QLatin1String ("\\u") ).append( hexCode );
}
++i;
}
str = result;
str.replace( QLatin1String( "\"" ), QLatin1String( "\\\"" ) );
str.replace( QLatin1String( "\b" ), QLatin1String( "\\b" ) );
str.replace( QLatin1String( "\f" ), QLatin1String( "\\f" ) );
str.replace( QLatin1String( "\n" ), QLatin1String( "\\n" ) );
str.replace( QLatin1String( "\r" ), QLatin1String( "\\r" ) );
str.replace( QLatin1String( "\t" ), QLatin1String( "\\t" ) );
return QString( QLatin1String( "\"%1\"" ) ).arg( str );
}
Serializer::Serializer()
: d( new SerializerPrivate )
{
}
Serializer::~Serializer() {
delete d;
}
void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
Q_ASSERT( io );
if (!io->isOpen()) {
if (!io->open(QIODevice::WriteOnly)) {
if ( ok != 0 )
*ok = false;
qCritical ("Error opening device");
return;
}
}
if (!io->isWritable()) {
if (ok != 0)
*ok = false;
qCritical ("Device is not readable");
io->close();
return;
}
const QByteArray str = serialize( v );
if ( !str.isNull() ) {
QDataStream stream( io );
stream << str;
} else {
if ( ok )
*ok = false;
}
}
static QByteArray join( const QList<QByteArray>& list, const QByteArray& sep ) {
QByteArray res;
Q_FOREACH( const QByteArray& i, list ) {
if ( !res.isEmpty() )
res += sep;
res += i;
}
return res;
}
QByteArray Serializer::serialize( const QVariant &v )
{
QByteArray str;
bool error = false;
if ( ! v.isValid() ) { // invalid or null?
str = "null";
} else if (( v.type() == QVariant::List ) || ( v.type() == QVariant::StringList )){ // an array or a stringlist?
const QVariantList list = v.toList();
QList<QByteArray> values;
Q_FOREACH( const QVariant& v, list )
{
QByteArray serializedValue = serialize( v );
if ( serializedValue.isNull() ) {
error = true;
break;
}
values << serializedValue;
}
str = "[ " + join( values, ", " ) + " ]";
} else if ( v.type() == QVariant::Map ) { // variant is a map?
const QVariantMap vmap = v.toMap();
QMapIterator<QString, QVariant> it( vmap );
str = "{ ";
QList<QByteArray> pairs;
while ( it.hasNext() ) {
it.next();
QByteArray serializedValue = serialize( it.value() );
if ( serializedValue.isNull() ) {
error = true;
break;
}
pairs << d->sanitizeString( it.key() ).toUtf8() + " : " + serializedValue;
}
str += join( pairs, ", " );
str += " }";
} else if (( v.type() == QVariant::String ) || ( v.type() == QVariant::ByteArray )) { // a string or a byte array?
str = d->sanitizeString( v.toString() ).toUtf8();
} else if (( v.type() == QVariant::Double) || (v.type() == QMetaType::Float)) { // a double or a float?
const double value = v.toDouble();
#ifdef _WIN32
const bool special = _isnan(value) || !_finite(value);
#else
const bool special = std::isnan(value) || std::isinf(value);
#endif
if (special) {
if (specialNumbersAllowed()) {
#ifdef _WIN32
if (_isnan(value)) {
#else
if (std::isnan(value)) {
#endif
str += "NaN";
} else {
if (value<0) {
str += "-";
}
str += "Infinity";
}
} else {
qCritical("Attempt to write NaN or infinity, which is not supported by json");
error = true;
}
} else {
str = QByteArray::number( value );
if( ! str.contains( "." ) && ! str.contains( "e" ) ) {
str += ".0";
}
}
} else if ( v.type() == QVariant::Bool ) { // boolean value?
str = ( v.toBool() ? "true" : "false" );
} else if ( v.type() == QVariant::ULongLong ) { // large unsigned number?
str = QByteArray::number( v.value<qulonglong>() );
} else if ( v.canConvert<qlonglong>() ) { // any signed number?
str = QByteArray::number( v.value<qlonglong>() );
} else if ( v.canConvert<QString>() ){ // can value be converted to string?
// this will catch QDate, QDateTime, QUrl, ...
str = d->sanitizeString( v.toString() ).toUtf8();
//TODO: catch other values like QImage, QRect, ...
} else {
error = true;
}
if ( !error )
return str;
else
return QByteArray();
}
void QJson::Serializer::allowSpecialNumbers(bool allow) {
d->specialNumbersAllowed = allow;
}
bool QJson::Serializer::specialNumbersAllowed() const {
return d->specialNumbersAllowed;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Filter.hxx"
#include "CompletionHandler.hxx"
#include "lib/openssl/Error.hxx"
#include "lib/openssl/Name.hxx"
#include "lib/openssl/UniqueX509.hxx"
#include "FifoBufferBio.hxx"
#include "fs/ThreadSocketFilter.hxx"
#include "memory/fb_pool.hxx"
#include "memory/SliceFifoBuffer.hxx"
#include "util/AllocatedArray.hxx"
#include "util/AllocatedString.hxx"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <assert.h>
#include <string.h>
class SslFilter final : public ThreadSocketFilterHandler,
SslCompletionHandler {
/**
* Buffers which can be accessed from within the thread without
* holding locks. These will be copied to/from the according
* #thread_socket_filter buffers.
*/
SliceFifoBuffer encrypted_input, decrypted_input,
plain_output, encrypted_output;
const UniqueSSL ssl;
bool handshaking = true;
AllocatedArray<unsigned char> alpn_selected;
public:
AllocatedString peer_subject, peer_issuer_subject;
SslFilter(UniqueSSL &&_ssl)
:ssl(std::move(_ssl)) {
SSL_set_bio(ssl.get(),
NewFifoBufferBio(encrypted_input),
NewFifoBufferBio(encrypted_output));
SetSslCompletionHandler(*ssl, *this);
}
std::span<const unsigned char> GetAlpnSelected() const noexcept {
return {alpn_selected.data(), alpn_selected.size()};
}
private:
/**
* Called from inside Run() right after the handshake has
* completed. This is used to collect some data for our
* public getters.
*/
void PostHandshake() noexcept;
void Encrypt();
/* virtual methods from class ThreadSocketFilterHandler */
void PreRun(ThreadSocketFilterInternal &f) noexcept override;
void Run(ThreadSocketFilterInternal &f) override;
void PostRun(ThreadSocketFilterInternal &f) noexcept override;
void CancelRun(ThreadSocketFilterInternal &f) noexcept override;
/* virtual methods from class SslCompletionHandler */
void OnSslCompletion() noexcept override {
ScheduleRun();
}
};
static AllocatedString
format_subject_name(X509 *cert)
{
return ToString(X509_get_subject_name(cert));
}
static AllocatedString
format_issuer_subject_name(X509 *cert)
{
return ToString(X509_get_issuer_name(cert));
}
[[gnu::pure]]
static bool
is_ssl_error(SSL *ssl, int ret)
{
if (ret == 0)
/* this is always an error according to the documentation of
SSL_read(), SSL_write() and SSL_do_handshake() */
return true;
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_X509_LOOKUP:
return false;
default:
return true;
}
}
static void
CheckThrowSslError(SSL *ssl, int result)
{
if (is_ssl_error(ssl, result))
throw SslError();
}
inline void
SslFilter::PostHandshake() noexcept
{
const unsigned char *alpn_data;
unsigned int alpn_length;
SSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length);
if (alpn_length > 0)
alpn_selected = std::span<const unsigned char>(alpn_data,
alpn_length);
UniqueX509 cert(SSL_get_peer_certificate(ssl.get()));
if (cert != nullptr) {
peer_subject = format_subject_name(cert.get());
peer_issuer_subject = format_issuer_subject_name(cert.get());
}
}
enum class SslDecryptResult {
SUCCESS,
/**
* More encrypted_input data is required.
*/
MORE,
CLOSE_NOTIFY_ALERT,
};
static SslDecryptResult
ssl_decrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer)
{
/* SSL_read() must be called repeatedly until there is no more
data (or until the buffer is full) */
while (true) {
auto w = buffer.Write();
if (w.empty())
return SslDecryptResult::SUCCESS;
int result = SSL_read(ssl, w.data(), w.size());
if (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ)
return SslDecryptResult::MORE;
if (result <= 0) {
if (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN)
/* got a "close notify" alert from the peer */
return SslDecryptResult::CLOSE_NOTIFY_ALERT;
CheckThrowSslError(ssl, result);
return SslDecryptResult::SUCCESS;
}
buffer.Append(result);
}
}
static void
ssl_encrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer)
{
/* SSL_write() must be called repeatedly until there is no more
data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes
only the current incomplete record, and additional data which
has been submitted more recently will only be considered in the
next SSL_write() call */
while (true) {
auto r = buffer.Read();
if (r.empty())
return;
int result = SSL_write(ssl, r.data(), r.size());
if (result <= 0) {
CheckThrowSslError(ssl, result);
return;
}
buffer.Consume(result);
}
}
inline void
SslFilter::Encrypt()
{
ssl_encrypt(ssl.get(), plain_output);
}
/*
* thread_socket_filter_handler
*
*/
void
SslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept
{
if (f.IsIdle()) {
decrypted_input.AllocateIfNull(fb_pool_get());
encrypted_output.AllocateIfNull(fb_pool_get());
}
}
void
SslFilter::Run(ThreadSocketFilterInternal &f)
{
/* copy input (and output to make room for more output) */
{
std::unique_lock<std::mutex> lock(f.mutex);
if (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) {
/* retry, let PreRun() allocate the missing buffer */
f.again = true;
return;
}
f.decrypted_input.MoveFromAllowNull(decrypted_input);
plain_output.MoveFromAllowNull(f.plain_output);
encrypted_input.MoveFromAllowSrcNull(f.encrypted_input);
f.encrypted_output.MoveFromAllowNull(encrypted_output);
if (decrypted_input.IsNull() || encrypted_output.IsNull()) {
/* retry, let PreRun() allocate the missing buffer */
f.again = true;
return;
}
}
/* let OpenSSL work */
ERR_clear_error();
if (handshaking) [[unlikely]] {
int result = SSL_do_handshake(ssl.get());
if (result == 1) {
handshaking = false;
PostHandshake();
} else {
try {
CheckThrowSslError(ssl.get(), result);
/* flush the encrypted_output buffer, because it may
contain a "TLS alert" */
} catch (...) {
const std::lock_guard<std::mutex> lock(f.mutex);
f.encrypted_output.MoveFromAllowNull(encrypted_output);
throw;
}
}
}
if (!handshaking) [[likely]] {
Encrypt();
switch (ssl_decrypt(ssl.get(), decrypted_input)) {
case SslDecryptResult::SUCCESS:
break;
case SslDecryptResult::MORE:
if (encrypted_input.IsDefinedAndFull())
throw std::runtime_error("SSL encrypted_input buffer is full");
break;
case SslDecryptResult::CLOSE_NOTIFY_ALERT:
{
std::unique_lock<std::mutex> lock(f.mutex);
f.input_eof = true;
}
break;
}
}
/* copy output */
{
std::unique_lock<std::mutex> lock(f.mutex);
f.decrypted_input.MoveFromAllowNull(decrypted_input);
f.encrypted_output.MoveFromAllowNull(encrypted_output);
f.drained = plain_output.empty() && encrypted_output.empty();
if (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty())
/* there's more data to be decrypted and we
still have room in the destination buffer,
so let's run again */
f.again = true;
if (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() &&
!encrypted_output.IsDefinedAndFull())
/* there's more data, and we're ready to handle it: try
again */
f.again = true;
f.handshaking = handshaking;
}
}
void
SslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept
{
if (f.IsIdle()) {
plain_output.FreeIfEmpty();
encrypted_input.FreeIfEmpty();
decrypted_input.FreeIfEmpty();
encrypted_output.FreeIfEmpty();
}
}
void
SslFilter::CancelRun(ThreadSocketFilterInternal &) noexcept
{
if (cancel_ptr)
/* cancel the CertCache::Apply() call */
cancel_ptr.Cancel();
}
/*
* constructor
*
*/
std::unique_ptr<ThreadSocketFilterHandler>
ssl_filter_new(UniqueSSL &&ssl) noexcept
{
return std::make_unique<SslFilter>(std::move(ssl));
}
SslFilter &
ssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept
{
return static_cast<SslFilter &>(tsfh);
}
const SslFilter *
ssl_filter_cast_from(const SocketFilter *socket_filter) noexcept
{
const auto *tsf = dynamic_cast<const ThreadSocketFilter *>(socket_filter);
if (tsf == nullptr)
return nullptr;
return dynamic_cast<const SslFilter *>(&tsf->GetHandler());
}
std::span<const unsigned char>
ssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept
{
return ssl.GetAlpnSelected();
}
const char *
ssl_filter_get_peer_subject(const SslFilter &ssl) noexcept
{
return ssl.peer_subject.c_str();
}
const char *
ssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept
{
return ssl.peer_issuer_subject.c_str();
}
<commit_msg>ssl/Filter: rename is_ssl_error() to IsSslError()<commit_after>/*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Filter.hxx"
#include "CompletionHandler.hxx"
#include "lib/openssl/Error.hxx"
#include "lib/openssl/Name.hxx"
#include "lib/openssl/UniqueX509.hxx"
#include "FifoBufferBio.hxx"
#include "fs/ThreadSocketFilter.hxx"
#include "memory/fb_pool.hxx"
#include "memory/SliceFifoBuffer.hxx"
#include "util/AllocatedArray.hxx"
#include "util/AllocatedString.hxx"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <assert.h>
#include <string.h>
class SslFilter final : public ThreadSocketFilterHandler,
SslCompletionHandler {
/**
* Buffers which can be accessed from within the thread without
* holding locks. These will be copied to/from the according
* #thread_socket_filter buffers.
*/
SliceFifoBuffer encrypted_input, decrypted_input,
plain_output, encrypted_output;
const UniqueSSL ssl;
bool handshaking = true;
AllocatedArray<unsigned char> alpn_selected;
public:
AllocatedString peer_subject, peer_issuer_subject;
SslFilter(UniqueSSL &&_ssl)
:ssl(std::move(_ssl)) {
SSL_set_bio(ssl.get(),
NewFifoBufferBio(encrypted_input),
NewFifoBufferBio(encrypted_output));
SetSslCompletionHandler(*ssl, *this);
}
std::span<const unsigned char> GetAlpnSelected() const noexcept {
return {alpn_selected.data(), alpn_selected.size()};
}
private:
/**
* Called from inside Run() right after the handshake has
* completed. This is used to collect some data for our
* public getters.
*/
void PostHandshake() noexcept;
void Encrypt();
/* virtual methods from class ThreadSocketFilterHandler */
void PreRun(ThreadSocketFilterInternal &f) noexcept override;
void Run(ThreadSocketFilterInternal &f) override;
void PostRun(ThreadSocketFilterInternal &f) noexcept override;
void CancelRun(ThreadSocketFilterInternal &f) noexcept override;
/* virtual methods from class SslCompletionHandler */
void OnSslCompletion() noexcept override {
ScheduleRun();
}
};
static AllocatedString
format_subject_name(X509 *cert)
{
return ToString(X509_get_subject_name(cert));
}
static AllocatedString
format_issuer_subject_name(X509 *cert)
{
return ToString(X509_get_issuer_name(cert));
}
[[gnu::pure]]
static bool
IsSslError(SSL *ssl, int ret) noexcept
{
if (ret == 0)
/* this is always an error according to the documentation of
SSL_read(), SSL_write() and SSL_do_handshake() */
return true;
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_NONE:
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_X509_LOOKUP:
return false;
default:
return true;
}
}
static void
CheckThrowSslError(SSL *ssl, int result)
{
if (IsSslError(ssl, result))
throw SslError();
}
inline void
SslFilter::PostHandshake() noexcept
{
const unsigned char *alpn_data;
unsigned int alpn_length;
SSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length);
if (alpn_length > 0)
alpn_selected = std::span<const unsigned char>(alpn_data,
alpn_length);
UniqueX509 cert(SSL_get_peer_certificate(ssl.get()));
if (cert != nullptr) {
peer_subject = format_subject_name(cert.get());
peer_issuer_subject = format_issuer_subject_name(cert.get());
}
}
enum class SslDecryptResult {
SUCCESS,
/**
* More encrypted_input data is required.
*/
MORE,
CLOSE_NOTIFY_ALERT,
};
static SslDecryptResult
ssl_decrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer)
{
/* SSL_read() must be called repeatedly until there is no more
data (or until the buffer is full) */
while (true) {
auto w = buffer.Write();
if (w.empty())
return SslDecryptResult::SUCCESS;
int result = SSL_read(ssl, w.data(), w.size());
if (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ)
return SslDecryptResult::MORE;
if (result <= 0) {
if (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN)
/* got a "close notify" alert from the peer */
return SslDecryptResult::CLOSE_NOTIFY_ALERT;
CheckThrowSslError(ssl, result);
return SslDecryptResult::SUCCESS;
}
buffer.Append(result);
}
}
static void
ssl_encrypt(SSL *ssl, ForeignFifoBuffer<std::byte> &buffer)
{
/* SSL_write() must be called repeatedly until there is no more
data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes
only the current incomplete record, and additional data which
has been submitted more recently will only be considered in the
next SSL_write() call */
while (true) {
auto r = buffer.Read();
if (r.empty())
return;
int result = SSL_write(ssl, r.data(), r.size());
if (result <= 0) {
CheckThrowSslError(ssl, result);
return;
}
buffer.Consume(result);
}
}
inline void
SslFilter::Encrypt()
{
ssl_encrypt(ssl.get(), plain_output);
}
/*
* thread_socket_filter_handler
*
*/
void
SslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept
{
if (f.IsIdle()) {
decrypted_input.AllocateIfNull(fb_pool_get());
encrypted_output.AllocateIfNull(fb_pool_get());
}
}
void
SslFilter::Run(ThreadSocketFilterInternal &f)
{
/* copy input (and output to make room for more output) */
{
std::unique_lock<std::mutex> lock(f.mutex);
if (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) {
/* retry, let PreRun() allocate the missing buffer */
f.again = true;
return;
}
f.decrypted_input.MoveFromAllowNull(decrypted_input);
plain_output.MoveFromAllowNull(f.plain_output);
encrypted_input.MoveFromAllowSrcNull(f.encrypted_input);
f.encrypted_output.MoveFromAllowNull(encrypted_output);
if (decrypted_input.IsNull() || encrypted_output.IsNull()) {
/* retry, let PreRun() allocate the missing buffer */
f.again = true;
return;
}
}
/* let OpenSSL work */
ERR_clear_error();
if (handshaking) [[unlikely]] {
int result = SSL_do_handshake(ssl.get());
if (result == 1) {
handshaking = false;
PostHandshake();
} else {
try {
CheckThrowSslError(ssl.get(), result);
/* flush the encrypted_output buffer, because it may
contain a "TLS alert" */
} catch (...) {
const std::lock_guard<std::mutex> lock(f.mutex);
f.encrypted_output.MoveFromAllowNull(encrypted_output);
throw;
}
}
}
if (!handshaking) [[likely]] {
Encrypt();
switch (ssl_decrypt(ssl.get(), decrypted_input)) {
case SslDecryptResult::SUCCESS:
break;
case SslDecryptResult::MORE:
if (encrypted_input.IsDefinedAndFull())
throw std::runtime_error("SSL encrypted_input buffer is full");
break;
case SslDecryptResult::CLOSE_NOTIFY_ALERT:
{
std::unique_lock<std::mutex> lock(f.mutex);
f.input_eof = true;
}
break;
}
}
/* copy output */
{
std::unique_lock<std::mutex> lock(f.mutex);
f.decrypted_input.MoveFromAllowNull(decrypted_input);
f.encrypted_output.MoveFromAllowNull(encrypted_output);
f.drained = plain_output.empty() && encrypted_output.empty();
if (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty())
/* there's more data to be decrypted and we
still have room in the destination buffer,
so let's run again */
f.again = true;
if (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() &&
!encrypted_output.IsDefinedAndFull())
/* there's more data, and we're ready to handle it: try
again */
f.again = true;
f.handshaking = handshaking;
}
}
void
SslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept
{
if (f.IsIdle()) {
plain_output.FreeIfEmpty();
encrypted_input.FreeIfEmpty();
decrypted_input.FreeIfEmpty();
encrypted_output.FreeIfEmpty();
}
}
void
SslFilter::CancelRun(ThreadSocketFilterInternal &) noexcept
{
if (cancel_ptr)
/* cancel the CertCache::Apply() call */
cancel_ptr.Cancel();
}
/*
* constructor
*
*/
std::unique_ptr<ThreadSocketFilterHandler>
ssl_filter_new(UniqueSSL &&ssl) noexcept
{
return std::make_unique<SslFilter>(std::move(ssl));
}
SslFilter &
ssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept
{
return static_cast<SslFilter &>(tsfh);
}
const SslFilter *
ssl_filter_cast_from(const SocketFilter *socket_filter) noexcept
{
const auto *tsf = dynamic_cast<const ThreadSocketFilter *>(socket_filter);
if (tsf == nullptr)
return nullptr;
return dynamic_cast<const SslFilter *>(&tsf->GetHandler());
}
std::span<const unsigned char>
ssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept
{
return ssl.GetAlpnSelected();
}
const char *
ssl_filter_get_peer_subject(const SslFilter &ssl) noexcept
{
return ssl.peer_subject.c_str();
}
const char *
ssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept
{
return ssl.peer_issuer_subject.c_str();
}
<|endoftext|> |
<commit_before>/*
* statusspec.cpp
* StatusSpec project
*
* Copyright (c) 2014 thesupremecommander
* BSD 2-Clause License
* http://opensource.org/licenses/BSD-2-Clause
*
*/
#include "statusspec.h"
AntiFreeze *g_AntiFreeze = nullptr;
CameraTools *g_CameraTools = nullptr;
CustomTextures *g_CustomTextures = nullptr;
FOVOverride *g_FOVOverride = nullptr;
Killstreaks *g_Killstreaks = nullptr;
LoadoutIcons *g_LoadoutIcons = nullptr;
LocalPlayer *g_LocalPlayer = nullptr;
MedigunInfo *g_MedigunInfo = nullptr;
MultiPanel *g_MultiPanel = nullptr;
PlayerAliases *g_PlayerAliases = nullptr;
PlayerModels *g_PlayerModels = nullptr;
PlayerOutlines *g_PlayerOutlines = nullptr;
ProjectileOutlines *g_ProjectileOutlines = nullptr;
SpecGUIOrder *g_SpecGUIOrder = nullptr;
StatusIcons *g_StatusIcons = nullptr;
TeamOverrides *g_TeamOverrides = nullptr;
static int doPostScreenSpaceEffectsHook;
void Hook_IBaseClientDLL_FrameStageNotify(ClientFrameStage_t curStage) {
if (!doPostScreenSpaceEffectsHook && Interfaces::GetClientMode()) {
doPostScreenSpaceEffectsHook = Funcs::AddHook_IClientMode_DoPostScreenSpaceEffects(Interfaces::GetClientMode(), SH_STATIC(Hook_IClientMode_DoPostScreenSpaceEffects), false);
}
if (curStage == FRAME_RENDER_START) {
int maxEntity = Interfaces::pClientEntityList->GetHighestEntityIndex();
for (int i = 0; i < maxEntity; i++) {
IClientEntity *entity = Interfaces::pClientEntityList->GetClientEntity(i);
if (!entity) {
continue;
}
}
}
RETURN_META(MRES_IGNORED);
}
bool Hook_IClientMode_DoPostScreenSpaceEffects(const CViewSetup *pSetup) {
g_GlowObjectManager.RenderGlowEffects(pSetup);
RETURN_META_VALUE(MRES_OVERRIDE, true);
}
void Hook_IPanel_PaintTraverse_Post(vgui::VPANEL vguiPanel, bool forceRepaint, bool allowForce = true) {
if (g_StatusIcons) {
if (g_StatusIcons->IsEnabled()) {
g_StatusIcons->Paint(vguiPanel);
}
else {
g_StatusIcons->NoPaint(vguiPanel);
}
}
RETURN_META(MRES_IGNORED);
}
void Hook_IPanel_SendMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) {
if (g_StatusIcons) {
if (g_StatusIcons->IsEnabled()) {
g_StatusIcons->InterceptMessage(vguiPanel, params, ifromPanel);
}
}
RETURN_META(MRES_IGNORED);
}
// The plugin is a static singleton that is exported as an interface
StatusSpecPlugin g_StatusSpecPlugin;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(StatusSpecPlugin, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_StatusSpecPlugin);
StatusSpecPlugin::StatusSpecPlugin()
{
}
StatusSpecPlugin::~StatusSpecPlugin()
{
}
bool StatusSpecPlugin::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory)
{
if (!Interfaces::Load(interfaceFactory, gameServerFactory)) {
Warning("[%s] Unable to load required libraries!\n", PLUGIN_DESC);
return false;
}
if (!Entities::PrepareOffsets()) {
Warning("[%s] Unable to determine proper offsets!\n", PLUGIN_DESC);
return false;
}
if (!Funcs::Load()) {
Warning("[%s] Unable to initialize hooking!", PLUGIN_DESC);
return false;
}
Funcs::AddHook_IBaseClientDLL_FrameStageNotify(Interfaces::pClientDLL, SH_STATIC(Hook_IBaseClientDLL_FrameStageNotify), false);
Funcs::AddHook_IPanel_PaintTraverse(g_pVGuiPanel, SH_STATIC(Hook_IPanel_PaintTraverse_Post), true);
Funcs::AddHook_IPanel_SendMessage(g_pVGuiPanel, SH_STATIC(Hook_IPanel_SendMessage), false);
ConVar_Register();
g_AntiFreeze = new AntiFreeze();
g_CameraTools = new CameraTools();
g_CustomTextures = new CustomTextures();
g_FOVOverride = new FOVOverride();
g_Killstreaks = new Killstreaks();
g_LoadoutIcons = new LoadoutIcons();
g_LocalPlayer = new LocalPlayer();
g_MedigunInfo = new MedigunInfo();
g_MultiPanel = new MultiPanel();
g_PlayerAliases = new PlayerAliases();
g_PlayerModels = new PlayerModels();
g_PlayerOutlines = new PlayerOutlines();
g_ProjectileOutlines = new ProjectileOutlines();
g_SpecGUIOrder = new SpecGUIOrder();
g_StatusIcons = new StatusIcons();
g_TeamOverrides = new TeamOverrides();
Msg("%s loaded!\n", PLUGIN_DESC);
return true;
}
void StatusSpecPlugin::Unload(void)
{
delete g_AntiFreeze;
delete g_CameraTools;
delete g_CustomTextures;
delete g_FOVOverride;
delete g_Killstreaks;
delete g_LoadoutIcons;
delete g_LocalPlayer;
delete g_MedigunInfo;
delete g_MultiPanel;
delete g_PlayerAliases;
delete g_PlayerModels;
delete g_PlayerOutlines;
delete g_ProjectileOutlines;
delete g_SpecGUIOrder;
delete g_StatusIcons;
delete g_TeamOverrides;
Funcs::Unload();
ConVar_Unregister();
Interfaces::Unload();
}
void StatusSpecPlugin::Pause(void) {
Funcs::Pause();
}
void StatusSpecPlugin::UnPause(void) {
Funcs::Unpause();
}
const char *StatusSpecPlugin::GetPluginDescription(void) {
return PLUGIN_DESC;
}
void StatusSpecPlugin::LevelInit(char const *pMapName) {}
void StatusSpecPlugin::ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) {}
void StatusSpecPlugin::GameFrame(bool simulating) {}
void StatusSpecPlugin::LevelShutdown(void) {}
void StatusSpecPlugin::ClientActive(edict_t *pEntity) {}
void StatusSpecPlugin::ClientDisconnect(edict_t *pEntity) {}
void StatusSpecPlugin::ClientPutInServer(edict_t *pEntity, char const *playername) {}
void StatusSpecPlugin::SetCommandClient(int index) {}
void StatusSpecPlugin::ClientSettingsChanged(edict_t *pEdict) {}
PLUGIN_RESULT StatusSpecPlugin::ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) { return PLUGIN_CONTINUE; }
PLUGIN_RESULT StatusSpecPlugin::ClientCommand(edict_t *pEntity, const CCommand &args) { return PLUGIN_CONTINUE; }
PLUGIN_RESULT StatusSpecPlugin::NetworkIDValidated(const char *pszUserName, const char *pszNetworkID) { return PLUGIN_CONTINUE; }
void StatusSpecPlugin::OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue) {}
void StatusSpecPlugin::OnEdictAllocated(edict_t *edict) {}
void StatusSpecPlugin::OnEdictFreed(const edict_t *edict) {}<commit_msg>Revamp global frame hook to just initialize DPSSE hook.<commit_after>/*
* statusspec.cpp
* StatusSpec project
*
* Copyright (c) 2014 thesupremecommander
* BSD 2-Clause License
* http://opensource.org/licenses/BSD-2-Clause
*
*/
#include "statusspec.h"
AntiFreeze *g_AntiFreeze = nullptr;
CameraTools *g_CameraTools = nullptr;
CustomTextures *g_CustomTextures = nullptr;
FOVOverride *g_FOVOverride = nullptr;
Killstreaks *g_Killstreaks = nullptr;
LoadoutIcons *g_LoadoutIcons = nullptr;
LocalPlayer *g_LocalPlayer = nullptr;
MedigunInfo *g_MedigunInfo = nullptr;
MultiPanel *g_MultiPanel = nullptr;
PlayerAliases *g_PlayerAliases = nullptr;
PlayerModels *g_PlayerModels = nullptr;
PlayerOutlines *g_PlayerOutlines = nullptr;
ProjectileOutlines *g_ProjectileOutlines = nullptr;
SpecGUIOrder *g_SpecGUIOrder = nullptr;
StatusIcons *g_StatusIcons = nullptr;
TeamOverrides *g_TeamOverrides = nullptr;
static int doPostScreenSpaceEffectsHook = 0;
static int frameHook = 0;
void Hook_IBaseClientDLL_FrameStageNotify(ClientFrameStage_t curStage) {
if (!doPostScreenSpaceEffectsHook) {
try {
doPostScreenSpaceEffectsHook = Funcs::AddHook_IClientMode_DoPostScreenSpaceEffects(Interfaces::GetClientMode(), SH_STATIC(Hook_IClientMode_DoPostScreenSpaceEffects), false);
}
catch (bad_pointer &e) {
Warning(e.what());
}
}
if (doPostScreenSpaceEffectsHook) {
if (Funcs::RemoveHook(frameHook)) {
frameHook = 0;
}
}
RETURN_META(MRES_IGNORED);
}
bool Hook_IClientMode_DoPostScreenSpaceEffects(const CViewSetup *pSetup) {
g_GlowObjectManager.RenderGlowEffects(pSetup);
RETURN_META_VALUE(MRES_OVERRIDE, true);
}
void Hook_IPanel_PaintTraverse_Post(vgui::VPANEL vguiPanel, bool forceRepaint, bool allowForce = true) {
if (g_StatusIcons) {
if (g_StatusIcons->IsEnabled()) {
g_StatusIcons->Paint(vguiPanel);
}
else {
g_StatusIcons->NoPaint(vguiPanel);
}
}
RETURN_META(MRES_IGNORED);
}
void Hook_IPanel_SendMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) {
if (g_StatusIcons) {
if (g_StatusIcons->IsEnabled()) {
g_StatusIcons->InterceptMessage(vguiPanel, params, ifromPanel);
}
}
RETURN_META(MRES_IGNORED);
}
// The plugin is a static singleton that is exported as an interface
StatusSpecPlugin g_StatusSpecPlugin;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(StatusSpecPlugin, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_StatusSpecPlugin);
StatusSpecPlugin::StatusSpecPlugin()
{
}
StatusSpecPlugin::~StatusSpecPlugin()
{
}
bool StatusSpecPlugin::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory)
{
if (!Interfaces::Load(interfaceFactory, gameServerFactory)) {
Warning("[%s] Unable to load required libraries!\n", PLUGIN_DESC);
return false;
}
if (!Entities::PrepareOffsets()) {
Warning("[%s] Unable to determine proper offsets!\n", PLUGIN_DESC);
return false;
}
if (!Funcs::Load()) {
Warning("[%s] Unable to initialize hooking!", PLUGIN_DESC);
return false;
}
if (!doPostScreenSpaceEffectsHook) {
try {
doPostScreenSpaceEffectsHook = Funcs::AddHook_IClientMode_DoPostScreenSpaceEffects(Interfaces::GetClientMode(), SH_STATIC(Hook_IClientMode_DoPostScreenSpaceEffects), false);
}
catch (bad_pointer &e) {
Warning(e.what());
}
if (!doPostScreenSpaceEffectsHook && !frameHook) {
frameHook = Funcs::AddHook_IBaseClientDLL_FrameStageNotify(Interfaces::pClientDLL, SH_STATIC(Hook_IBaseClientDLL_FrameStageNotify), true);
}
}
Funcs::AddHook_IPanel_PaintTraverse(g_pVGuiPanel, SH_STATIC(Hook_IPanel_PaintTraverse_Post), true);
Funcs::AddHook_IPanel_SendMessage(g_pVGuiPanel, SH_STATIC(Hook_IPanel_SendMessage), false);
ConVar_Register();
g_AntiFreeze = new AntiFreeze();
g_CameraTools = new CameraTools();
g_CustomTextures = new CustomTextures();
g_FOVOverride = new FOVOverride();
g_Killstreaks = new Killstreaks();
g_LoadoutIcons = new LoadoutIcons();
g_LocalPlayer = new LocalPlayer();
g_MedigunInfo = new MedigunInfo();
g_MultiPanel = new MultiPanel();
g_PlayerAliases = new PlayerAliases();
g_PlayerModels = new PlayerModels();
g_PlayerOutlines = new PlayerOutlines();
g_ProjectileOutlines = new ProjectileOutlines();
g_SpecGUIOrder = new SpecGUIOrder();
g_StatusIcons = new StatusIcons();
g_TeamOverrides = new TeamOverrides();
Msg("%s loaded!\n", PLUGIN_DESC);
return true;
}
void StatusSpecPlugin::Unload(void)
{
delete g_AntiFreeze;
delete g_CameraTools;
delete g_CustomTextures;
delete g_FOVOverride;
delete g_Killstreaks;
delete g_LoadoutIcons;
delete g_LocalPlayer;
delete g_MedigunInfo;
delete g_MultiPanel;
delete g_PlayerAliases;
delete g_PlayerModels;
delete g_PlayerOutlines;
delete g_ProjectileOutlines;
delete g_SpecGUIOrder;
delete g_StatusIcons;
delete g_TeamOverrides;
Funcs::Unload();
ConVar_Unregister();
Interfaces::Unload();
}
void StatusSpecPlugin::Pause(void) {
Funcs::Pause();
}
void StatusSpecPlugin::UnPause(void) {
Funcs::Unpause();
}
const char *StatusSpecPlugin::GetPluginDescription(void) {
return PLUGIN_DESC;
}
void StatusSpecPlugin::LevelInit(char const *pMapName) {}
void StatusSpecPlugin::ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) {}
void StatusSpecPlugin::GameFrame(bool simulating) {}
void StatusSpecPlugin::LevelShutdown(void) {}
void StatusSpecPlugin::ClientActive(edict_t *pEntity) {}
void StatusSpecPlugin::ClientDisconnect(edict_t *pEntity) {}
void StatusSpecPlugin::ClientPutInServer(edict_t *pEntity, char const *playername) {}
void StatusSpecPlugin::SetCommandClient(int index) {}
void StatusSpecPlugin::ClientSettingsChanged(edict_t *pEdict) {}
PLUGIN_RESULT StatusSpecPlugin::ClientConnect(bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen) { return PLUGIN_CONTINUE; }
PLUGIN_RESULT StatusSpecPlugin::ClientCommand(edict_t *pEntity, const CCommand &args) { return PLUGIN_CONTINUE; }
PLUGIN_RESULT StatusSpecPlugin::NetworkIDValidated(const char *pszUserName, const char *pszNetworkID) { return PLUGIN_CONTINUE; }
void StatusSpecPlugin::OnQueryCvarValueFinished(QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue) {}
void StatusSpecPlugin::OnEdictAllocated(edict_t *edict) {}
void StatusSpecPlugin::OnEdictFreed(const edict_t *edict) {}<|endoftext|> |
<commit_before>/*
Copyright 2016 Fixstars Corporation
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <iostream>
#include <libsgm.h>
#include "internal.h"
#include "sgm.hpp"
namespace sgm {
static bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; }
static bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; }
class SemiGlobalMatchingBase {
public:
using output_type = uint8_t;
virtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
size_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) = 0;
virtual ~SemiGlobalMatchingBase() {}
};
class SemiGlobalMatching_8_64 : public SemiGlobalMatchingBase {
public:
void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
size_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override
{
sgm_engine_.execute(dst_L, dst_R, (const uint8_t*)src_L, (const uint8_t*)src_R, w, h, P1, P2, uniqueness);
}
private:
SemiGlobalMatching<uint8_t, 64> sgm_engine_;
};
class SemiGlobalMatching_8_128 : public SemiGlobalMatchingBase {
public:
void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
size_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override
{
sgm_engine_.execute(dst_L, dst_R, (const uint8_t*)src_L, (const uint8_t*)src_R, w, h, P1, P2, uniqueness);
}
private:
SemiGlobalMatching<uint8_t, 128> sgm_engine_;
};
class SemiGlobalMatching_16_64 : public SemiGlobalMatchingBase {
public:
void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
size_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override
{
sgm_engine_.execute(dst_L, dst_R, (const uint16_t*)src_L, (const uint16_t*)src_R, w, h, P1, P2, uniqueness);
}
private:
SemiGlobalMatching<uint16_t, 64> sgm_engine_;
};
class SemiGlobalMatching_16_128 : public SemiGlobalMatchingBase {
public:
void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
size_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override
{
sgm_engine_.execute(dst_L, dst_R, (const uint16_t*)src_L, (const uint16_t*)src_R, w, h, P1, P2, uniqueness);
}
private:
SemiGlobalMatching<uint16_t, 128> sgm_engine_;
};
struct CudaStereoSGMResources {
void* d_src_left;
void* d_src_right;
void* d_left_disp;
void* d_right_disp;
void* d_tmp_left_disp;
void* d_tmp_right_disp;
SemiGlobalMatchingBase* sgm_engine;
CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) {
if (input_depth_bits_ == 8 && disparity_size_ == 64)
sgm_engine = new SemiGlobalMatching_8_64();
else if (input_depth_bits_ == 8 && disparity_size_ == 128)
sgm_engine = new SemiGlobalMatching_8_128();
else if (input_depth_bits_ == 16 && disparity_size_ == 64)
sgm_engine = new SemiGlobalMatching_16_64();
else if (input_depth_bits_ == 16 && disparity_size_ == 128)
sgm_engine = new SemiGlobalMatching_16_128();
else
throw std::logic_error("depth bits must be 8 or 16, and disparity size must be 64 or 128");
if (is_cuda_input(inout_type_)) {
this->d_src_left = NULL;
this->d_src_right = NULL;
}
else {
CudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ / 8 * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ / 8 * width_ * height_));
}
CudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_left_disp, 0, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_right_disp, 0, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_));
}
~CudaStereoSGMResources() {
CudaSafeCall(cudaFree(this->d_src_left));
CudaSafeCall(cudaFree(this->d_src_right));
CudaSafeCall(cudaFree(this->d_left_disp));
CudaSafeCall(cudaFree(this->d_right_disp));
CudaSafeCall(cudaFree(this->d_tmp_left_disp));
CudaSafeCall(cudaFree(this->d_tmp_right_disp));
delete sgm_engine;
}
};
StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits,
EXECUTE_INOUT inout_type, const Parameters& param) :
cu_res_(NULL),
width_(width),
height_(height),
disparity_size_(disparity_size),
input_depth_bits_(input_depth_bits),
output_depth_bits_(output_depth_bits),
inout_type_(inout_type),
param_(param)
{
// check values
if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {
width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
throw std::logic_error("depth bits must be 8 or 16");
}
if (disparity_size_ != 64 && disparity_size_ != 128) {
width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
throw std::logic_error("disparity size must be 64 or 128");
}
cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_);
}
StereoSGM::~StereoSGM() {
if (cu_res_) { delete cu_res_; }
}
void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void* dst) {
const void *d_input_left, *d_input_right;
if (is_cuda_input(inout_type_)) {
d_input_left = left_pixels;
d_input_right = right_pixels;
}
else {
CudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice));
CudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice));
d_input_left = cu_res_->d_src_left;
d_input_right = cu_res_->d_src_right;
}
void* d_tmp_left_disp = cu_res_->d_tmp_left_disp;
void* d_tmp_right_disp = cu_res_->d_tmp_right_disp;
void* d_left_disp = cu_res_->d_left_disp;
void* d_right_disp = cu_res_->d_right_disp;
if (is_cuda_output(inout_type_) && output_depth_bits_ == 8)
d_left_disp = dst; // when threre is no device-host copy or type conversion, use passed buffer
cu_res_->sgm_engine->execute((uint8_t*)d_tmp_left_disp, (uint8_t*)d_tmp_right_disp,
d_input_left, d_input_right, width_, height_, param_.P1, param_.P2, param_.uniqueness);
sgm::details::median_filter((uint8_t*)d_tmp_left_disp, (uint8_t*)d_left_disp, width_, height_);
sgm::details::median_filter((uint8_t*)d_tmp_right_disp, (uint8_t*)d_right_disp, width_, height_);
sgm::details::check_consistency((uint8_t*)d_left_disp, (uint8_t*)d_right_disp, d_input_left, width_, height_, input_depth_bits_);
if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
sgm::details::cast_8bit_16bit_array((const uint8_t*)d_left_disp, (uint16_t*)d_tmp_left_disp, width_ * height_);
CudaSafeCall(cudaMemcpy(dst, d_tmp_left_disp, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost));
}
else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
sgm::details::cast_8bit_16bit_array((const uint8_t*)d_left_disp, (uint16_t*)dst, width_ * height_);
}
else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
CudaSafeCall(cudaMemcpy(dst, d_left_disp, sizeof(uint8_t) * width_ * height_, cudaMemcpyDeviceToHost));
}
else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
// optimize! no-copy!
}
else {
std::cerr << "not impl" << std::endl;
}
}
}
<commit_msg>Refactoring sgm engine<commit_after>/*
Copyright 2016 Fixstars Corporation
Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <iostream>
#include <libsgm.h>
#include "internal.h"
#include "sgm.hpp"
namespace sgm {
static bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; }
static bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; }
class SemiGlobalMatchingBase {
public:
using output_type = uint8_t;
virtual void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
size_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) = 0;
virtual ~SemiGlobalMatchingBase() {}
};
template <typename input_type, int DISP_SIZE>
class SemiGlobalMatchingImpl : public SemiGlobalMatchingBase {
public:
void execute(output_type* dst_L, output_type* dst_R, const void* src_L, const void* src_R,
size_t w, size_t h, unsigned int P1, unsigned int P2, float uniqueness) override
{
sgm_engine_.execute(dst_L, dst_R, (const input_type*)src_L, (const input_type*)src_R, w, h, P1, P2, uniqueness);
}
private:
SemiGlobalMatching<input_type, DISP_SIZE> sgm_engine_;
};
struct CudaStereoSGMResources {
void* d_src_left;
void* d_src_right;
void* d_left_disp;
void* d_right_disp;
void* d_tmp_left_disp;
void* d_tmp_right_disp;
SemiGlobalMatchingBase* sgm_engine;
CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) {
if (input_depth_bits_ == 8 && disparity_size_ == 64)
sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 64>();
else if (input_depth_bits_ == 8 && disparity_size_ == 128)
sgm_engine = new SemiGlobalMatchingImpl<uint8_t, 128>();
else if (input_depth_bits_ == 16 && disparity_size_ == 64)
sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 64>();
else if (input_depth_bits_ == 16 && disparity_size_ == 128)
sgm_engine = new SemiGlobalMatchingImpl<uint16_t, 128>();
else
throw std::logic_error("depth bits must be 8 or 16, and disparity size must be 64 or 128");
if (is_cuda_input(inout_type_)) {
this->d_src_left = NULL;
this->d_src_right = NULL;
}
else {
CudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ / 8 * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ / 8 * width_ * height_));
}
CudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_left_disp, 0, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_right_disp, 0, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_));
CudaSafeCall(cudaMemset(this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_));
}
~CudaStereoSGMResources() {
CudaSafeCall(cudaFree(this->d_src_left));
CudaSafeCall(cudaFree(this->d_src_right));
CudaSafeCall(cudaFree(this->d_left_disp));
CudaSafeCall(cudaFree(this->d_right_disp));
CudaSafeCall(cudaFree(this->d_tmp_left_disp));
CudaSafeCall(cudaFree(this->d_tmp_right_disp));
delete sgm_engine;
}
};
StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits,
EXECUTE_INOUT inout_type, const Parameters& param) :
cu_res_(NULL),
width_(width),
height_(height),
disparity_size_(disparity_size),
input_depth_bits_(input_depth_bits),
output_depth_bits_(output_depth_bits),
inout_type_(inout_type),
param_(param)
{
// check values
if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {
width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
throw std::logic_error("depth bits must be 8 or 16");
}
if (disparity_size_ != 64 && disparity_size_ != 128) {
width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;
throw std::logic_error("disparity size must be 64 or 128");
}
cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_);
}
StereoSGM::~StereoSGM() {
if (cu_res_) { delete cu_res_; }
}
void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void* dst) {
const void *d_input_left, *d_input_right;
if (is_cuda_input(inout_type_)) {
d_input_left = left_pixels;
d_input_right = right_pixels;
}
else {
CudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice));
CudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice));
d_input_left = cu_res_->d_src_left;
d_input_right = cu_res_->d_src_right;
}
void* d_tmp_left_disp = cu_res_->d_tmp_left_disp;
void* d_tmp_right_disp = cu_res_->d_tmp_right_disp;
void* d_left_disp = cu_res_->d_left_disp;
void* d_right_disp = cu_res_->d_right_disp;
if (is_cuda_output(inout_type_) && output_depth_bits_ == 8)
d_left_disp = dst; // when threre is no device-host copy or type conversion, use passed buffer
cu_res_->sgm_engine->execute((uint8_t*)d_tmp_left_disp, (uint8_t*)d_tmp_right_disp,
d_input_left, d_input_right, width_, height_, param_.P1, param_.P2, param_.uniqueness);
sgm::details::median_filter((uint8_t*)d_tmp_left_disp, (uint8_t*)d_left_disp, width_, height_);
sgm::details::median_filter((uint8_t*)d_tmp_right_disp, (uint8_t*)d_right_disp, width_, height_);
sgm::details::check_consistency((uint8_t*)d_left_disp, (uint8_t*)d_right_disp, d_input_left, width_, height_, input_depth_bits_);
if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
sgm::details::cast_8bit_16bit_array((const uint8_t*)d_left_disp, (uint16_t*)d_tmp_left_disp, width_ * height_);
CudaSafeCall(cudaMemcpy(dst, d_tmp_left_disp, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost));
}
else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {
sgm::details::cast_8bit_16bit_array((const uint8_t*)d_left_disp, (uint16_t*)dst, width_ * height_);
}
else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
CudaSafeCall(cudaMemcpy(dst, d_left_disp, sizeof(uint8_t) * width_ * height_, cudaMemcpyDeviceToHost));
}
else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {
// optimize! no-copy!
}
else {
std::cerr << "not impl" << std::endl;
}
}
}
<|endoftext|> |
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/color.hpp"
#include"ork/glm.hpp"
#include"ork/test/catch_include.hpp"
#include"glm/vec4.hpp"
using namespace ork;
bool within_hex(const float v1, const float v2) {
return std::abs(v1 - v2) < 0.5 / 255.0;
}
TEST_CASE("Convention for hue", "[color]") {
const color4 d1{0.f, 0.f, 0.f, 1.f};
const color4 r1{0.f, 0.f, 0.f, 1.f};
REQUIRE(truncate_hue(d1, color_space::rgb) == r1);
}
TEST_CASE("RGB round trip to HEX", "[color]") {
const color4 d1{0.1, 0.2, 0.3, 0.4};
const string r1{ORK("1A334D66")};
const string to{to_hex(d1, color_space::rgb)};
const color4 from{from_hex(to, color_space::rgb)};
REQUIRE(to == r1);
LOOPVIG(d1) {
REQUIRE(within_hex(from[i], d1[i]));
}
}
}
<commit_msg>Added data for rgb conversion<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/color.hpp"
#include"ork/glm.hpp"
#include"ork/test/catch_include.hpp"
#include"glm/vec4.hpp"
using namespace ork;
bool within_hex(const float v1, const float v2) {
return std::abs(v1 - v2) < 0.5 / 255.0;
}
TEST_CASE("Convention for hue", "[color]") {
const color4 d1{0.f, 0.f, 0.f, 1.f};
const color4 r1{0.f, 0.f, 0.f, 1.f};
REQUIRE(truncate_hue(d1, color_space::rgb) == r1);
}
TEST_CASE("RGB Conversion", "[color]") {
const color4 rgb{0.2f, 0.3f, 0.4f, 0.5f};
const color4 r1{0.5850f, 0.3333f, 0.3000f, 0.5f};//HSL
const color4 r2{0.5850f, 0.5000f, 0.4000f, 0.5f};//HSV
const color4 c1{convert(rgb, color_space::rgb, color_space::hsl)};
const color4 c2{convert(rgb, color_space::rgb, color_space::hsv)};
}
TEST_CASE("RGB round trip to HEX", "[color]") {
const color4 d1{0.1, 0.2, 0.3, 0.4};
const string r1{ORK("1A334D66")};
const string to{to_hex(d1, color_space::rgb)};
const color4 from{from_hex(to, color_space::rgb)};
REQUIRE(to == r1);
LOOPVIG(d1) {
REQUIRE(within_hex(from[i], d1[i]));
}
}
}
<|endoftext|> |
<commit_before>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method
) {
// range errors: test all combinations of
// "wrong" (outside of correct range) arguments
// Max_index: 0; min_index: 0
for (int arg1 = -1; arg1 <= 1; arg1++) {
for (int arg2 = -1; arg2 <= 1; arg2++) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
}
}
// "dead" error
// (attempt to do something with dead bacterium)
model->kill(0, 0);
BOOST_REQUIRE_THROW(
((*model).*model_method)(0, 0), Exception
);
}
#define CREATE_NEW \
model->createNewByCoordinates( \
coordinates, \
DEFAULT_MASS, \
0, \
0, \
0 \
);
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
CREATE_NEW
return coordinates;
}
static void createByCoordinates(
Implementation::Model* model,
Abstract::Point coordinates
) {
CREATE_NEW
}
#undef CREATE_NEW
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(model, &Implementation::Model::getMass);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
// error handling checks
createInBaseCoordinates(model);
// FIXME test doesn't work correctly without this function call.
// The solution is to use set instead of vector in model.
model->clearBeforeMove(0);
checkErrorHandling(model, &Implementation::Model::kill);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
delete model;
}
<commit_msg>Model tests: add typedef TwoArgsMethod<commit_after>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*TwoArgsMethod) (
const Abstract::Point& coordinates,
int change
);
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method
) {
// range errors: test all combinations of
// "wrong" (outside of correct range) arguments
// Max_index: 0; min_index: 0
for (int arg1 = -1; arg1 <= 1; arg1++) {
for (int arg2 = -1; arg2 <= 1; arg2++) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
}
}
// "dead" error
// (attempt to do something with dead bacterium)
model->kill(0, 0);
BOOST_REQUIRE_THROW(
((*model).*model_method)(0, 0), Exception
);
}
#define CREATE_NEW \
model->createNewByCoordinates( \
coordinates, \
DEFAULT_MASS, \
0, \
0, \
0 \
);
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
CREATE_NEW
return coordinates;
}
static void createByCoordinates(
Implementation::Model* model,
Abstract::Point coordinates
) {
CREATE_NEW
}
#undef CREATE_NEW
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(model, &Implementation::Model::getMass);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
// error handling checks
createInBaseCoordinates(model);
// FIXME test doesn't work correctly without this function call.
// The solution is to use set instead of vector in model.
model->clearBeforeMove(0);
checkErrorHandling(model, &Implementation::Model::kill);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
delete model;
}
<|endoftext|> |
<commit_before>// (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2003.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// See http://www.boost.org for updates, documentation, and revision history.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : supplies offline implemtation for the Test Tools
// ***************************************************************************
// Boost.Test
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_result.hpp>
// BOOST
#include <boost/config.hpp>
// STL
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
# ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::strcmp; using ::strncmp; using ::strlen; }
# endif
namespace boost {
namespace test_toolbox {
namespace detail {
// ************************************************************************** //
// ************** TOOL BOX Implementation ************** //
// ************************************************************************** //
void
checkpoint_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_test_suites )
unit_test_framework::checkpoint( message.str() )
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
message_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_messages )
message.str()
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
warn_and_continue_impl( bool predicate, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num, bool add_fail_pass )
{
if( !predicate ) {
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_warnings )
(add_fail_pass ? "condition " : "") << message.str() << (add_fail_pass ? " is not satisfied" : "" )
BOOST_UT_LOG_END
}
else {
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )
"condition " << message.str() << " is satisfied"
BOOST_UT_LOG_END
}
}
//____________________________________________________________________________//
void
warn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num,
bool add_fail_pass )
{
warn_and_continue_impl( !!v,
message << (add_fail_pass && !v ? " is not satisfied. " : "" ) << *(v.p_message),
file_name, line_num, false );
}
//____________________________________________________________________________//
bool
test_and_continue_impl( bool predicate, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
if( !predicate ) {
unit_test_framework::unit_test_result::instance().inc_failed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " failed" : "")
BOOST_UT_LOG_END
return true;
}
else {
unit_test_framework::unit_test_result::instance().inc_passed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " passed" : "")
BOOST_UT_LOG_END
return false;
}
}
//____________________________________________________________________________//
bool
test_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
return test_and_continue_impl( !!v,
message << (add_fail_pass ? (!v ? " failed. " : " passed. ") : "") << *(v.p_message),
file_name, line_num, false, loglevel );
}
//____________________________________________________________________________//
void
test_and_throw_impl( bool predicate, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed(); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
void
test_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed(); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
bool
equal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
unit_test_framework::log_level loglevel )
{
bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right);
left = left ? left : "null string";
right = right ? right : "null string";
if( !predicate ) {
return test_and_continue_impl( false,
wrap_stringstream().ref() << "test " << message.str() << " failed [" << left << " != " << right << "]",
file_name, line_num, false, loglevel );
}
return test_and_continue_impl( true, message, file_name, line_num, true, loglevel );
}
//____________________________________________________________________________//
bool
is_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value )
{
// return std::strncmp( symbol_name, symbol_value, std::strlen( symbol_name ) ) != 0;
return std::strcmp( symbol_name, symbol_value + 2 ) != 0;
}
//____________________________________________________________________________//
} // namespace detail
// ************************************************************************** //
// ************** output_test_stream ************** //
// ************************************************************************** //
struct output_test_stream::Impl
{
std::fstream m_pattern_to_match_or_save;
bool m_match_or_save;
std::string m_synced_string;
char get_char()
{
char res;
do {
m_pattern_to_match_or_save.get( res );
} while( res == '\r' &&
!m_pattern_to_match_or_save.fail() &&
!m_pattern_to_match_or_save.eof() );
return res;
}
void check_and_fill( extended_predicate_value& res )
{
if( !res.p_predicate_value.get() )
*(res.p_message) << "Output content: \"" << m_synced_string << '\"';
}
};
//____________________________________________________________________________//
output_test_stream::output_test_stream( std::string const& pattern_file_name, bool match_or_save )
: m_pimpl( new Impl )
{
if( !pattern_file_name.empty() )
m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name.c_str(), match_or_save ? std::ios::in : std::ios::out );
m_pimpl->m_match_or_save = match_or_save;
}
//____________________________________________________________________________//
output_test_stream::output_test_stream( c_string_literal pattern_file_name, bool match_or_save )
: m_pimpl( new Impl )
{
if( pattern_file_name && pattern_file_name[0] != '\0' )
m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name, match_or_save ? std::ios::in : std::ios::out );
m_pimpl->m_match_or_save = match_or_save;
}
//____________________________________________________________________________//
output_test_stream::~output_test_stream()
{
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_empty( bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.empty() );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::check_length( std::size_t length_, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.length() == length_ );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_equal( c_string_literal arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_equal( std::string const& arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::match_pattern( bool flush_stream )
{
sync();
result_type result( true );
if( !m_pimpl->m_pattern_to_match_or_save.is_open() ) {
result = false;
*(result.p_message) << "Couldn't open pattern file for "
<< ( m_pimpl->m_match_or_save ? "reading" : "writing");
}
else {
if( m_pimpl->m_match_or_save ) {
std::string::const_iterator it = m_pimpl->m_synced_string.begin();
while( it != m_pimpl->m_synced_string.end() ) {
char c = m_pimpl->get_char();
result = !m_pimpl->m_pattern_to_match_or_save.fail() &&
!m_pimpl->m_pattern_to_match_or_save.eof() &&
(*it == c);
if( !result ) {
size_t suffix_size = std::min( m_pimpl->m_synced_string.end() - it, 5 );
size_t pos = it - m_pimpl->m_synced_string.begin();
// try to log area around the mismatch
*(result.p_message) << "Mismatch in a position " << pos << '\n'
<< "..." << m_pimpl->m_synced_string.substr( pos, suffix_size ) << "..." << '\n'
<< "..." << c;
size_t counter = suffix_size;
while( --counter ) {
char c = m_pimpl->get_char();
if( m_pimpl->m_pattern_to_match_or_save.fail() ||
m_pimpl->m_pattern_to_match_or_save.eof() )
break;
*(result.p_message) << c;
}
*(result.p_message) << "...";
// skip rest of the bytes. May help for further matching
m_pimpl->m_pattern_to_match_or_save.ignore( m_pimpl->m_synced_string.end() - it - suffix_size);
break;
}
++it;
}
}
else {
m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(),
static_cast<std::streamsize>( m_pimpl->m_synced_string.length() ) );
m_pimpl->m_pattern_to_match_or_save.flush();
}
}
if( flush_stream )
flush();
return result;
}
//____________________________________________________________________________//
void
output_test_stream::flush()
{
m_pimpl->m_synced_string.erase();
#ifndef BOOST_NO_STRINGSTREAM
str( std::string() );
#else
seekp( 0, std::ios::beg );
#endif
}
//____________________________________________________________________________//
std::size_t
output_test_stream::length()
{
sync();
return m_pimpl->m_synced_string.length();
}
//____________________________________________________________________________//
void
output_test_stream::sync()
{
#ifdef BOOST_NO_STRINGSTREAM
m_pimpl->m_synced_string.assign( str(), pcount() );
freeze( false );
#else
m_pimpl->m_synced_string = str();
#endif
}
//____________________________________________________________________________//
} // namespace test_toolbox
} // namespace boost
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.17 2003/06/20 11:01:15 rogeeff
// match_pattern show an error mismatch snippet
//
// Revision 1.16 2003/06/09 09:14:35 rogeeff
// added support for extended users predicate returning also error message
//
// ***************************************************************************
// EOF
<commit_msg>fix some but not all problems with previous commit<commit_after>// (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2003.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// See http://www.boost.org for updates, documentation, and revision history.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : supplies offline implemtation for the Test Tools
// ***************************************************************************
// Boost.Test
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_result.hpp>
// BOOST
#include <boost/config.hpp>
// STL
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
# ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::strcmp; using ::strncmp; using ::strlen; }
# endif
namespace boost {
namespace test_toolbox {
namespace detail {
// ************************************************************************** //
// ************** TOOL BOX Implementation ************** //
// ************************************************************************** //
void
checkpoint_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_test_suites )
unit_test_framework::checkpoint( message.str() )
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
message_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num )
{
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_messages )
message.str()
BOOST_UT_LOG_END
}
//____________________________________________________________________________//
void
warn_and_continue_impl( bool predicate, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num, bool add_fail_pass )
{
if( !predicate ) {
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_warnings )
(add_fail_pass ? "condition " : "") << message.str() << (add_fail_pass ? " is not satisfied" : "" )
BOOST_UT_LOG_END
}
else {
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )
"condition " << message.str() << " is satisfied"
BOOST_UT_LOG_END
}
}
//____________________________________________________________________________//
void
warn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num,
bool add_fail_pass )
{
warn_and_continue_impl( !!v,
message << (add_fail_pass && !v ? " is not satisfied. " : "" ) << *(v.p_message),
file_name, line_num, false );
}
//____________________________________________________________________________//
bool
test_and_continue_impl( bool predicate, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
if( !predicate ) {
unit_test_framework::unit_test_result::instance().inc_failed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " failed" : "")
BOOST_UT_LOG_END
return true;
}
else {
unit_test_framework::unit_test_result::instance().inc_passed_assertions();
BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )
(add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " passed" : "")
BOOST_UT_LOG_END
return false;
}
}
//____________________________________________________________________________//
bool
test_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
return test_and_continue_impl( !!v,
message << (add_fail_pass ? (!v ? " failed. " : " passed. ") : "") << *(v.p_message),
file_name, line_num, false, loglevel );
}
//____________________________________________________________________________//
void
test_and_throw_impl( bool predicate, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed(); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
void
test_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
bool add_fail_pass, unit_test_framework::log_level loglevel )
{
if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {
throw test_tool_failed(); // error already reported by test_and_continue_impl
}
}
//____________________________________________________________________________//
bool
equal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message,
c_string_literal file_name, std::size_t line_num,
unit_test_framework::log_level loglevel )
{
bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right);
left = left ? left : "null string";
right = right ? right : "null string";
if( !predicate ) {
return test_and_continue_impl( false,
wrap_stringstream().ref() << "test " << message.str() << " failed [" << left << " != " << right << "]",
file_name, line_num, false, loglevel );
}
return test_and_continue_impl( true, message, file_name, line_num, true, loglevel );
}
//____________________________________________________________________________//
bool
is_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value )
{
// return std::strncmp( symbol_name, symbol_value, std::strlen( symbol_name ) ) != 0;
return std::strcmp( symbol_name, symbol_value + 2 ) != 0;
}
//____________________________________________________________________________//
} // namespace detail
// ************************************************************************** //
// ************** output_test_stream ************** //
// ************************************************************************** //
struct output_test_stream::Impl
{
std::fstream m_pattern_to_match_or_save;
bool m_match_or_save;
std::string m_synced_string;
char get_char()
{
char res;
do {
m_pattern_to_match_or_save.get( res );
} while( res == '\r' &&
!m_pattern_to_match_or_save.fail() &&
!m_pattern_to_match_or_save.eof() );
return res;
}
void check_and_fill( extended_predicate_value& res )
{
if( !res.p_predicate_value.get() )
*(res.p_message) << "Output content: \"" << m_synced_string << '\"';
}
};
//____________________________________________________________________________//
output_test_stream::output_test_stream( std::string const& pattern_file_name, bool match_or_save )
: m_pimpl( new Impl )
{
if( !pattern_file_name.empty() )
m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name.c_str(), match_or_save ? std::ios::in : std::ios::out );
m_pimpl->m_match_or_save = match_or_save;
}
//____________________________________________________________________________//
output_test_stream::output_test_stream( c_string_literal pattern_file_name, bool match_or_save )
: m_pimpl( new Impl )
{
if( pattern_file_name && pattern_file_name[0] != '\0' )
m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name, match_or_save ? std::ios::in : std::ios::out );
m_pimpl->m_match_or_save = match_or_save;
}
//____________________________________________________________________________//
output_test_stream::~output_test_stream()
{
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_empty( bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.empty() );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::check_length( std::size_t length_, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string.length() == length_ );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_equal( c_string_literal arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_equal( std::string const& arg, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == arg );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream )
{
sync();
result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );
m_pimpl->check_and_fill( res );
if( flush_stream )
flush();
return res;
}
//____________________________________________________________________________//
extended_predicate_value
output_test_stream::match_pattern( bool flush_stream )
{
sync();
result_type result( true );
if( !m_pimpl->m_pattern_to_match_or_save.is_open() ) {
result = false;
*(result.p_message) << "Couldn't open pattern file for "
<< ( m_pimpl->m_match_or_save ? "reading" : "writing");
}
else {
if( m_pimpl->m_match_or_save ) {
std::string::const_iterator it = m_pimpl->m_synced_string.begin();
while( it != m_pimpl->m_synced_string.end() ) {
char c = m_pimpl->get_char();
result = !m_pimpl->m_pattern_to_match_or_save.fail() &&
!m_pimpl->m_pattern_to_match_or_save.eof() &&
(*it == c);
if( !result ) {
std::size_t suffix_size = std::min( m_pimpl->m_synced_string.end() - it, static_cast<std::ptrdiff_t>(5) );
std::size_t pos = it - m_pimpl->m_synced_string.begin();
// try to log area around the mismatch
*(result.p_message) << "Mismatch in a position " << pos << '\n'
<< "..." << m_pimpl->m_synced_string.substr( pos, suffix_size ) << "..." << '\n'
<< "..." << c;
std::size_t counter = suffix_size;
while( --counter ) {
char c = m_pimpl->get_char();
if( m_pimpl->m_pattern_to_match_or_save.fail() ||
m_pimpl->m_pattern_to_match_or_save.eof() )
break;
*(result.p_message) << c;
}
*(result.p_message) << "...";
// skip rest of the bytes. May help for further matching
m_pimpl->m_pattern_to_match_or_save.ignore( m_pimpl->m_synced_string.end() - it - suffix_size);
break;
}
++it;
}
}
else {
m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(),
static_cast<std::streamsize>( m_pimpl->m_synced_string.length() ) );
m_pimpl->m_pattern_to_match_or_save.flush();
}
}
if( flush_stream )
flush();
return result;
}
//____________________________________________________________________________//
void
output_test_stream::flush()
{
m_pimpl->m_synced_string.erase();
#ifndef BOOST_NO_STRINGSTREAM
str( std::string() );
#else
seekp( 0, std::ios::beg );
#endif
}
//____________________________________________________________________________//
std::size_t
output_test_stream::length()
{
sync();
return m_pimpl->m_synced_string.length();
}
//____________________________________________________________________________//
void
output_test_stream::sync()
{
#ifdef BOOST_NO_STRINGSTREAM
m_pimpl->m_synced_string.assign( str(), pcount() );
freeze( false );
#else
m_pimpl->m_synced_string = str();
#endif
}
//____________________________________________________________________________//
} // namespace test_toolbox
} // namespace boost
// ***************************************************************************
// Revision History :
//
// $Log$
// Revision 1.18 2003/06/20 18:13:54 beman_dawes
// fix some but not all problems with previous commit
//
// Revision 1.17 2003/06/20 11:01:15 rogeeff
// match_pattern show an error mismatch snippet
//
// Revision 1.16 2003/06/09 09:14:35 rogeeff
// added support for extended users predicate returning also error message
//
// ***************************************************************************
// EOF
<|endoftext|> |
<commit_before>#include "03.hpp"
//////////////
// Includes //
#include <vector>
#include "../parser.hpp"
#include "../json.hpp"
#include "utils.hpp"
//////////
// Code //
// Testing the number array.
bool testNumArray(JValue numArray) {
if (!numArray.isArray())
return true;
std::vector<JValue> vals = numArray.jArray();
for (int i = 0; i < vals.size(); i++)
if (!vals[i].isNumber() || !around((double)(i + 1), vals[i].jNumber(), 1))
return true;
return false;
}
// Testing the string array.
bool testStrArray(JValue strArray) {
return false;
}
// Testing the bool array.
bool testBoolArray(JValue boolArray) {
return false;
}
// Testing the Array portion of parseJSON.
int runTest03() {
JValue numArray = parseJSON("[1, 2, 3, 4, 5]");
JValue strArray = parseJSON("[\"testing\", \"with spaces\", \"and a 'quote\"]");
JValue boolArray = parseJSON("[true, false, true]");
if (testNumArray(numArray))
return 1;
if (testStrArray(strArray))
return 1;
if (testBoolArray(boolArray))
return 1;
return 0;
}
<commit_msg>Added testing for the string JSON array.<commit_after>#include "03.hpp"
//////////////
// Includes //
#include <iostream>
#include <vector>
#include "../parser.hpp"
#include "../json.hpp"
#include "utils.hpp"
//////////
// Code //
// Testing the number array.
bool testNumArray(const JValue& numArray) {
if (!numArray.isArray())
return true;
std::vector<JValue> vals = numArray.jArray();
for (int i = 0; i < vals.size(); i++)
if (!vals[i].isNumber() || !around((double)(i + 1), vals[i].jNumber(), 1))
return true;
return false;
}
// Testing the string array.
bool testStrArray(const JValue& strArray) {
if (!strArray.isArray())
return true;
auto validate = [](const JValue& str, const std::string& tStr) -> bool const {
if (!str.isString() || str.jString().compare(tStr) != 0)
return true;
return false;
};
std::vector<std::string> targets;
targets.push_back("testing");
targets.push_back("with spaces");
targets.push_back("and a 'quote");
for (int i = 0; i < targets.size(); i++) {
JValue v = strArray.jArray()[i];
if (validate(v, targets[i])) {
std::string out;
if (v.isNull())
out = "null";
else
out = v.jArray()[i].jString();
std::cerr << out
<< " != "
<< targets[i]
<< std::endl;
}
}
return false;
}
// Testing the bool array.
bool testBoolArray(const JValue& boolArray) {
return false;
}
// Testing the Array portion of parseJSON.
int runTest03() {
JValue numArray = parseJSON("[1, 2, 3, 4, 5]");
JValue strArray = parseJSON("[\"testing\", \"with spaces\", \"and a 'quote\"]");
JValue boolArray = parseJSON("[true, false, true]");
if (testNumArray(numArray))
return 1;
if (testStrArray(strArray))
return 1;
if (testBoolArray(boolArray))
return 1;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************************/
/*************************************************************************************/
/** **/
/** Tinyplayer - TibV2 example **/
/** written by Tammo 'kb' Hinrichs 2000-2008 **/
/** This file is in the public domain **/
/** "Patient Zero" is (C) Melwyn+LB 2005, do not redistribute **/
/** **/
/*************************************************************************************/
/*************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <SDL2/SDL.h>
#include "v2mplayer.h"
#include "libv2.h"
#include "v2mconv.h"
#include "sounddef.h"
#include "version.h"
static V2MPlayer player;
static SDL_AudioDeviceID dev;
////////////////////////////////////////////////////////////////////////////////////////////////////
static void V2mPlayerTitle()
{
printf("Farbrausch Tiny Music Player v0.dontcare TWO\n");
printf("Code and Synthesizer (C) 2000-2008 kb/Farbrausch\n");
printf("Version: %s\n", V2M_VERSION);
printf("SDL Port by %s\n\n", V2M_URL);
}
static void V2mPlayerUsage()
{
printf("Usage : v2mplayer [options] <input_file_v2m>\n\n");
printf("options:\n");
printf(" -b N force power size stdin buffer (int, optional, [0..10])\n");
printf(" -s N.N start at position (float, optional, in s., default = 0.0)\n");
printf(" -k key/auto stop (bool, optional, default = false)\n");
printf(" -o str output v2m newest version (string, optional, default = none)\n");
printf(" -h this help\n");
}
static void sdl_callback(void *userdata, Uint8 * stream, int len) {
player.Render((float*) stream, len / 8);
}
static bool init_sdl()
{
if (SDL_Init(SDL_INIT_AUDIO) < 0)
{
SDL_Log("Couldn't initialize SDL: %s\n",SDL_GetError());
SDL_Quit();
return false;
}
SDL_AudioSpec desired, actual;
desired.channels = 2;
desired.freq = 44100;
desired.samples = 1024;
desired.format = AUDIO_F32;
desired.callback = sdl_callback;
dev = SDL_OpenAudioDevice(NULL, 0, &desired, &actual, 0);
if (! dev)
{
SDL_Log("Failed to open audio, %s\n", SDL_GetError());
return false;
}
return true;
}
static unsigned char* check_and_convert(unsigned char* tune, unsigned int* length)
{
sdInit();
if (tune[2] != 0 || tune[3] != 0)
{
SDL_LogCritical(SDL_LOG_CATEGORY_INPUT, "No valid input file");
return NULL;
}
ssbase base;
int version = CheckV2MVersion(tune, *length, base);
if (version < 0)
{
SDL_LogCritical(SDL_LOG_CATEGORY_INPUT, "Failed to Check Version on input file");
return NULL;
}
uint8_t* converted;
int converted_length;
ConvertV2M(tune, *length, &converted, &converted_length);
*length = converted_length;
free(tune);
return converted;
}
int main(int argc, char** argv)
{
V2mPlayerTitle();
int opt;
int startPos = 0;
int fbuf = -1;
int fouts = 0;
int fkey = 0;
int fhelp = 0;
char *foutput;
while ((opt = getopt(argc, argv, ":b:ko:hs:")) != -1)
{
switch(opt)
{
case 'b':
fbuf = atoi(optarg);
break;
case 'k':
fkey = 1;
break;
case 'o':
foutput = optarg;
fouts = 1;
break;
case 'h':
fhelp = 1;
break;
case 's':
startPos = (int)(atof(optarg) * 1000);
startPos = (startPos > 0) ? startPos : 0;
break;
case ':':
printf("option needs a value\n");
break;
case '?':
printf("unknown option: %c\n", optopt);
break;
}
}
if(fhelp > 0)
{
V2mPlayerUsage();
return 1;
}
unsigned char* theTune;
FILE* file;
uint64_t size;
unsigned int blksz = 4096, read = 0, eofcnt = 0;
char ch;
if(optind + 1 > argc)
{
file = stdin;
if (fbuf < 0)
{
eofcnt = 0;
size = blksz;
theTune = (unsigned char*) calloc(1, size);
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
ch = getc(stdin);
while (ch != EOF || eofcnt < blksz)
{
if (ch != EOF) {eofcnt = 0;} else {eofcnt++;}
if (read == size)
{
size += blksz;
theTune = (unsigned char*)realloc(theTune, size * sizeof(unsigned char));
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
}
theTune[read] = ch;
read++;
ch = getc(stdin);
}
read -= eofcnt;
} else {
if (fbuf < 0 || fbuf > 10) fbuf = 4;
fbuf += 20;
size = 1 << fbuf;
theTune = (unsigned char*) calloc(1, size);
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
read = fread(theTune, 1, size, file);
}
printf("Now Playing: stdin(%d[%Ld])\n", read, size);
size = read;
} else {
const char *v2m_filename = argv[optind];
file = fopen(v2m_filename, "rb");
if (file == NULL)
{
fprintf(stderr, "Failed to open %s\n", v2m_filename);
return 1;
}
fseek(file, 0, SEEK_END);
size = ftell(file);
fseek(file, 0, SEEK_SET);
printf("Now Playing: %s\n", v2m_filename);
theTune = (unsigned char*) calloc(1, size);
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
read = fread(theTune, 1, size, file);
}
if (size != read)
{
fprintf(stderr, "Invalid read size\n");
return 1;
}
fclose(file);
theTune = check_and_convert(theTune, &read);
if (theTune == NULL)
{
fprintf(stderr, "Error convert to newest\n");
exit(1);
}
printf("Convert: %d b\n", read);
while (theTune[read--] == 0){}
read++;
read++;
printf("Strip: %d b\n", read);
if (fouts)
{
FILE* fout;
fout = fopen(foutput, "a");
if (fout == NULL)
{
fprintf(stderr, "Failed to open %s\n", foutput);
return 1;
}
fwrite(theTune, 1, read, fout);
fclose(fout);
}
player.Init();
player.Open(theTune);
if (! init_sdl()) {
return 1;
}
player.Play(startPos);
SDL_PauseAudioDevice(dev, 0);
printf("Length: %d\n", player.Length());
if (fkey > 0)
{
printf("\n\npress Enter to quit\n");
getc(stdin);
} else {
while(player.IsPlaying()) { sleep(1); }
}
SDL_PauseAudioDevice(dev, 1);
SDL_Quit();
player.Close();
free(theTune);
return 0;
}
<commit_msg>add output gain<commit_after>/*************************************************************************************/
/*************************************************************************************/
/** **/
/** Tinyplayer - TibV2 example **/
/** written by Tammo 'kb' Hinrichs 2000-2008 **/
/** This file is in the public domain **/
/** "Patient Zero" is (C) Melwyn+LB 2005, do not redistribute **/
/** **/
/*************************************************************************************/
/*************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <SDL2/SDL.h>
#include "v2mplayer.h"
#include "libv2.h"
#include "v2mconv.h"
#include "sounddef.h"
#include "version.h"
static V2MPlayer player;
static SDL_AudioDeviceID dev;
////////////////////////////////////////////////////////////////////////////////////////////////////
static void V2mPlayerTitle()
{
printf("Farbrausch Tiny Music Player v0.dontcare TWO\n");
printf("Code and Synthesizer (C) 2000-2008 kb/Farbrausch\n");
printf("Version: %s\n", V2M_VERSION);
printf("SDL Port by %s\n\n", V2M_URL);
}
static void V2mPlayerUsage()
{
printf("Usage : v2mplayer [options] <input_file_v2m>\n\n");
printf("options:\n");
printf(" -b N force power size stdin buffer (int, optional, [0..10])\n");
printf(" -s N.N start at position (float, optional, in s., default = 0.0)\n");
printf(" -g N.N gain (float, optional, default = 0.0)\n");
printf(" -k key/auto stop (bool, optional, default = false)\n");
printf(" -o str output v2m newest version (string, optional, default = none)\n");
printf(" -h this help\n");
}
static float gain = 1.0f;
static void sdl_callback(void *userdata, Uint8 * stream, int len) {
float* buf = (float*) stream;
player.Render(buf, len / 8);
for (int i = 0; i < (len / 4); ++i) {
buf[i] *= gain;
}
}
static bool init_sdl()
{
if (SDL_Init(SDL_INIT_AUDIO) < 0)
{
SDL_Log("Couldn't initialize SDL: %s\n",SDL_GetError());
SDL_Quit();
return false;
}
SDL_AudioSpec desired, actual;
desired.channels = 2;
desired.freq = 44100;
desired.samples = 1024;
desired.format = AUDIO_F32;
desired.callback = sdl_callback;
dev = SDL_OpenAudioDevice(NULL, 0, &desired, &actual, 0);
if (! dev)
{
SDL_Log("Failed to open audio, %s\n", SDL_GetError());
return false;
}
return true;
}
static unsigned char* check_and_convert(unsigned char* tune, unsigned int* length)
{
sdInit();
if (tune[2] != 0 || tune[3] != 0)
{
SDL_LogCritical(SDL_LOG_CATEGORY_INPUT, "No valid input file");
return NULL;
}
ssbase base;
int version = CheckV2MVersion(tune, *length, base);
if (version < 0)
{
SDL_LogCritical(SDL_LOG_CATEGORY_INPUT, "Failed to Check Version on input file");
return NULL;
}
uint8_t* converted;
int converted_length;
ConvertV2M(tune, *length, &converted, &converted_length);
*length = converted_length;
free(tune);
return converted;
}
int main(int argc, char** argv)
{
V2mPlayerTitle();
int opt;
int startPos = 0;
int fbuf = -1;
int fouts = 0;
int fkey = 0;
int fhelp = 0;
char *foutput;
while ((opt = getopt(argc, argv, ":b:ko:hs:g:")) != -1)
{
switch(opt)
{
case 'b':
fbuf = atoi(optarg);
break;
case 'k':
fkey = 1;
break;
case 'o':
foutput = optarg;
fouts = 1;
break;
case 'h':
fhelp = 1;
break;
case 'g':
gain = atof(optarg);
break;
case 's':
startPos = (int)(atof(optarg) * 1000);
startPos = (startPos > 0) ? startPos : 0;
break;
case ':':
printf("option needs a value\n");
break;
case '?':
printf("unknown option: %c\n", optopt);
break;
}
}
if(fhelp > 0)
{
V2mPlayerUsage();
return 1;
}
unsigned char* theTune;
FILE* file;
uint64_t size;
unsigned int blksz = 4096, read = 0, eofcnt = 0;
char ch;
if(optind + 1 > argc)
{
file = stdin;
if (fbuf < 0)
{
eofcnt = 0;
size = blksz;
theTune = (unsigned char*) calloc(1, size);
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
ch = getc(stdin);
while (ch != EOF || eofcnt < blksz)
{
if (ch != EOF) {eofcnt = 0;} else {eofcnt++;}
if (read == size)
{
size += blksz;
theTune = (unsigned char*)realloc(theTune, size * sizeof(unsigned char));
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
}
theTune[read] = ch;
read++;
ch = getc(stdin);
}
read -= eofcnt;
} else {
if (fbuf < 0 || fbuf > 10) fbuf = 4;
fbuf += 20;
size = 1 << fbuf;
theTune = (unsigned char*) calloc(1, size);
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
read = fread(theTune, 1, size, file);
}
printf("Now Playing: stdin(%d[%Ld])\n", read, size);
size = read;
} else {
const char *v2m_filename = argv[optind];
file = fopen(v2m_filename, "rb");
if (file == NULL)
{
fprintf(stderr, "Failed to open %s\n", v2m_filename);
return 1;
}
fseek(file, 0, SEEK_END);
size = ftell(file);
fseek(file, 0, SEEK_SET);
printf("Now Playing: %s\n", v2m_filename);
theTune = (unsigned char*) calloc(1, size);
if (theTune == NULL)
{
fprintf(stderr, "Error memory allocator: %Ld b\n", size);
exit(1);
}
read = fread(theTune, 1, size, file);
}
if (size != read)
{
fprintf(stderr, "Invalid read size\n");
return 1;
}
fclose(file);
theTune = check_and_convert(theTune, &read);
if (theTune == NULL)
{
fprintf(stderr, "Error convert to newest\n");
exit(1);
}
printf("Convert: %d b\n", read);
while (theTune[read--] == 0){}
read++;
read++;
printf("Strip: %d b\n", read);
if (fouts)
{
FILE* fout;
fout = fopen(foutput, "a");
if (fout == NULL)
{
fprintf(stderr, "Failed to open %s\n", foutput);
return 1;
}
fwrite(theTune, 1, read, fout);
fclose(fout);
}
player.Init();
player.Open(theTune);
if (! init_sdl()) {
return 1;
}
player.Play(startPos);
SDL_PauseAudioDevice(dev, 0);
printf("Length: %d\n", player.Length());
if (fkey > 0)
{
printf("\n\npress Enter to quit\n");
getc(stdin);
} else {
while(player.IsPlaying()) { sleep(1); }
}
SDL_PauseAudioDevice(dev, 1);
SDL_Quit();
player.Close();
free(theTune);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2007, 2008 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <algorithm>
#include <string>
#include <vector>
#include "libmv/correspondence/correspondence.h"
#include "libmv/correspondence/feature.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/image_pyramid.h"
#include "libmv/image/image_sequence_io.h"
#include "libmv/image/cached_image_sequence.h"
#include "libmv/image/pyramid_sequence.h"
#include "third_party/gflags/gflags.h"
DEFINE_bool(debug_images, true, "Output debug images.");
DEFINE_double(sigma, 0.9, "Blur filter strength.");
DEFINE_int32(pyramid_levels, 4, "Number of levels in the image pyramid.");
using namespace libmv;
using std::sort;
using std::string;
using std::vector;
void WriteOutputImage(const FloatImage &image,
CorrespondencesView<KLTPointFeature>::Iterator features,
const char *output_filename) {
FloatImage output_image(image.Height(), image.Width(), 3);
for (int i = 0; i < image.Height(); ++i) {
for (int j = 0; j < image.Width(); ++j) {
output_image(i,j,0) = image(i,j);
output_image(i,j,1) = image(i,j);
output_image(i,j,2) = image(i,j);
}
}
Vec3 green;
green << 0, 1, 0;
for (; !features.Done(); features.Next()) {
DrawFeature(*features.feature(), green, &output_image);
}
WritePnm(output_image, output_filename);
}
int main(int argc, char **argv) {
google::SetUsageMessage("Track a sequence.");
google::ParseCommandLineFlags(&argc, &argv, true);
// This is not the place for this. I am experimenting with what sort of API
// will be convenient for the tracking base classes.
vector<string> files;
for (int i = 0; i < argc; ++i) {
files.push_back(argv[i]);
}
sort(files.begin(), files.end());
if (files.size() < 2) {
printf("Not enough files.\n");
return 1;
}
ImageCache cache;
ImageSequence *source = ImageSequenceFromFiles(files, &cache);
PyramidSequence *pyramid_sequence =
MakePyramidSequence(source, FLAGS_pyramid_levels, FLAGS_sigma);
KLTContext klt;
Correspondences correspondences;
// TODO(keir): Really have to get a scoped_ptr<> implementation!
// Consider taking the one from boost but editing out the cruft.
ImagePyramid *pyramid = pyramid_sequence->Pyramid(0);
KLTContext::FeatureList features;
klt.DetectGoodFeatures(pyramid->Level(0), &features);
// WriteOutputImage(pyramid->Level(0), klt, features,
// (files[0]+".out.ppm").c_str());
int i = 0;
for (KLTContext::FeatureList::iterator it = features.begin();
it != features.end(); ++it, ++i) {
correspondences.Insert(0, i, *it);
}
CorrespondencesView<KLTPointFeature> klt_correspondences(&correspondences);
// TODO(keir): Use correspondences here!
for (size_t i = 1; i < files.size(); ++i) {
printf("Tracking %2zd features in %s\n", features.size(), files[i].c_str());
CorrespondencesView<KLTPointFeature>::Iterator it =
klt_correspondences.ScanFeaturesForImage(i-1);
for (; !it.Done(); it.Next()) {
KLTPointFeature *next_position = new KLTPointFeature;
if (klt.TrackFeature(pyramid_sequence->Pyramid(i-1), *it.feature(),
pyramid_sequence->Pyramid(i), next_position)) {
correspondences.Insert(i, it.track(), next_position);
} else {
delete next_position;
}
}
WriteOutputImage(
pyramid_sequence->Pyramid(i)->Level(0),
klt_correspondences.ScanFeaturesForImage(i),
(files[i]+".out.ppm").c_str());
}
// XXX
// TODO(keir): Now do something useful with 'correspondences'!
// XXX
//
return 0;
}
<commit_msg>Fix track compilation.<commit_after>// Copyright (c) 2007, 2008 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <algorithm>
#include <string>
#include <vector>
#include "libmv/correspondence/correspondence.h"
#include "libmv/correspondence/feature.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/image_pyramid.h"
#include "libmv/image/image_sequence_io.h"
#include "libmv/image/cached_image_sequence.h"
#include "libmv/image/pyramid_sequence.h"
#include "third_party/gflags/gflags.h"
DEFINE_bool(debug_images, true, "Output debug images.");
DEFINE_double(sigma, 0.9, "Blur filter strength.");
DEFINE_int32(pyramid_levels, 4, "Number of levels in the image pyramid.");
using namespace libmv;
using std::sort;
using std::string;
using std::vector;
void WriteOutputImage(const FloatImage &image,
CorrespondencesView<KLTPointFeature>::Iterator features,
const char *output_filename) {
FloatImage output_image(image.Height(), image.Width(), 3);
for (int i = 0; i < image.Height(); ++i) {
for (int j = 0; j < image.Width(); ++j) {
output_image(i,j,0) = image(i,j);
output_image(i,j,1) = image(i,j);
output_image(i,j,2) = image(i,j);
}
}
Vec3 green;
green << 0, 1, 0;
for (; !features.Done(); features.Next()) {
DrawFeature(*features.feature(), green, &output_image);
}
WritePnm(output_image, output_filename);
}
int main(int argc, char **argv) {
google::SetUsageMessage("Track a sequence.");
google::ParseCommandLineFlags(&argc, &argv, true);
// This is not the place for this. I am experimenting with what sort of API
// will be convenient for the tracking base classes.
vector<string> files;
for (int i = 0; i < argc; ++i) {
files.push_back(argv[i]);
}
sort(files.begin(), files.end());
if (files.size() < 2) {
printf("Not enough files.\n");
return 1;
}
ImageCache cache;
ImageSequence *source = ImageSequenceFromFiles(files, &cache);
PyramidSequence *pyramid_sequence =
MakePyramidSequence(source, FLAGS_pyramid_levels, FLAGS_sigma);
KLTContext klt;
Correspondences correspondences;
// TODO(keir): Really have to get a scoped_ptr<> implementation!
// Consider taking the one from boost but editing out the cruft.
ImagePyramid *pyramid = pyramid_sequence->Pyramid(0);
KLTContext::FeatureList features;
klt.DetectGoodFeatures(pyramid->Level(0), &features);
int i = 0;
for (KLTContext::FeatureList::iterator it = features.begin();
it != features.end(); ++it, ++i) {
correspondences.Insert(0, i, *it);
}
CorrespondencesView<KLTPointFeature> klt_correspondences(&correspondences);
if (FLAGS_debug_images) {
WriteOutputImage(
pyramid_sequence->Pyramid(0)->Level(0),
klt_correspondences.ScanFeaturesForImage(0),
(files[0]+".out.ppm").c_str());
}
// TODO(keir): Use correspondences here!
for (size_t i = 1; i < files.size(); ++i) {
printf("Tracking %2zd features in %s\n", features.size(), files[i].c_str());
CorrespondencesView<KLTPointFeature>::Iterator it =
klt_correspondences.ScanFeaturesForImage(i-1);
for (; !it.Done(); it.Next()) {
KLTPointFeature *next_position = new KLTPointFeature;
if (klt.TrackFeature(pyramid_sequence->Pyramid(i-1), *it.feature(),
pyramid_sequence->Pyramid(i), next_position)) {
correspondences.Insert(i, it.track(), next_position);
} else {
delete next_position;
}
}
if (FLAGS_debug_images) {
WriteOutputImage(
pyramid_sequence->Pyramid(i)->Level(0),
klt_correspondences.ScanFeaturesForImage(i),
(files[i]+".out.ppm").c_str());
}
}
// XXX
// TODO(keir): Now do something useful with 'correspondences'!
// XXX
//
return 0;
}
<|endoftext|> |
<commit_before>#include "toxchannel.hpp"
#include "messages.hpp"
namespace linux {
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
}
namespace toxChannel {
namespace util {
/* Thanks to [0xd34df00d](https://github.com/0xd34df00d) for this bunch of functions */
#include <cassert>
std::string hex2bin(std::string const& s) {
assert(s.length() % 2 == 0);
std::string sOut;
sOut.reserve(s.length() / 2);
std::string extract;
for (std::string::const_iterator pos = s.begin(); pos < s.end(); pos += 2)
{
extract.assign(pos, pos + 2);
sOut.push_back(std::stoi(extract, nullptr, 16));
}
return sOut;
}
template <size_t Size>
std::string ToxId2HR (const uint8_t* address)
{
std::string result;
auto toHexChar = [] (uint8_t num) -> char
{
return num >= 10 ? (num - 10 + 'A') : (num + '0');
};
for (size_t i = 0; i < Size; ++i)
{
const auto num = address [i];
result += toHexChar ((num & 0xf0) >> 4);
result += toHexChar (num & 0xf);
}
return result;
}
template <size_t Size>
std::string ToxId2HR (const std::array<uint8_t, Size>& address)
{
return ToxId2HR<Size>(address.data ());
}
#include <string.h>
}
static Tox * toxInit(const std::string& datafile)
{
TOX_ERR_NEW tox_error;
Tox* retval;
struct Tox_Options options;
tox_options_default(&options);
try {
const auto dataFileName = datafile.c_str();
struct linux::stat sb;
if ((stat(dataFileName, &sb) == -1))
throw config::option_error("No such file");
if ((sb.st_mode & S_IFMT) != S_IFREG)
throw config::option_error("Not a file");
const size_t filesize = sb.st_size;
const auto toxData = std::make_unique<uint8_t[]>(filesize);
const int toxfd = linux::open(dataFileName, O_RDONLY);
int result = linux::read(toxfd, toxData.get(), filesize);
if (result < 0)
throw config::option_error("Error reading file");
result = linux::close(toxfd);
if (result < 0)
throw config::option_error("Error closing file");
if (result > 0)
throw config::option_error("Tox data is encrypted");
options.savedata_data = toxData.get();
options.savedata_length = filesize;
options.savedata_type = TOX_SAVEDATA_TYPE_TOX_SAVE;
retval = tox_new(&options, &tox_error);
} catch (config::option_error e) {
std::cerr << "[DEBUG] Can't open tox data: " << e.what() << std::endl;
options.savedata_data = nullptr;
options.savedata_length = 0;
retval = tox_new(&options, &tox_error);
}
switch (tox_error) {
case TOX_ERR_NEW_OK:
std::cerr << "[DEBUG] toxdata successfully loaded" << std::endl;
break;
case TOX_ERR_NEW_LOAD_BAD_FORMAT:
std::cerr << "[DEBUG] toxdata file is damaged" << std::endl;
break;
default:
std::cerr << "[DEBUG] tox_new error: " << tox_error << std::endl;
}
return retval;
}
ToxChannel::ToxChannel(Hub::Hub* hub, const std::string& config) :
channeling::Channel(hub, config),
_tox(toxInit(std::string(_config["datafile"]))), /** TODO: make options handling */
wasConnected(false)
{}
std::future<void> ToxChannel::activate() {
return std::async(std::launch::async, [this]() {
if (_active)
return;
_pipeRunning = true;
toxStart();
_thread = std::make_unique<std::thread>(std::thread(&ToxChannel::pollThread, this));
_active = true;
});
}
void ToxChannel::incoming(const messaging::message_ptr&& msg) {
if (msg->type() == messaging::MessageType::Text) {
const auto textmsg = messaging::TextMessage::fromMessage(msg);
std::cerr << "[DEBUG] #tox " << _name << " " << textmsg->data() << std::endl;
static uint8_t msg[TOX_MAX_MESSAGE_LENGTH];
const auto len = snprintf(reinterpret_cast<char *>(msg), TOX_MAX_MESSAGE_LENGTH,
"[%s]: %s",
textmsg->user()->name().c_str(), textmsg->data().c_str());
tox_group_message_send(_tox, 0, msg, len);
}
}
void ToxChannel::pollThread() {
std::cerr << "[DEBUG] Starting tox thread" << std::endl;
while (_pipeRunning) {
tox_iterate(_tox);
auto wait = tox_iteration_interval(_tox);
std::this_thread::sleep_for( std::chrono::milliseconds (wait));
}
}
ToxChannel::~ToxChannel() {
if (_thread) {
_pipeRunning = false;
_thread->join();
}
try {
const auto dataFileName = std::string(_config["datafile"]).c_str();
const size_t filesize = tox_get_savedata_size(_tox);
const auto toxData = std::make_unique<uint8_t[]>(filesize);
tox_get_savedata(_tox, toxData.get());
const int toxfd = linux::open(dataFileName, O_WRONLY | O_CREAT, 0644);
int result = linux::write(toxfd, toxData.get(), filesize);
if (result < 0)
throw config::option_error("Error writing file");
std::cerr << "[DEBUG] #tox " << _name << " Successfully saved " << result << " bytes of tox data" << std::endl;
result = linux::close(toxfd);
if (result < 0)
throw config::option_error("Error closing file");
} catch (config::option_error e) {
std::cerr << "[DEBUG] Can't save tox data: " << e.what() << std::endl;
}
tox_kill(_tox);
}
void ToxChannel::friendRequestCallback(Tox* tox, const uint8_t* public_key, const uint8_t* data, size_t length, void* userdata) {
TOX_ERR_FRIEND_ADD friend_error;
const auto channel = static_cast<ToxChannel *>(userdata);
const auto friendNum = tox_friend_add_norequest(tox, public_key, &friend_error); /** TODO: check friend_error */
std::cerr << "[DEBUG] tox id with data" << data << " of " << length << " bytes " << util::ToxId2HR<TOX_ADDRESS_SIZE>(public_key) << " wants to be your friend. Added with #" << friendNum << std::endl;
}
void ToxChannel::messageCallback(Tox* tox, uint32_t friendnumber, TOX_MESSAGE_TYPE type, const uint8_t* message, size_t length, void* userdata) {
const auto channel = static_cast<ToxChannel *>(userdata);
const auto buffer = std::make_unique<char *>(new char[length + 1]);
snprintf(*buffer, length + 1, "%s", message);
switch (type) {
case TOX_MESSAGE_TYPE_NORMAL:
std::cerr << "[DEBUG] Message from friend #" << friendnumber << "> " << *buffer << std::endl;
if (util::strncmp(cmd_invite, *buffer, length) == 0)
tox_invite_friend(tox, friendnumber, 0);
break;
case TOX_MESSAGE_TYPE_ACTION:
std::cerr << "[DEBUG] Action from friend #" << friendnumber << "> " << *buffer << std::endl;
break;
default:
std::cerr << "[DEBUG] Unknown message type from " << friendnumber << "> " << *buffer << std::endl;
}
}
void ToxChannel::groupMessageCallback(Tox* tox, int32_t groupnumber, int32_t peernumber, const uint8_t* message, uint16_t length, void* userdata) {
const auto channel = static_cast<ToxChannel *>(userdata);
const auto nameBuffer = std::make_unique<uint8_t *>(new uint8_t[TOX_MAX_NAME_LENGTH]);
const auto nameLen = tox_group_peername(tox, groupnumber, peernumber, *nameBuffer);
const auto name = std::make_unique<char *>(new char[nameLen + 2]);
snprintf(*name, nameLen + 1, "%s", *nameBuffer);
const auto msg = std::make_unique<char *>(new char[length + 2]);
snprintf(*msg, length + 1, "%s", message);
if (std::string(*name) != std::string(channel->_config.get("nickname", defaultBotName))) {
const auto newMessage = std::make_shared<const messaging::TextMessage>(channel->_id,
std::make_shared<const messaging::User>(messaging::User(*name)),
*msg);
std::cerr << "[DEBUG] tox Group msg " << newMessage->user()->name() << "> " << newMessage->data() << std::endl;
channel->_hub->newMessage(std::move(newMessage));
}
}
const messaging::message_ptr ToxChannel::parse(const char* line) const
{
const std::string s(line);
const auto name = s.substr(0, s.find(":"));
const auto text = s.substr(s.find(":"), s.length());
const auto msg = std::make_shared<const messaging::TextMessage>(_id,
std::make_shared<const messaging::User>(messaging::User(name.c_str())),
text.c_str());
return msg;
}
int ToxChannel::toxStart() {
TOX_ERR_SET_INFO result;
TOX_ERR_BOOTSTRAP bootstrap_result;
//std::unique_ptr<uint8_t[]> pubKey(new uint8_t[TOX_CLIENT_ID_SIZE]);
tox_callback_friend_request(_tox, friendRequestCallback, this);
tox_callback_friend_message(_tox, messageCallback, this);
tox_callback_group_message(_tox, groupMessageCallback, this);
const std::string nick = _config.get("nickname", defaultBotName);
const uint8_t* nickData = reinterpret_cast<const uint8_t *>(nick.c_str());
tox_self_set_name(_tox, nickData, nick.length(), &result);
if (result)
throw channeling::activate_error(ERR_TOX_INIT + "(tox_set_name)");
const std::string statusMsg = _config.get("status_message", defaultStatusMessage);
const uint8_t* statusData = reinterpret_cast<const uint8_t *>(statusMsg.c_str());
tox_self_set_status_message(_tox, statusData, statusMsg.length(), &result);
if (result)
throw channeling::activate_error(ERR_TOX_INIT + "(tox_set_status_message)");
tox_self_set_status(_tox, defaultBotStatus);
if (tox_self_get_connection_status(_tox) == TOX_CONNECTION_NONE)
tox_bootstrap(_tox, defaultBootstrapAddress, defaultBootstrapPort, reinterpret_cast<const uint8_t *>(util::hex2bin(defaultBootstrapKey).c_str()), &bootstrap_result);
if (bootstrap_result)
throw channeling::activate_error(ERR_TOX_INIT + ": Can't decode bootstrapping ip");
std::cerr << "[DEBUG] Bootstrapping" << std::endl;
/* TODO: Make timeout exception handling */
while (!wasConnected) {
TOX_CONNECTION status;
tox_iterate(_tox);
auto wait = tox_iteration_interval(_tox);
if (!wasConnected && (TOX_CONNECTION_NONE != tox_self_get_connection_status(_tox))) {
std::array<uint8_t, TOX_ADDRESS_SIZE> address;
tox_self_get_address (_tox, address.data ());
std::cerr << "[DEBUG] Tox is connected with id " << util::ToxId2HR (address) << std::endl
;
wasConnected = true;
}
std::this_thread::sleep_for( std::chrono::milliseconds (wait));
}
tox_add_groupchat (_tox);
return 0;
}
}
<commit_msg>[Tox] Bootstrap check localized<commit_after>#include "toxchannel.hpp"
#include "messages.hpp"
namespace linux {
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
}
namespace toxChannel {
namespace util {
/* Thanks to [0xd34df00d](https://github.com/0xd34df00d) for this bunch of functions */
#include <cassert>
std::string hex2bin(std::string const& s) {
assert(s.length() % 2 == 0);
std::string sOut;
sOut.reserve(s.length() / 2);
std::string extract;
for (std::string::const_iterator pos = s.begin(); pos < s.end(); pos += 2)
{
extract.assign(pos, pos + 2);
sOut.push_back(std::stoi(extract, nullptr, 16));
}
return sOut;
}
template <size_t Size>
std::string ToxId2HR (const uint8_t* address)
{
std::string result;
auto toHexChar = [] (uint8_t num) -> char
{
return num >= 10 ? (num - 10 + 'A') : (num + '0');
};
for (size_t i = 0; i < Size; ++i)
{
const auto num = address [i];
result += toHexChar ((num & 0xf0) >> 4);
result += toHexChar (num & 0xf);
}
return result;
}
template <size_t Size>
std::string ToxId2HR (const std::array<uint8_t, Size>& address)
{
return ToxId2HR<Size>(address.data ());
}
#include <string.h>
}
static Tox * toxInit(const std::string& datafile)
{
TOX_ERR_NEW tox_error;
Tox* retval;
struct Tox_Options options;
tox_options_default(&options);
try {
const auto dataFileName = datafile.c_str();
struct linux::stat sb;
if ((stat(dataFileName, &sb) == -1))
throw config::option_error("No such file");
if ((sb.st_mode & S_IFMT) != S_IFREG)
throw config::option_error("Not a file");
const size_t filesize = sb.st_size;
const auto toxData = std::make_unique<uint8_t[]>(filesize);
const int toxfd = linux::open(dataFileName, O_RDONLY);
int result = linux::read(toxfd, toxData.get(), filesize);
if (result < 0)
throw config::option_error("Error reading file");
result = linux::close(toxfd);
if (result < 0)
throw config::option_error("Error closing file");
if (result > 0)
throw config::option_error("Tox data is encrypted");
options.savedata_data = toxData.get();
options.savedata_length = filesize;
options.savedata_type = TOX_SAVEDATA_TYPE_TOX_SAVE;
retval = tox_new(&options, &tox_error);
} catch (config::option_error e) {
std::cerr << "[DEBUG] Can't open tox data: " << e.what() << std::endl;
options.savedata_data = nullptr;
options.savedata_length = 0;
retval = tox_new(&options, &tox_error);
}
switch (tox_error) {
case TOX_ERR_NEW_OK:
std::cerr << "[DEBUG] toxdata successfully loaded" << std::endl;
break;
case TOX_ERR_NEW_LOAD_BAD_FORMAT:
std::cerr << "[DEBUG] toxdata file is damaged" << std::endl;
break;
default:
std::cerr << "[DEBUG] tox_new error: " << tox_error << std::endl;
}
return retval;
}
ToxChannel::ToxChannel(Hub::Hub* hub, const std::string& config) :
channeling::Channel(hub, config),
_tox(toxInit(std::string(_config["datafile"]))), /** TODO: make options handling */
wasConnected(false)
{}
std::future<void> ToxChannel::activate() {
return std::async(std::launch::async, [this]() {
if (_active)
return;
_pipeRunning = true;
toxStart();
_thread = std::make_unique<std::thread>(std::thread(&ToxChannel::pollThread, this));
_active = true;
});
}
void ToxChannel::incoming(const messaging::message_ptr&& msg) {
if (msg->type() == messaging::MessageType::Text) {
const auto textmsg = messaging::TextMessage::fromMessage(msg);
std::cerr << "[DEBUG] #tox " << _name << " " << textmsg->data() << std::endl;
static uint8_t msg[TOX_MAX_MESSAGE_LENGTH];
const auto len = snprintf(reinterpret_cast<char *>(msg), TOX_MAX_MESSAGE_LENGTH,
"[%s]: %s",
textmsg->user()->name().c_str(), textmsg->data().c_str());
tox_group_message_send(_tox, 0, msg, len);
}
}
void ToxChannel::pollThread() {
std::cerr << "[DEBUG] Starting tox thread" << std::endl;
while (_pipeRunning) {
tox_iterate(_tox);
auto wait = tox_iteration_interval(_tox);
std::this_thread::sleep_for( std::chrono::milliseconds (wait));
}
}
ToxChannel::~ToxChannel() {
if (_thread) {
_pipeRunning = false;
_thread->join();
}
try {
const auto dataFileName = std::string(_config["datafile"]).c_str();
const size_t filesize = tox_get_savedata_size(_tox);
const auto toxData = std::make_unique<uint8_t[]>(filesize);
tox_get_savedata(_tox, toxData.get());
const int toxfd = linux::open(dataFileName, O_WRONLY | O_CREAT, 0644);
int result = linux::write(toxfd, toxData.get(), filesize);
if (result < 0)
throw config::option_error("Error writing file");
std::cerr << "[DEBUG] #tox " << _name << " Successfully saved " << result << " bytes of tox data" << std::endl;
result = linux::close(toxfd);
if (result < 0)
throw config::option_error("Error closing file");
} catch (config::option_error e) {
std::cerr << "[DEBUG] Can't save tox data: " << e.what() << std::endl;
}
tox_kill(_tox);
}
void ToxChannel::friendRequestCallback(Tox* tox, const uint8_t* public_key, const uint8_t* data, size_t length, void* userdata) {
TOX_ERR_FRIEND_ADD friend_error;
const auto channel = static_cast<ToxChannel *>(userdata);
const auto friendNum = tox_friend_add_norequest(tox, public_key, &friend_error); /** TODO: check friend_error */
std::cerr << "[DEBUG] tox id with data" << data << " of " << length << " bytes " << util::ToxId2HR<TOX_ADDRESS_SIZE>(public_key) << " wants to be your friend. Added with #" << friendNum << std::endl;
}
void ToxChannel::messageCallback(Tox* tox, uint32_t friendnumber, TOX_MESSAGE_TYPE type, const uint8_t* message, size_t length, void* userdata) {
const auto channel = static_cast<ToxChannel *>(userdata);
const auto buffer = std::make_unique<char *>(new char[length + 1]);
snprintf(*buffer, length + 1, "%s", message);
switch (type) {
case TOX_MESSAGE_TYPE_NORMAL:
std::cerr << "[DEBUG] Message from friend #" << friendnumber << "> " << *buffer << std::endl;
if (util::strncmp(cmd_invite, *buffer, length) == 0)
tox_invite_friend(tox, friendnumber, 0);
break;
case TOX_MESSAGE_TYPE_ACTION:
std::cerr << "[DEBUG] Action from friend #" << friendnumber << "> " << *buffer << std::endl;
break;
default:
std::cerr << "[DEBUG] Unknown message type from " << friendnumber << "> " << *buffer << std::endl;
}
}
void ToxChannel::groupMessageCallback(Tox* tox, int32_t groupnumber, int32_t peernumber, const uint8_t* message, uint16_t length, void* userdata) {
const auto channel = static_cast<ToxChannel *>(userdata);
const auto nameBuffer = std::make_unique<uint8_t *>(new uint8_t[TOX_MAX_NAME_LENGTH]);
const auto nameLen = tox_group_peername(tox, groupnumber, peernumber, *nameBuffer);
const auto name = std::make_unique<char *>(new char[nameLen + 2]);
snprintf(*name, nameLen + 1, "%s", *nameBuffer);
const auto msg = std::make_unique<char *>(new char[length + 2]);
snprintf(*msg, length + 1, "%s", message);
if (std::string(*name) != std::string(channel->_config.get("nickname", defaultBotName))) {
const auto newMessage = std::make_shared<const messaging::TextMessage>(channel->_id,
std::make_shared<const messaging::User>(messaging::User(*name)),
*msg);
std::cerr << "[DEBUG] tox Group msg " << newMessage->user()->name() << "> " << newMessage->data() << std::endl;
channel->_hub->newMessage(std::move(newMessage));
}
}
const messaging::message_ptr ToxChannel::parse(const char* line) const
{
const std::string s(line);
const auto name = s.substr(0, s.find(":"));
const auto text = s.substr(s.find(":"), s.length());
const auto msg = std::make_shared<const messaging::TextMessage>(_id,
std::make_shared<const messaging::User>(messaging::User(name.c_str())),
text.c_str());
return msg;
}
int ToxChannel::toxStart() {
TOX_ERR_SET_INFO result;
//std::unique_ptr<uint8_t[]> pubKey(new uint8_t[TOX_CLIENT_ID_SIZE]);
tox_callback_friend_request(_tox, friendRequestCallback, this);
tox_callback_friend_message(_tox, messageCallback, this);
tox_callback_group_message(_tox, groupMessageCallback, this);
const std::string nick = _config.get("nickname", defaultBotName);
const uint8_t* nickData = reinterpret_cast<const uint8_t *>(nick.c_str());
tox_self_set_name(_tox, nickData, nick.length(), &result);
if (result)
throw channeling::activate_error(ERR_TOX_INIT + "(tox_set_name)");
const std::string statusMsg = _config.get("status_message", defaultStatusMessage);
const uint8_t* statusData = reinterpret_cast<const uint8_t *>(statusMsg.c_str());
tox_self_set_status_message(_tox, statusData, statusMsg.length(), &result);
if (result)
throw channeling::activate_error(ERR_TOX_INIT + "(tox_set_status_message)");
tox_self_set_status(_tox, defaultBotStatus);
if (tox_self_get_connection_status(_tox) == TOX_CONNECTION_NONE) {
TOX_ERR_BOOTSTRAP bootstrap_result;
tox_bootstrap(_tox, defaultBootstrapAddress, defaultBootstrapPort, reinterpret_cast<const uint8_t *>(util::hex2bin(defaultBootstrapKey).c_str()), &bootstrap_result);
if (bootstrap_result)
throw channeling::activate_error(ERR_TOX_INIT + ": Can't decode bootstrapping ip");
}
std::cerr << "[DEBUG] Bootstrapping" << std::endl;
/* TODO: Make timeout exception handling */
while (!wasConnected) {
TOX_CONNECTION status;
tox_iterate(_tox);
auto wait = tox_iteration_interval(_tox);
if (!wasConnected && (TOX_CONNECTION_NONE != tox_self_get_connection_status(_tox))) {
std::array<uint8_t, TOX_ADDRESS_SIZE> address;
tox_self_get_address (_tox, address.data ());
std::cerr << "[DEBUG] Tox is connected with id " << util::ToxId2HR (address) << std::endl
;
wasConnected = true;
}
std::this_thread::sleep_for( std::chrono::milliseconds (wait));
}
tox_add_groupchat (_tox);
return 0;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Distributed under the terms of the BSD license (see the LICENSE
// file for the exact terms).
// Email: hermes1d@googlegroups.com, home page: http://hpfem.org/
#include "transforms.h"
#define N_chebyshev (3+2*(MAX_P-1))
double chebyshev_points[N_chebyshev];
double chebyshev_matrix[N_chebyshev][N_chebyshev];
double transformation_matrix[N_chebyshev][MAX_P+1];
int transformation_matrix_initialized=0;
void fill_chebyshev_points()
{
for (int i=0; i < N_chebyshev; i++)
chebyshev_points[i] = cos(i*M_PI/(N_chebyshev-1));
}
// transform values from (-1, 0) to (-1, 1)
#define map_left(x) (2*x+1)
// transform values from (0, 1) to (-1, 1)
#define map_right(x) (2*x-1)
double phi(int i, double x)
{
if (x < 0) {
if (i == 0)
return lobatto_fn_tab_1d[0](map_left(x));
else if (i % 2 == 0)
return 0;
else
return lobatto_fn_tab_1d[(i+1)/2](map_left(x));
} else {
if (i == 0)
return 0;
else if (i == 1)
return lobatto_fn_tab_1d[0](map_left(x));
else if (i % 2 == 1)
return 0;
else
return lobatto_fn_tab_1d[i/2](map_left(x));
}
}
void fill_chebyshev_matrix()
{
for (int i=0; i < N_chebyshev; i++)
for (int j=0; j < N_chebyshev; j++)
chebyshev_matrix[i][j] = phi(i, chebyshev_points[j]);
}
void fill_transformation_matrix()
{
if (transformation_matrix_initialized)
return;
fill_chebyshev_matrix();
for (int i=0; i < MAX_P; i++) {
Matrix *_mat = new DenseMatrix(N_chebyshev);
_mat->zero();
for (int _i=0; _i < N_chebyshev; _i++)
for (int _j=0; _j < N_chebyshev; _j++)
_mat->add(_i, _j, chebyshev_matrix[_i][_j]);
double f[N_chebyshev];
for (int j=0; j < N_chebyshev; j++)
f[j] = lobatto_fn_tab_1d[i](chebyshev_points[j]);
solve_linear_system(_mat, f);
for (int j=0; j < N_chebyshev; j++)
transformation_matrix[j][i] = f[j];
}
transformation_matrix_initialized = 1;
}
void transform_element(int comp, double *y_prev, double *y_prev_ref, Element
*e, Element *e_ref_left, Element *e_ref_right)
{
double y_prev_loc[MAX_P+1];
double y_prev_loc_trans[N_chebyshev+1];
for (int i=0; i < e->p + 1; i++)
y_prev_loc[i] = y_prev[e->dof[comp][i]];
fill_transformation_matrix();
for (int i=0; i < 3 + 2*(e->p - 1); i++) {
y_prev_loc_trans[i] = 0.;
for (int j=0; j < e->p + 1; j++)
y_prev_loc_trans[i] += transformation_matrix[i][j] * y_prev_loc[j];
}
}
<commit_msg>transform updated<commit_after>// Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Distributed under the terms of the BSD license (see the LICENSE
// file for the exact terms).
// Email: hermes1d@googlegroups.com, home page: http://hpfem.org/
#include "transforms.h"
#define N_chebyshev (3+2*(MAX_P-1))
double chebyshev_points[N_chebyshev];
double chebyshev_matrix[N_chebyshev][N_chebyshev];
double transformation_matrix[N_chebyshev][MAX_P+1];
int transformation_matrix_initialized=0;
void fill_chebyshev_points()
{
for (int i=0; i < N_chebyshev; i++)
chebyshev_points[i] = cos(i*M_PI/(N_chebyshev-1));
}
// transform values from (-1, 0) to (-1, 1)
#define map_left(x) (2*x+1)
// transform values from (0, 1) to (-1, 1)
#define map_right(x) (2*x-1)
double phi(int i, double x)
{
if (x < 0) {
if (i == 0)
return lobatto_fn_tab_1d[0](map_left(x));
else if (i % 2 == 0)
return 0;
else
return lobatto_fn_tab_1d[(i+1)/2](map_left(x));
} else {
if (i == 0)
return 0;
else if (i == 1)
return lobatto_fn_tab_1d[0](map_left(x));
else if (i % 2 == 1)
return 0;
else
return lobatto_fn_tab_1d[i/2](map_left(x));
}
}
void fill_chebyshev_matrix()
{
for (int i=0; i < N_chebyshev; i++)
for (int j=0; j < N_chebyshev; j++)
chebyshev_matrix[i][j] = phi(i, chebyshev_points[j]);
}
void fill_transformation_matrix()
{
if (transformation_matrix_initialized)
return;
fill_chebyshev_matrix();
for (int i=0; i < MAX_P; i++) {
Matrix *_mat = new DenseMatrix(N_chebyshev);
_mat->zero();
for (int _i=0; _i < N_chebyshev; _i++)
for (int _j=0; _j < N_chebyshev; _j++)
_mat->add(_i, _j, chebyshev_matrix[_i][_j]);
double f[N_chebyshev];
for (int j=0; j < N_chebyshev; j++)
f[j] = lobatto_fn_tab_1d[i](chebyshev_points[j]);
solve_linear_system(_mat, f);
for (int j=0; j < N_chebyshev; j++)
transformation_matrix[j][i] = f[j];
}
transformation_matrix_initialized = 1;
}
void transform_element(int comp, double *y_prev, double *y_prev_ref, Element
*e, Element *e_ref_left, Element *e_ref_right, Mesh *mesh, Mesh
*mesh_ref)
{
double y_prev_loc[MAX_P+1];
double y_prev_loc_trans[N_chebyshev+1];
if (e->dof[comp][0] == -1)
y_prev_loc[0] = mesh->bc_left_dir_values[comp];
else
y_prev_loc[0] = y_prev[e->dof[comp][0]];
if (e->dof[comp][1] == -1)
y_prev_loc[1] = mesh->bc_right_dir_values[comp];
else
y_prev_loc[1] = y_prev[e->dof[comp][1]];
for (int i=2; i < e->p + 1; i++)
y_prev_loc[i] = y_prev[e->dof[comp][i]];
fill_transformation_matrix();
for (int i=0; i < 3 + 2*(e->p - 1); i++) {
y_prev_loc_trans[i] = 0.;
for (int j=0; j < e->p + 1; j++)
y_prev_loc_trans[i] += transformation_matrix[i][j] * y_prev_loc[j];
}
// copying computed coefficients into the elements e_ref_left and
// e_ref_right
if (e->dof[comp][0] != -1)
y_prev_ref[e_ref_left->dof[comp][0]] = y_prev_loc_trans[0];
y_prev_ref[e_ref_left->dof[comp][1]] = y_prev_loc_trans[1];
y_prev_ref[e_ref_right->dof[comp][0]] = y_prev_loc_trans[1];
if (e->dof[comp][1] != -1)
y_prev_ref[e_ref_right->dof[comp][1]] = y_prev_loc_trans[2];
if (e_ref_left->p != e_ref_right->p)
error("internal error in transform_element: the left and right elements
must have the same order.");
int counter = 0;
for (int p=2; p < e_ref_left->p + 1; p++) {
y_prev_ref[e_ref_left->dof[comp][p]] = y_prev_loc_trans[3+counter];
counter++;
y_prev_ref[e_ref_right->dof[comp][p]] = y_prev_loc_trans[3+counter];
counter++;
}
}
<|endoftext|> |
<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ===========================================================================
// File: perfmap.cpp
//
#include "common.h"
#if defined(FEATURE_PERFMAP) && !defined(DACCESS_COMPILE)
#include "perfmap.h"
#include "pal.h"
PerfMap * PerfMap::s_Current = NULL;
// Initialize the map for the process - called from EEStartupHelper.
void PerfMap::Initialize()
{
LIMITED_METHOD_CONTRACT;
// Only enable the map if requested.
if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapEnabled))
{
// Get the current process id.
int currentPid = GetCurrentProcessId();
// Create the map.
s_Current = new PerfMap(currentPid);
}
}
// Destroy the map for the process - called from EEShutdownHelper.
void PerfMap::Destroy()
{
LIMITED_METHOD_CONTRACT;
if (s_Current != NULL)
{
delete s_Current;
s_Current = NULL;
}
}
// Construct a new map for the process.
PerfMap::PerfMap(int pid)
{
LIMITED_METHOD_CONTRACT;
// Initialize with no failures.
m_ErrorEncountered = false;
// Build the path to the map file on disk.
WCHAR tempPath[MAX_LONGPATH+1];
if(!GetTempPathW(MAX_LONGPATH, tempPath))
{
return;
}
SString path;
path.Printf("%Sperf-%d.map", &tempPath, pid);
// Open the map file for writing.
OpenFile(path);
}
// Construct a new map without a specified file name.
// Used for offline creation of NGEN map files.
PerfMap::PerfMap()
{
LIMITED_METHOD_CONTRACT;
}
// Clean-up resources.
PerfMap::~PerfMap()
{
LIMITED_METHOD_CONTRACT;
delete m_FileStream;
m_FileStream = NULL;
}
// Open the specified destination map file.
void PerfMap::OpenFile(SString& path)
{
STANDARD_VM_CONTRACT;
// Open the file stream.
m_FileStream = new (nothrow) CFileStream();
if(m_FileStream != NULL)
{
HRESULT hr = m_FileStream->OpenForWrite(path.GetUnicode());
if(FAILED(hr))
{
delete m_FileStream;
m_FileStream = NULL;
}
}
}
// Write a line to the map file.
void PerfMap::WriteLine(SString& line)
{
STANDARD_VM_CONTRACT;
EX_TRY
{
// Write the line.
// The PAL already takes a lock when writing, so we don't need to do so here.
StackScratchBuffer scratch;
const char * strLine = line.GetANSI(scratch);
ULONG inCount = line.GetCount();
ULONG outCount;
m_FileStream->Write(strLine, inCount, &outCount);
if (inCount != outCount)
{
// This will cause us to stop writing to the file.
// The file will still remain open until shutdown so that we don't have to take a lock at this level when we touch the file stream.
m_ErrorEncountered = true;
}
}
EX_CATCH{} EX_END_CATCH(SwallowAllExceptions);
}
// Log a method to the map.
void PerfMap::LogMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize)
{
CONTRACTL{
THROWS;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
PRECONDITION(pMethod != NULL);
PRECONDITION(pCode != NULL);
PRECONDITION(codeSize > 0);
} CONTRACTL_END;
if (m_FileStream == NULL || m_ErrorEncountered)
{
// A failure occurred, do not log.
return;
}
// Logging failures should not cause any exceptions to flow upstream.
EX_TRY
{
// Get the full method signature.
SString fullMethodSignature;
pMethod->GetFullMethodInfo(fullMethodSignature);
// Build the map file line.
StackScratchBuffer scratch;
SString line;
line.Printf("%p %x %s\n", pCode, codeSize, fullMethodSignature.GetANSI(scratch));
// Write the line.
WriteLine(line);
}
EX_CATCH{} EX_END_CATCH(SwallowAllExceptions);
}
// Log a native image to the map.
void PerfMap::LogNativeImage(PEFile * pFile)
{
CONTRACTL{
THROWS;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
PRECONDITION(pFile != NULL);
} CONTRACTL_END;
if (m_FileStream == NULL || m_ErrorEncountered)
{
// A failure occurred, do not log.
return;
}
// Logging failures should not cause any exceptions to flow upstream.
EX_TRY
{
// Get the native image name.
LPCUTF8 lpcSimpleName = pFile->GetSimpleName();
// Get the native image signature.
WCHAR wszSignature[39];
GetNativeImageSignature(pFile, wszSignature, lengthof(wszSignature));
SString strNativeImageSymbol;
strNativeImageSymbol.Printf("%s.ni.%S", lpcSimpleName, wszSignature);
// Get the base addess of the native image.
SIZE_T baseAddress = (SIZE_T)pFile->GetLoaded()->GetBase();
// Get the image size
COUNT_T imageSize = pFile->GetLoaded()->GetVirtualSize();
// Log baseAddress imageSize strNativeImageSymbol
StackScratchBuffer scratch;
SString line;
line.Printf("%p %x %s\n", baseAddress, imageSize, strNativeImageSymbol.GetANSI(scratch));
// Write the line.
WriteLine(line);
}
EX_CATCH{} EX_END_CATCH(SwallowAllExceptions);
}
// Log a native image load to the map.
void PerfMap::LogNativeImageLoad(PEFile * pFile)
{
STANDARD_VM_CONTRACT;
if (s_Current != NULL)
{
s_Current->LogNativeImage(pFile);
}
}
// Log a method to the map.
void PerfMap::LogJITCompiledMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize)
{
LIMITED_METHOD_CONTRACT;
if (s_Current != NULL)
{
s_Current->LogMethod(pMethod, pCode, codeSize);
}
}
void PerfMap::GetNativeImageSignature(PEFile * pFile, WCHAR * pwszSig, unsigned int nSigSize)
{
CONTRACTL{
PRECONDITION(pFile != NULL);
PRECONDITION(pFile->HasNativeImage());
PRECONDITION(pwszSig != NULL);
PRECONDITION(nSigSize >= 39);
} CONTRACTL_END;
PEImageHolder pNativeImage(pFile->GetNativeImageWithRef());
CORCOMPILE_VERSION_INFO * pVersionInfo = pNativeImage->GetLoadedLayout()->GetNativeVersionInfo();
_ASSERTE(pVersionInfo);
CORCOMPILE_NGEN_SIGNATURE * pSignature = &pVersionInfo->signature;
if(!StringFromGUID2(*pSignature, pwszSig, nSigSize))
{
pwszSig[0] = '\0';
}
}
// Create a new native image perf map.
NativeImagePerfMap::NativeImagePerfMap(Assembly * pAssembly, BSTR pDestPath)
: PerfMap()
{
STANDARD_VM_CONTRACT;
// Generate perfmap path.
// Get the assembly simple name.
LPCUTF8 lpcSimpleName = pAssembly->GetSimpleName();
// Get the native image signature (GUID).
// Used to ensure that we match symbols to the correct NGEN image.
WCHAR wszSignature[39];
GetNativeImageSignature(pAssembly->GetManifestFile(), wszSignature, lengthof(wszSignature));
// Build the path to the perfmap file, which consists of <inputpath><imagesimplename>.ni.<signature>.map.
// Example: /tmp/mscorlib.ni.{GUID}.map
SString sDestPerfMapPath;
sDestPerfMapPath.Printf("%S%s.ni.%S.map", pDestPath, lpcSimpleName, wszSignature);
// Open the perf map file.
OpenFile(sDestPerfMapPath);
}
// Log data to the perfmap for the specified module.
void NativeImagePerfMap::LogDataForModule(Module * pModule)
{
STANDARD_VM_CONTRACT;
PEImageLayout * pLoadedLayout = pModule->GetFile()->GetLoaded();
_ASSERTE(pLoadedLayout != NULL);
SIZE_T baseAddr = (SIZE_T)pLoadedLayout->GetBase();
#ifdef FEATURE_READYTORUN_COMPILER
if (pLoadedLayout->HasReadyToRunHeader())
{
ReadyToRunInfo::MethodIterator mi(pModule->GetReadyToRunInfo());
while (mi.Next())
{
MethodDesc *hotDesc = mi.GetMethodDesc();
LogPreCompiledMethod(hotDesc, mi.GetMethodStartAddress(), baseAddr);
}
}
else
#endif // FEATURE_READYTORUN_COMPILER
{
MethodIterator mi((PTR_Module)pModule);
while (mi.Next())
{
MethodDesc *hotDesc = mi.GetMethodDesc();
hotDesc->CheckRestore();
LogPreCompiledMethod(hotDesc, mi.GetMethodStartAddress(), baseAddr);
}
}
}
// Log a pre-compiled method to the perfmap.
void NativeImagePerfMap::LogPreCompiledMethod(MethodDesc * pMethod, PCODE pCode, SIZE_T baseAddr)
{
STANDARD_VM_CONTRACT;
// Get information about the NGEN'd method code.
EECodeInfo codeInfo(pCode);
_ASSERTE(codeInfo.IsValid());
IJitManager::MethodRegionInfo methodRegionInfo;
codeInfo.GetMethodRegionInfo(&methodRegionInfo);
// NGEN can split code between hot and cold sections which are separate in memory.
// Emit an entry for each section if it is used.
if (methodRegionInfo.hotSize > 0)
{
LogMethod(pMethod, (PCODE)methodRegionInfo.hotStartAddress - baseAddr, methodRegionInfo.hotSize);
}
if (methodRegionInfo.coldSize > 0)
{
LogMethod(pMethod, (PCODE)methodRegionInfo.coldStartAddress - baseAddr, methodRegionInfo.coldSize);
}
}
#endif // FEATURE_PERFMAP && !DACCESS_COMPILE
<commit_msg>Fix PerfMap::GetNativeImageSignature to work for ready to run images.<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ===========================================================================
// File: perfmap.cpp
//
#include "common.h"
#if defined(FEATURE_PERFMAP) && !defined(DACCESS_COMPILE)
#include "perfmap.h"
#include "pal.h"
PerfMap * PerfMap::s_Current = NULL;
// Initialize the map for the process - called from EEStartupHelper.
void PerfMap::Initialize()
{
LIMITED_METHOD_CONTRACT;
// Only enable the map if requested.
if (CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_PerfMapEnabled))
{
// Get the current process id.
int currentPid = GetCurrentProcessId();
// Create the map.
s_Current = new PerfMap(currentPid);
}
}
// Destroy the map for the process - called from EEShutdownHelper.
void PerfMap::Destroy()
{
LIMITED_METHOD_CONTRACT;
if (s_Current != NULL)
{
delete s_Current;
s_Current = NULL;
}
}
// Construct a new map for the process.
PerfMap::PerfMap(int pid)
{
LIMITED_METHOD_CONTRACT;
// Initialize with no failures.
m_ErrorEncountered = false;
// Build the path to the map file on disk.
WCHAR tempPath[MAX_LONGPATH+1];
if(!GetTempPathW(MAX_LONGPATH, tempPath))
{
return;
}
SString path;
path.Printf("%Sperf-%d.map", &tempPath, pid);
// Open the map file for writing.
OpenFile(path);
}
// Construct a new map without a specified file name.
// Used for offline creation of NGEN map files.
PerfMap::PerfMap()
{
LIMITED_METHOD_CONTRACT;
}
// Clean-up resources.
PerfMap::~PerfMap()
{
LIMITED_METHOD_CONTRACT;
delete m_FileStream;
m_FileStream = NULL;
}
// Open the specified destination map file.
void PerfMap::OpenFile(SString& path)
{
STANDARD_VM_CONTRACT;
// Open the file stream.
m_FileStream = new (nothrow) CFileStream();
if(m_FileStream != NULL)
{
HRESULT hr = m_FileStream->OpenForWrite(path.GetUnicode());
if(FAILED(hr))
{
delete m_FileStream;
m_FileStream = NULL;
}
}
}
// Write a line to the map file.
void PerfMap::WriteLine(SString& line)
{
STANDARD_VM_CONTRACT;
EX_TRY
{
// Write the line.
// The PAL already takes a lock when writing, so we don't need to do so here.
StackScratchBuffer scratch;
const char * strLine = line.GetANSI(scratch);
ULONG inCount = line.GetCount();
ULONG outCount;
m_FileStream->Write(strLine, inCount, &outCount);
if (inCount != outCount)
{
// This will cause us to stop writing to the file.
// The file will still remain open until shutdown so that we don't have to take a lock at this level when we touch the file stream.
m_ErrorEncountered = true;
}
}
EX_CATCH{} EX_END_CATCH(SwallowAllExceptions);
}
// Log a method to the map.
void PerfMap::LogMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize)
{
CONTRACTL{
THROWS;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
PRECONDITION(pMethod != NULL);
PRECONDITION(pCode != NULL);
PRECONDITION(codeSize > 0);
} CONTRACTL_END;
if (m_FileStream == NULL || m_ErrorEncountered)
{
// A failure occurred, do not log.
return;
}
// Logging failures should not cause any exceptions to flow upstream.
EX_TRY
{
// Get the full method signature.
SString fullMethodSignature;
pMethod->GetFullMethodInfo(fullMethodSignature);
// Build the map file line.
StackScratchBuffer scratch;
SString line;
line.Printf("%p %x %s\n", pCode, codeSize, fullMethodSignature.GetANSI(scratch));
// Write the line.
WriteLine(line);
}
EX_CATCH{} EX_END_CATCH(SwallowAllExceptions);
}
// Log a native image to the map.
void PerfMap::LogNativeImage(PEFile * pFile)
{
CONTRACTL{
THROWS;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
PRECONDITION(pFile != NULL);
} CONTRACTL_END;
if (m_FileStream == NULL || m_ErrorEncountered)
{
// A failure occurred, do not log.
return;
}
// Logging failures should not cause any exceptions to flow upstream.
EX_TRY
{
// Get the native image name.
LPCUTF8 lpcSimpleName = pFile->GetSimpleName();
// Get the native image signature.
WCHAR wszSignature[39];
GetNativeImageSignature(pFile, wszSignature, lengthof(wszSignature));
SString strNativeImageSymbol;
strNativeImageSymbol.Printf("%s.ni.%S", lpcSimpleName, wszSignature);
// Get the base addess of the native image.
SIZE_T baseAddress = (SIZE_T)pFile->GetLoaded()->GetBase();
// Get the image size
COUNT_T imageSize = pFile->GetLoaded()->GetVirtualSize();
// Log baseAddress imageSize strNativeImageSymbol
StackScratchBuffer scratch;
SString line;
line.Printf("%p %x %s\n", baseAddress, imageSize, strNativeImageSymbol.GetANSI(scratch));
// Write the line.
WriteLine(line);
}
EX_CATCH{} EX_END_CATCH(SwallowAllExceptions);
}
// Log a native image load to the map.
void PerfMap::LogNativeImageLoad(PEFile * pFile)
{
STANDARD_VM_CONTRACT;
if (s_Current != NULL)
{
s_Current->LogNativeImage(pFile);
}
}
// Log a method to the map.
void PerfMap::LogJITCompiledMethod(MethodDesc * pMethod, PCODE pCode, size_t codeSize)
{
LIMITED_METHOD_CONTRACT;
if (s_Current != NULL)
{
s_Current->LogMethod(pMethod, pCode, codeSize);
}
}
void PerfMap::GetNativeImageSignature(PEFile * pFile, WCHAR * pwszSig, unsigned int nSigSize)
{
CONTRACTL{
PRECONDITION(pFile != NULL);
PRECONDITION(pwszSig != NULL);
PRECONDITION(nSigSize >= 39);
} CONTRACTL_END;
// We use the MVID as the signature, since ready to run images
// don't have a native image signature.
GUID mvid;
pFile->GetMVID(&mvid);
if(!StringFromGUID2(mvid, pwszSig, nSigSize))
{
pwszSig[0] = '\0';
}
}
// Create a new native image perf map.
NativeImagePerfMap::NativeImagePerfMap(Assembly * pAssembly, BSTR pDestPath)
: PerfMap()
{
STANDARD_VM_CONTRACT;
// Generate perfmap path.
// Get the assembly simple name.
LPCUTF8 lpcSimpleName = pAssembly->GetSimpleName();
// Get the native image signature (GUID).
// Used to ensure that we match symbols to the correct NGEN image.
WCHAR wszSignature[39];
GetNativeImageSignature(pAssembly->GetManifestFile(), wszSignature, lengthof(wszSignature));
// Build the path to the perfmap file, which consists of <inputpath><imagesimplename>.ni.<signature>.map.
// Example: /tmp/mscorlib.ni.{GUID}.map
SString sDestPerfMapPath;
sDestPerfMapPath.Printf("%S%s.ni.%S.map", pDestPath, lpcSimpleName, wszSignature);
// Open the perf map file.
OpenFile(sDestPerfMapPath);
}
// Log data to the perfmap for the specified module.
void NativeImagePerfMap::LogDataForModule(Module * pModule)
{
STANDARD_VM_CONTRACT;
PEImageLayout * pLoadedLayout = pModule->GetFile()->GetLoaded();
_ASSERTE(pLoadedLayout != NULL);
SIZE_T baseAddr = (SIZE_T)pLoadedLayout->GetBase();
#ifdef FEATURE_READYTORUN_COMPILER
if (pLoadedLayout->HasReadyToRunHeader())
{
ReadyToRunInfo::MethodIterator mi(pModule->GetReadyToRunInfo());
while (mi.Next())
{
MethodDesc *hotDesc = mi.GetMethodDesc();
LogPreCompiledMethod(hotDesc, mi.GetMethodStartAddress(), baseAddr);
}
}
else
#endif // FEATURE_READYTORUN_COMPILER
{
MethodIterator mi((PTR_Module)pModule);
while (mi.Next())
{
MethodDesc *hotDesc = mi.GetMethodDesc();
hotDesc->CheckRestore();
LogPreCompiledMethod(hotDesc, mi.GetMethodStartAddress(), baseAddr);
}
}
}
// Log a pre-compiled method to the perfmap.
void NativeImagePerfMap::LogPreCompiledMethod(MethodDesc * pMethod, PCODE pCode, SIZE_T baseAddr)
{
STANDARD_VM_CONTRACT;
// Get information about the NGEN'd method code.
EECodeInfo codeInfo(pCode);
_ASSERTE(codeInfo.IsValid());
IJitManager::MethodRegionInfo methodRegionInfo;
codeInfo.GetMethodRegionInfo(&methodRegionInfo);
// NGEN can split code between hot and cold sections which are separate in memory.
// Emit an entry for each section if it is used.
if (methodRegionInfo.hotSize > 0)
{
LogMethod(pMethod, (PCODE)methodRegionInfo.hotStartAddress - baseAddr, methodRegionInfo.hotSize);
}
if (methodRegionInfo.coldSize > 0)
{
LogMethod(pMethod, (PCODE)methodRegionInfo.coldStartAddress - baseAddr, methodRegionInfo.coldSize);
}
}
#endif // FEATURE_PERFMAP && !DACCESS_COMPILE
<|endoftext|> |
<commit_before>#include <kdebug.h>
#include <QCryptographicHash>
#include <QTextCodec>
#include <QByteArray>
#include "mradata.h"
#include "mraconnection.h"
#include "mracontactlist.h"
#include "mracontactinfo.h"
#include "mraprotocolv123.h"
MRAProtocolV123::MRAProtocolV123(QObject *parent) :
MRAProtocol(parent)
{
}
MRAProtocolV123::~MRAProtocolV123() {
}
bool MRAProtocolV123::makeConnection(const QString &login, const QString &password)
{
if (!MRAProtocol::makeConnection(login, password)) {
return false;
}
return true;
}
void MRAProtocolV123::sendLogin(const QString &login, const QString &password)
{
sendUnknownBeforeLogin();
MRAData data;
// proto v1.23
data.addString(login);
data.addBinaryString(QCryptographicHash::hash(password.toAscii(), QCryptographicHash::Md5) );
data.addInt32(0x00000bff);
data.addString("client=\"magent\" version=\"5.10\" build=\"5282\"");
data.addString("ru");
data.addInt32(0x10);
data.addInt32(0x01);
data.addString("geo-list");
data.addString("MRA 5.10 (build 5282);");
connection()->sendMsg(MRIM_CS_LOGIN3, &data);
}
void MRAProtocolV123::readLoginAck(MRAData & data) {
Q_UNUSED(data);
setStatus(ONLINE);
emit connected();
}
void MRAProtocolV123::sendUnknownBeforeLogin() {
MRAData data;
data.addInt32(0x03);
data.addInt32(0x00);
data.addInt32(0x00);
data.addInt32(0x01);
data.addInt32(0x00);
data.addInt32(0x02);
data.addInt32(0x00);
connection()->sendMsg(MRIM_CS_UNKNOWN2, &data);
}
void MRAProtocolV123::readMessage(MRAData & data) {
// UL msg_id
// UL flags
// LPS from
// LPS message
// LPS rtf-formatted message (>=1.1)
int msg_id = data.getInt32();
int flags = data.getInt32();
QString from = data.getString();
QString text;
if (flags & MESSAGE_FLAG_UNICODE) {
if (flags & MESSAGE_FLAG_AUTHORIZE) {
// QTextCodec *codec = QTextCodec::codecForName("UTF-16LE");
MRAData authMessage( QByteArray::fromBase64(data.getString().toAscii()) );
// text = codec->toUnicode( );
authMessage.getInt32(); // 0x02 // ???
kWarning() << authMessage.getUnicodeString();// WTF? sender?
text = authMessage.getUnicodeString();
} else {
text = data.getUnicodeString();
}
} else {
text = data.getString();
}
if ( (flags & MESSAGE_FLAG_RTF) && !data.eof() ) {
QString rtf = data.getString(); // ignore
Q_UNUSED(rtf);
}
if ( (flags & MESSAGE_FLAG_NOTIFY) != 0 ) {
emit typingAMessage( from );
} else if ( (flags & MESSAGE_FLAG_AUTHORIZE) != 0) {
emit authorizeRequestReceived(from, text);
} else {
if ( (flags & MESSAGE_FLAG_CHAT) && !data.eof() ) {
// 0x3d 0b00111101 -- old client (non unicode message)
// 0x3b 0b00111011 -- normal chat message
// 0x2d 0b00101101 -- ???
// 0x53 0b01010011 -- chat list membets
// 0x120 0b100100000 -- updated (?) members list
int messageType = data.getInt32(); // 0x3b,0x3d ??
int i2 = data.getInt32(); // 0x00 ??
const int CHAT_TEXT_MESSAGE = 0x0028;
if ( (messageType & CHAT_TEXT_MESSAGE) == CHAT_TEXT_MESSAGE ) {
kWarning() << "i1=" << messageType << "from=" <<from;
QString chatTitle = data.getUnicodeString(); // subject
QString chatMember = data.getString(); // sender
text = chatTitle + '(' + chatMember + ')' + '\n' + text;
} else if ( (messageType == 0x53) || (messageType == 0x120) ) {
QString chatTitle = data.getUnicodeString(); // subject
int i3 = data.getInt32();
int numMembers = data.getInt32();
QList<QString> membersList;
for(; numMembers > 0; --numMembers) {
membersList.append( data.getString() );
}
emit chatMembersListReceived(from, chatTitle, membersList);
Q_UNUSED(i2);
Q_UNUSED(i3);
} else {
kWarning() << "unknown messageType =" << messageType;
}
}
if ( not (flags & MESSAGE_FLAG_SYSTEM) ) {
emit messageReceived( from, text );
}
}
if ( (flags & MESSAGE_FLAG_NORECV) == 0 ) {
MRAData ackData;
ackData.addString(from); // LPS ## from ##
ackData.addInt32(msg_id); // UL ## msg_id ##
connection()->sendMsg(MRIM_CS_MESSAGE_RECV, &ackData);
}
}
/*!
\fn MRAMsg::sendMessage()
*/
void MRAProtocolV123::sendText(const QString &to, const QString &text)
{
MRAData data;
unsigned long int flags = MESSAGE_FLAG_NORECV;
data.addInt32(flags);
data.addString(to);
data.addUnicodeString(text);
data.addString(" ");// RTF is not supported yet
connection()->sendMsg(MRIM_CS_MESSAGE, &data);
}
void MRAProtocolV123::loadChatMembersList(const QString &to) {
MRAData data;
unsigned long int flags = MESSAGE_FLAG_RTF;
data.addInt32(flags);
data.addString(to);
data.addString("");
data.addString("");
data.addInt32(0x04); // whatis 4?
data.addInt32(0x01); // whatis 4?
connection()->sendMsg(MRIM_CS_MESSAGE, &data);
/*
ack: flags: 0x00400084 = MESSAGE_FLAG_NORECV | MESSAGE_FLAG_RTF | MESSAGE_FLAG_CHAT
chat int 1: 0x53
chat int 2: 0x02
lps chatTitle
chat int 3: 0x2d
chat int 4: 0x02 (members number?)
lps*number
*/
}
void MRAProtocolV123::setStatus(STATUS status) {
MRAData data;
data.addInt32( statusToInt(status) );
if (status == ONLINE) {
data.addString("STATUS_ONLINE");
data.addUnicodeString(tr("Online")); /// @todo make phrases configurable
} else if (status == AWAY) {
data.addString("STATUS_AWAY");
data.addUnicodeString(tr("Away"));
} else if (status == DONT_DISTRUB) {
data.addString("STATUS_DND");
data.addUnicodeString(tr("Don't distrub"));
} else if (status == CHATTY) {
data.addString("STATUS_CHAT");
data.addUnicodeString(tr("Ready to talk"));
} else {
/// @fixme
data.addString("STATUS_ONLINE");
data.addUnicodeString(tr("Online"));
}
data.addInt32(0x00); // user's client?
data.addInt32(0x00000BFF);
connection()->sendMsg(MRIM_CS_CHANGE_STATUS, &data);
}
void MRAProtocolV123::readUserSataus(MRAData & data) {
// data.dumpData();
int status = data.getInt32();
QString statusTitle = data.getString(); // STATUS_ONLINE
QString str = data.getUnicodeString(); // tr("Online")
int int1 = data.getInt32(); // ???
QString user = data.getString();
int int2 = data.getInt32(); // 0x00000BFF
QString client = data.getString(); // client="magent" version="5.10" build="5309"
kWarning() <<status<< statusTitle << str << int1 << user << int2 << client;
emit userStatusChanged(user, status);
}
void MRAProtocolV123::readAnketaInfo(MRAData & data) {
MRAContactInfo info;
uint status = data.getInt32();
kWarning() << "status=" << status;
uint fields_num = data.getInt32();
uint max_rows = data.getInt32();
uint server_time= data.getInt32();
Q_UNUSED(max_rows); /// @fixme: use this fields
Q_UNUSED(server_time); /// @fixme: use this fields
QVector<QString> vecInfo;
vecInfo.reserve(fields_num);
for( uint i = 0; i < fields_num; ++i ) {
QString field = data.getString();
kWarning() << field;
vecInfo.append( field );
}
for( uint i = 0; i < fields_num; ++i ) {
QString fieldData;
bool isUnicodeAttribute =
vecInfo[i] == "Location" ||
vecInfo[i] == "Nickname" ||
vecInfo[i] == "FirstName" ||
vecInfo[i] == "LastName" ||
vecInfo[i] == "status_title";
if (isUnicodeAttribute) {
fieldData = data.getUnicodeString();
} else {
fieldData = data.getString();
}
info.setParam(vecInfo[i], fieldData);
kWarning() << vecInfo[i] << fieldData;
}
this->emit userInfoLoaded( info.email(), info );
}
/* void MRAProtocolV123::authorizeContact(const QString &contact) {
Q_UNUSED(contact);
} */
void MRAProtocolV123::addToContactList(int flags, int groupId, const QString &address, const QString &nick, const QString &myAddress, const QString &authMessage) {
/*
#define MRIM_CS_ADD_CONTACT 0x1019 // C -> S
// added by negram. since v1.23:
//
// UL flags (group(2) or usual(0)
// UL group id (unused if contact is group)
// LPS contact
// LPS name (unicode)
// LPS unused
// LPS authorization message, 'please, authorize me': base64(unicode(message))
// UL ??? (0x00000001)
*/
MRAData addData;
addData.addInt32(flags);
addData.addInt32(groupId);
addData.addString(address);
addData.addUnicodeString(nick);
addData.addString(""); // unused
MRAData authMessageData;
authMessageData.addInt32(0x02); // ???
authMessageData.addUnicodeString(myAddress);
authMessageData.addUnicodeString(authMessage);
addData.addString( authMessageData.toBase64() );
addData.addInt32( 1 );
connection()->sendMsg(MRIM_CS_ADD_CONTACT, &addData);
}
void MRAProtocolV123::sendAuthorizationRequest(const QString &contact, const QString &myAddress, const QString &message) {
MRAData authData;
unsigned long int authFlags = MESSAGE_FLAG_NORECV | MESSAGE_FLAG_AUTHORIZE | MESSAGE_FLAG_UNICODE;
authData.addInt32(authFlags);
authData.addString(contact);
MRAData authMessage;
authMessage.addInt32(0x02); // ???
authMessage.addUnicodeString(myAddress);
authMessage.addUnicodeString(message);
authData.addString(authMessage.toBase64());
authData.addString("");// RTF is not supported yet
connection()->sendMsg(MRIM_CS_MESSAGE, &authData);
}
void MRAProtocolV123::readUserInfo(MRAData & data)
{
QString str;
QString val;
while (!data.eof()) {
str = data.getString();
if (str == "MRIM.NICKNAME" || str == "connect.xml") {
val = data.getUnicodeString();
} else {
val = data.getString();
}
kWarning() << str << " " << val;
}
}
void MRAProtocolV123::deleteContact(uint id, const QString &contact, const QString &contactName) {
kWarning() << __PRETTY_FUNCTION__;
/*
#define MRIM_CS_MODIFY_CONTACT 0x101B // C -> S
// UL id
// UL flags - same as for MRIM_CS_ADD_CONTACT
// UL group id (unused if contact is group)
// LPS contact
// LPS name
// LPS unused
*/
MRAData data;
data.addInt32( id );
data.addInt32( CONTACT_FLAG_REMOVED | CONTACT_FLAG_UNKNOWN );
data.addInt32( 0 ); // don't care about group
data.addString( contact );
data.addUnicodeString( contactName );
data.addString( QString() );
connection()->sendMsg( MRIM_CS_MODIFY_CONTACT, &data );
}
QVector<QVariant> MRAProtocolV123::readVectorByMask(MRAData & data, const QString &mask)
{
QVector<QVariant> result;
quint32 _int;
QString _string;
QString localMask = mask;
if (localMask.length() > 5) {
// user's mask
localMask[3] = 'S';
localMask[8] = 'S';
localMask[15] = 'S';
} else {
// group's mask
localMask[1] = 'S';
}
for (int k = 0; k < localMask.length(); ++k) {
if (localMask[k] == 'u') {
_int = data.getInt32();
kWarning() << "u=" << _int;
result.push_back(_int);
} else if (localMask[k] == 's') {
_string = data.getString( );
kWarning() << "s=" << _string;
result.push_back(_string);
} else if (localMask[k] == 'S') {
_string = data.getUnicodeString( );
kWarning() << "S=" << _string;
result.push_back(_string);
}
}
kWarning() << "done";
return result;
}
void MRAProtocolV123::fillUserInfo(QVector<QVariant> &protoData, MRAContactListEntry &item) {
item.setFlags( protoData[0].toUInt() );
item.setGroup( protoData[1].toUInt() );
item.setAddress( protoData[2].toString() );
item.setNick( protoData[3].toString() );
item.setServerFlags( protoData[4].toUInt() );
item.setStatus( protoData[5].toUInt() );
}
#include "mraprotocolv123.moc"
<commit_msg>right comparsion order<commit_after>#include <kdebug.h>
#include <QCryptographicHash>
#include <QTextCodec>
#include <QByteArray>
#include "mradata.h"
#include "mraconnection.h"
#include "mracontactlist.h"
#include "mracontactinfo.h"
#include "mraprotocolv123.h"
MRAProtocolV123::MRAProtocolV123(QObject *parent) :
MRAProtocol(parent)
{
}
MRAProtocolV123::~MRAProtocolV123() {
}
bool MRAProtocolV123::makeConnection(const QString &login, const QString &password)
{
if (!MRAProtocol::makeConnection(login, password)) {
return false;
}
return true;
}
void MRAProtocolV123::sendLogin(const QString &login, const QString &password)
{
sendUnknownBeforeLogin();
MRAData data;
// proto v1.23
data.addString(login);
data.addBinaryString(QCryptographicHash::hash(password.toAscii(), QCryptographicHash::Md5) );
data.addInt32(0x00000bff);
data.addString("client=\"magent\" version=\"5.10\" build=\"5282\"");
data.addString("ru");
data.addInt32(0x10);
data.addInt32(0x01);
data.addString("geo-list");
data.addString("MRA 5.10 (build 5282);");
connection()->sendMsg(MRIM_CS_LOGIN3, &data);
}
void MRAProtocolV123::readLoginAck(MRAData & data) {
Q_UNUSED(data);
setStatus(ONLINE);
emit connected();
}
void MRAProtocolV123::sendUnknownBeforeLogin() {
MRAData data;
data.addInt32(0x03);
data.addInt32(0x00);
data.addInt32(0x00);
data.addInt32(0x01);
data.addInt32(0x00);
data.addInt32(0x02);
data.addInt32(0x00);
connection()->sendMsg(MRIM_CS_UNKNOWN2, &data);
}
void MRAProtocolV123::readMessage(MRAData & data) {
// UL msg_id
// UL flags
// LPS from
// LPS message
// LPS rtf-formatted message (>=1.1)
int msg_id = data.getInt32();
int flags = data.getInt32();
QString from = data.getString();
QString text;
if (flags & MESSAGE_FLAG_UNICODE) {
if (flags & MESSAGE_FLAG_AUTHORIZE) {
// QTextCodec *codec = QTextCodec::codecForName("UTF-16LE");
MRAData authMessage( QByteArray::fromBase64(data.getString().toAscii()) );
// text = codec->toUnicode( );
authMessage.getInt32(); // 0x02 // ???
kWarning() << authMessage.getUnicodeString();// WTF? sender?
text = authMessage.getUnicodeString();
} else {
text = data.getUnicodeString();
}
} else {
text = data.getString();
}
if ( (flags & MESSAGE_FLAG_RTF) && !data.eof() ) {
QString rtf = data.getString(); // ignore
Q_UNUSED(rtf);
}
bool isSystemMessage = (flags & MESSAGE_FLAG_SYSTEM) != 0;
if ( (flags & MESSAGE_FLAG_NOTIFY) != 0 ) {
emit typingAMessage( from );
} else if ( (flags & MESSAGE_FLAG_AUTHORIZE) != 0) {
emit authorizeRequestReceived(from, text);
} else {
if ( (flags & MESSAGE_FLAG_CHAT) && !data.eof() ) {
// 0x3d 0b00111101 -- old client (non unicode message)
// 0x3b 0b00111011 -- normal chat message
// 0x2d 0b00101101 -- ???
// 0x35 0b00110101 -- ???
// 0x53 0b01010011 -- chat list membets
// 0x120 0b100100000 -- updated (?) members list
int messageType = data.getInt32(); // 0x3b,0x3d ??
int i2 = data.getInt32(); // 0x00 ??
kWarning() << "messageType =" << messageType;
const int CHAT_TEXT_MESSAGE = 0x0028;
if ( (messageType == 0x53) || (messageType == 0x120) ) {
isSystemMessage = true;
QString chatTitle = data.getUnicodeString(); // subject
int i3 = data.getInt32();
int numMembers = data.getInt32();
QList<QString> membersList;
for(; numMembers > 0; --numMembers) {
membersList.append( data.getString() );
}
emit chatMembersListReceived(from, chatTitle, membersList);
Q_UNUSED(i2);
Q_UNUSED(i3);
} else if ( (messageType & CHAT_TEXT_MESSAGE) ) {
kWarning() << "i1=" << messageType << "from=" <<from;
QString chatTitle = data.getUnicodeString(); // subject
QString chatMember = data.getString(); // sender
text = chatTitle + '(' + chatMember + ')' + '\n' + text;
} else {
kWarning() << "unknown messageType =" << messageType;
}
}
if ( not isSystemMessage ) {
emit messageReceived( from, text );
}
}
if ( (flags & MESSAGE_FLAG_NORECV) == 0 ) {
MRAData ackData;
ackData.addString(from); // LPS ## from ##
ackData.addInt32(msg_id); // UL ## msg_id ##
connection()->sendMsg(MRIM_CS_MESSAGE_RECV, &ackData);
}
}
/*!
\fn MRAMsg::sendMessage()
*/
void MRAProtocolV123::sendText(const QString &to, const QString &text)
{
MRAData data;
unsigned long int flags = MESSAGE_FLAG_NORECV;
data.addInt32(flags);
data.addString(to);
data.addUnicodeString(text);
data.addString(" ");// RTF is not supported yet
connection()->sendMsg(MRIM_CS_MESSAGE, &data);
}
void MRAProtocolV123::loadChatMembersList(const QString &to) {
MRAData data;
unsigned long int flags = MESSAGE_FLAG_RTF;
data.addInt32(flags);
data.addString(to);
data.addString("");
data.addString("");
data.addInt32(0x04); // whatis 4?
data.addInt32(0x01); // whatis 4?
connection()->sendMsg(MRIM_CS_MESSAGE, &data);
/*
ack: flags: 0x00400084 = MESSAGE_FLAG_NORECV | MESSAGE_FLAG_RTF | MESSAGE_FLAG_CHAT
chat int 1: 0x53
chat int 2: 0x02
lps chatTitle
chat int 3: 0x2d
chat int 4: 0x02 (members number?)
lps*number
*/
}
void MRAProtocolV123::setStatus(STATUS status) {
MRAData data;
data.addInt32( statusToInt(status) );
if (status == ONLINE) {
data.addString("STATUS_ONLINE");
data.addUnicodeString(tr("Online")); /// @todo make phrases configurable
} else if (status == AWAY) {
data.addString("STATUS_AWAY");
data.addUnicodeString(tr("Away"));
} else if (status == DONT_DISTRUB) {
data.addString("STATUS_DND");
data.addUnicodeString(tr("Don't distrub"));
} else if (status == CHATTY) {
data.addString("STATUS_CHAT");
data.addUnicodeString(tr("Ready to talk"));
} else {
/// @fixme
data.addString("STATUS_ONLINE");
data.addUnicodeString(tr("Online"));
}
data.addInt32(0x00); // user's client?
data.addInt32(0x00000BFF);
connection()->sendMsg(MRIM_CS_CHANGE_STATUS, &data);
}
void MRAProtocolV123::readUserSataus(MRAData & data) {
// data.dumpData();
int status = data.getInt32();
QString statusTitle = data.getString(); // STATUS_ONLINE
QString str = data.getUnicodeString(); // tr("Online")
int int1 = data.getInt32(); // ???
QString user = data.getString();
int int2 = data.getInt32(); // 0x00000BFF
QString client = data.getString(); // client="magent" version="5.10" build="5309"
kWarning() <<status<< statusTitle << str << int1 << user << int2 << client;
emit userStatusChanged(user, status);
}
void MRAProtocolV123::readAnketaInfo(MRAData & data) {
MRAContactInfo info;
uint status = data.getInt32();
kWarning() << "status=" << status;
uint fields_num = data.getInt32();
uint max_rows = data.getInt32();
uint server_time= data.getInt32();
Q_UNUSED(max_rows); /// @fixme: use this fields
Q_UNUSED(server_time); /// @fixme: use this fields
QVector<QString> vecInfo;
vecInfo.reserve(fields_num);
for( uint i = 0; i < fields_num; ++i ) {
QString field = data.getString();
kWarning() << field;
vecInfo.append( field );
}
for( uint i = 0; i < fields_num; ++i ) {
QString fieldData;
bool isUnicodeAttribute =
vecInfo[i] == "Location" ||
vecInfo[i] == "Nickname" ||
vecInfo[i] == "FirstName" ||
vecInfo[i] == "LastName" ||
vecInfo[i] == "status_title";
if (isUnicodeAttribute) {
fieldData = data.getUnicodeString();
} else {
fieldData = data.getString();
}
info.setParam(vecInfo[i], fieldData);
kWarning() << vecInfo[i] << fieldData;
}
this->emit userInfoLoaded( info.email(), info );
}
/* void MRAProtocolV123::authorizeContact(const QString &contact) {
Q_UNUSED(contact);
} */
void MRAProtocolV123::addToContactList(int flags, int groupId, const QString &address, const QString &nick, const QString &myAddress, const QString &authMessage) {
/*
#define MRIM_CS_ADD_CONTACT 0x1019 // C -> S
// added by negram. since v1.23:
//
// UL flags (group(2) or usual(0)
// UL group id (unused if contact is group)
// LPS contact
// LPS name (unicode)
// LPS unused
// LPS authorization message, 'please, authorize me': base64(unicode(message))
// UL ??? (0x00000001)
*/
MRAData addData;
addData.addInt32(flags);
addData.addInt32(groupId);
addData.addString(address);
addData.addUnicodeString(nick);
addData.addString(""); // unused
MRAData authMessageData;
authMessageData.addInt32(0x02); // ???
authMessageData.addUnicodeString(myAddress);
authMessageData.addUnicodeString(authMessage);
addData.addString( authMessageData.toBase64() );
addData.addInt32( 1 );
connection()->sendMsg(MRIM_CS_ADD_CONTACT, &addData);
}
void MRAProtocolV123::sendAuthorizationRequest(const QString &contact, const QString &myAddress, const QString &message) {
MRAData authData;
unsigned long int authFlags = MESSAGE_FLAG_NORECV | MESSAGE_FLAG_AUTHORIZE | MESSAGE_FLAG_UNICODE;
authData.addInt32(authFlags);
authData.addString(contact);
MRAData authMessage;
authMessage.addInt32(0x02); // ???
authMessage.addUnicodeString(myAddress);
authMessage.addUnicodeString(message);
authData.addString(authMessage.toBase64());
authData.addString("");// RTF is not supported yet
connection()->sendMsg(MRIM_CS_MESSAGE, &authData);
}
void MRAProtocolV123::readUserInfo(MRAData & data)
{
QString str;
QString val;
while (!data.eof()) {
str = data.getString();
if (str == "MRIM.NICKNAME" || str == "connect.xml") {
val = data.getUnicodeString();
} else {
val = data.getString();
}
kWarning() << str << " " << val;
}
}
void MRAProtocolV123::deleteContact(uint id, const QString &contact, const QString &contactName) {
kWarning() << __PRETTY_FUNCTION__;
/*
#define MRIM_CS_MODIFY_CONTACT 0x101B // C -> S
// UL id
// UL flags - same as for MRIM_CS_ADD_CONTACT
// UL group id (unused if contact is group)
// LPS contact
// LPS name
// LPS unused
*/
MRAData data;
data.addInt32( id );
data.addInt32( CONTACT_FLAG_REMOVED | CONTACT_FLAG_UNKNOWN );
data.addInt32( 0 ); // don't care about group
data.addString( contact );
data.addUnicodeString( contactName );
data.addString( QString() );
connection()->sendMsg( MRIM_CS_MODIFY_CONTACT, &data );
}
QVector<QVariant> MRAProtocolV123::readVectorByMask(MRAData & data, const QString &mask)
{
QVector<QVariant> result;
quint32 _int;
QString _string;
QString localMask = mask;
if (localMask.length() > 5) {
// user's mask
localMask[3] = 'S';
localMask[8] = 'S';
localMask[15] = 'S';
} else {
// group's mask
localMask[1] = 'S';
}
for (int k = 0; k < localMask.length(); ++k) {
if (localMask[k] == 'u') {
_int = data.getInt32();
kWarning() << "u=" << _int;
result.push_back(_int);
} else if (localMask[k] == 's') {
_string = data.getString( );
kWarning() << "s=" << _string;
result.push_back(_string);
} else if (localMask[k] == 'S') {
_string = data.getUnicodeString( );
kWarning() << "S=" << _string;
result.push_back(_string);
}
}
kWarning() << "done";
return result;
}
void MRAProtocolV123::fillUserInfo(QVector<QVariant> &protoData, MRAContactListEntry &item) {
item.setFlags( protoData[0].toUInt() );
item.setGroup( protoData[1].toUInt() );
item.setAddress( protoData[2].toString() );
item.setNick( protoData[3].toString() );
item.setServerFlags( protoData[4].toUInt() );
item.setStatus( protoData[5].toUInt() );
}
#include "mraprotocolv123.moc"
<|endoftext|> |
<commit_before>#pragma once
#include "channel9.hpp"
namespace Channel9
{
template <typename tPtr>
bool in_nursery(const tPtr *ptr);
bool in_nursery(const Value &val);
// Implements an object nursery for young objects. Really simple allocator, pretty much just shoves
// the data in and goes on its merry way. When it's time to collect it (by default when it has less
// than 1/10 available space), it just moves its entire active set into the main object pool.
// As an invariant, whenever an inner collection is taking place there should be nothing pointing
// at the nursery as all objects (and references) should have been moved to the inner collector.
template <typename tInnerGC>
class GC::Nursery
{
struct Remembered
{
uintptr_t *location;
uintptr_t val;
};
// m_data is a pointer to the base address of the nursery chunk,
// m_next_pos is the next position to allocate from,
// m_remembered_set is the first item in the remembered set (also the end of the allocation)
// m_remembered_end is the end of the remembered set and the end of the nursery chunk as a whole.
// After a nursery collection, the nursery will be evacuated and m_next_pos will == m_data and m_end_pos will == m_data_end
uint8_t *m_data;
uint8_t *m_next_pos;
Remembered *m_remembered_set;
Remembered *m_remembered_end;
std::set<GCRoot*> m_roots;
tInnerGC m_inner_gc;
enum {
STATE_NORMAL,
STATE_NURSERY_COLLECT,
STATE_INNER_COLLECT,
} m_state;
size_t m_size;
size_t m_free;
size_t m_min_free;
size_t m_moved;
const static uint64_t POINTER_MASK = 0x00007fffffffffffULL;
struct Data
{
uint32_t m_size;
uint16_t m_type;
uint16_t m_flags;
uint8_t m_data[0];
static const uint16_t FORWARD_FLAG = 0x1;
inline Data *init(uint32_t size, uint16_t type){
m_size = size;
m_type = type;
m_flags = 0;
return this;
}
template <typename tPtr>
static Data *from_ptr(const tPtr *ptr)
{
assert(Channel9::in_nursery(ptr));
return (Data*)ptr - 1;
}
template <typename tObj>
void set_forward(tObj *to)
{
m_flags |= FORWARD_FLAG;
*(tObj**)m_data = to;
}
uint8_t *forward_addr() const
{
if (m_flags & FORWARD_FLAG)
return *(uint8_t**)m_data;
else
return NULL;
}
};
public:
Nursery(size_t size = 1<<22)
: m_state(STATE_NORMAL),
m_size(size),
m_free(size),
m_min_free(1<<14)
{
m_data = m_next_pos = (uint8_t*)malloc(size);
m_remembered_end = m_remembered_set = (Remembered*)(m_data + size);
}
// extra is how much to allocate, type is one of Channel9::ValueType, return the new location
// likely to call one of the more specific versions below
template <typename tObj>
tObj *alloc(size_t extra, uint16_t type, bool pinned = false)
{
size_t object_size = sizeof(tObj) + extra;
size_t data_size = sizeof(Data) + object_size;
if (!pinned && data_size < m_free)
{
Data *data = (Data*)m_next_pos;
m_next_pos += data_size;
m_free -= data_size;
data->init(object_size, type);
return (tObj*)data->m_data;
} else {
return m_inner_gc.alloc<tObj>(extra, type, pinned);
}
}
//potentially faster versions to be called only if the size is known at compile time
template <typename tObj>
tObj *alloc_small(size_t extra, uint16_t type)
{
return alloc<tObj>(extra, type);
}
template <typename tObj>
tObj *alloc_med(size_t extra, uint16_t type)
{
return m_inner_gc.alloc_med<tObj>(extra, type);
}
template <typename tObj>
tObj *alloc_big(size_t extra, uint16_t type)
{
return m_inner_gc.alloc_big<tObj>(extra, type);
}
template <typename tObj>
tObj *alloc_pinned(size_t extra, uint16_t type)
{
return m_inner_gc.alloc_pinned<tObj>(extra, type);
}
// notify the gc that an obj is pointed to, might mark it, might move it, might do something else. Returns true if it moved
template <typename tObj>
bool mark(tObj ** from);
// is this object valid? only to be used for debugging
template <typename tObj> bool validate(tObj * obj)
{
return true;
}
// read a pointer and do anything necessary to it.
template <typename tRef>
tRef read_ptr(const tRef &obj)
{
return m_inner_gc.read_ptr(obj);
}
// tell the GC that obj will contain a reference to the object pointed to by ptr
template <typename tRef, typename tVal>
void write_ptr(tRef &ref, const tVal &val)
{
assert(sizeof(val) == sizeof(uintptr_t));
if (!Channel9::in_nursery(&ref) && Channel9::in_nursery(val))
{
// TODO: What to do when this happens? Maybe it should be a deque anyways.
assert(m_free >= sizeof(Remembered));
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Write barrier, adding: %p(%s) <- %p(%s)\n", &ref, Channel9::in_nursery(&ref)? "yes":"no", *(void**)&val, Channel9::in_nursery(val)? "yes":"no");
m_free -= sizeof(Remembered);
Remembered *r = --m_remembered_set;
r->location = (uintptr_t*)&ref;
r->val = *(uintptr_t*)&val;
}
m_inner_gc.write_ptr(ref, val);
}
template <typename tPtr>
bool in_nursery(const tPtr *ptr)
{
return ((uint8_t*)ptr >= m_data && (uint8_t*)ptr < m_data + m_size);
}
template <typename tObj>
void update_ptr(Data *data, tObj **ptr)
{
// we have to be careful in here because the pointer may have originally been a
// value. If so, we need to do the right thing here.
// TODO: If the location has been changed to an integer that just happens to correspond
// to a pointer, how do we deal with that?
uintptr_t *manip_ptr = (uintptr_t*)ptr;
tObj *optr = (tObj*)(*manip_ptr & POINTER_MASK);
tObj *nptr = m_inner_gc.alloc<tObj>(data->m_size - sizeof(tObj), data->m_type);
memcpy(nptr, optr, data->m_size);
data->set_forward(nptr);
*manip_ptr = (*manip_ptr & ~POINTER_MASK) | ((uintptr_t)nptr & POINTER_MASK);
TRACE_QUIET_PRINTF(TRACE_GC, TRACE_DEBUG, " moved to %p\n", nptr);
gc_scan(nptr);
TRACE_DO(TRACE_GC, TRACE_INFO) m_moved += data->m_size + sizeof(Data);
}
void collect();
void safe_point()
{
if (m_inner_gc.need_collect() || m_free < m_min_free)
{
m_state = STATE_NURSERY_COLLECT;
collect();
}
m_state = STATE_INNER_COLLECT;
m_inner_gc.safe_point();
m_state = STATE_NORMAL;
}
void register_root(GCRoot *root)
{
m_inner_gc.register_root(root);
m_roots.insert(root);
}
void unregister_root(GCRoot *root)
{
m_inner_gc.unregister_root(root);
m_roots.erase(root);
}
};
template <typename tInnerGC>
template <typename tObj>
bool GC::Nursery<tInnerGC>::mark(tObj ** from)
{
switch (m_state)
{
case STATE_NURSERY_COLLECT:
if (in_nursery(*from))
{
Data *data = Data::from_ptr(*from);
tObj *nptr = (tObj*)data->forward_addr();
if (nptr)
{
*from = nptr;
} else {
nptr = m_inner_gc.alloc<tObj>(data->m_size - sizeof(tObj), data->m_type);
memcpy(nptr, *from, data->m_size);
data->set_forward(nptr);
*from = nptr;
gc_scan(nptr);
TRACE_DO(TRACE_GC, TRACE_INFO) m_moved += data->m_size + sizeof(Data);
}
return true;
}
// the nursery collector stops when it reaches an object not
// in the nursery.
return false;
case STATE_INNER_COLLECT:
return m_inner_gc.mark(from);
case STATE_NORMAL:
assert(false && "Marking object while not in a collection.");
return false;
}
return false;
}
template <typename tInnerGC>
void GC::Nursery<tInnerGC>::collect()
{
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Nursery collection begun (free: %"PRIu64"/%"PRIu64")\n", (uint64_t)m_free, uint64_t(m_size));
TRACE_DO(TRACE_GC, TRACE_INFO) m_moved = 0;
// first, scan the roots, which triggers a DFS through part the live set in the nursery
for (std::set<GCRoot*>::iterator it = m_roots.begin(); it != m_roots.end(); it++)
{
(*it)->scan();
}
// we only look through the external pointers in the remembered set,
// not the full root set. This also triggers a partial dfs through the live set,
// and updates the forwarding pointers
Remembered *it = m_remembered_set;
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Updating %"PRIu64" pointers in remembered set\n", uint64_t(m_remembered_end - m_remembered_set));
while (it != m_remembered_end)
{
uintptr_t raw = (*it->location & POINTER_MASK);
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Updating pointer %p (was set to %p, current value %p):", it->location, (void*)it->val, (void*)*it->location);
if (it->val == *it->location)
{
Data *data = Data::from_ptr((char*)raw);
uint8_t *nptr = data->forward_addr();
if (nptr)
{
TRACE_QUIET_PRINTF(TRACE_GC, TRACE_DEBUG, " to %p (in forward table)\n", nptr);
*it->location = (*it->location & ~POINTER_MASK) | ((uintptr_t)nptr & POINTER_MASK);
} else {
switch(data->m_type)
{
case STRING: update_ptr(data, (String**) it->location); break;
case TUPLE: update_ptr(data, (Tuple**) it->location); break;
case MESSAGE: update_ptr(data, (Message**) it->location); break;
case CALLABLE_CONTEXT: update_ptr(data, (CallableContext**) it->location); break;
case RUNNING_CONTEXT: update_ptr(data, (RunningContext**) it->location); break;
case RUNNABLE_CONTEXT: update_ptr(data, (RunnableContext**) it->location); break;
case VARIABLE_FRAME: update_ptr(data, (VariableFrame**) it->location); break;
default: assert(false && "Unknown GC type");
}
}
} else {
TRACE_QUIET_PRINTF(TRACE_GC, TRACE_DEBUG, " did nothing.\n");
}
it++;
}
// and then reset the nursery space
m_next_pos = m_data;
m_remembered_set = m_remembered_end = (Remembered*)(m_data + m_size);
m_free = m_size;
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Nursery collection done, moved %"PRIu64" bytes to the inner collector\n", uint64_t(m_moved));
}
template <typename tPtr>
bool in_nursery(const tPtr *ptr)
{
return value_pool.in_nursery(ptr);
}
}
<commit_msg>Count the number of data blocks that were moved, not just the bytes<commit_after>#pragma once
#include "channel9.hpp"
namespace Channel9
{
template <typename tPtr>
bool in_nursery(const tPtr *ptr);
bool in_nursery(const Value &val);
// Implements an object nursery for young objects. Really simple allocator, pretty much just shoves
// the data in and goes on its merry way. When it's time to collect it (by default when it has less
// than 1/10 available space), it just moves its entire active set into the main object pool.
// As an invariant, whenever an inner collection is taking place there should be nothing pointing
// at the nursery as all objects (and references) should have been moved to the inner collector.
template <typename tInnerGC>
class GC::Nursery
{
struct Remembered
{
uintptr_t *location;
uintptr_t val;
};
// m_data is a pointer to the base address of the nursery chunk,
// m_next_pos is the next position to allocate from,
// m_remembered_set is the first item in the remembered set (also the end of the allocation)
// m_remembered_end is the end of the remembered set and the end of the nursery chunk as a whole.
// After a nursery collection, the nursery will be evacuated and m_next_pos will == m_data and m_end_pos will == m_data_end
uint8_t *m_data;
uint8_t *m_next_pos;
Remembered *m_remembered_set;
Remembered *m_remembered_end;
std::set<GCRoot*> m_roots;
tInnerGC m_inner_gc;
enum {
STATE_NORMAL,
STATE_NURSERY_COLLECT,
STATE_INNER_COLLECT,
} m_state;
size_t m_size;
size_t m_free;
size_t m_min_free;
size_t m_moved_bytes;
size_t m_moved_data;
const static uint64_t POINTER_MASK = 0x00007fffffffffffULL;
struct Data
{
uint32_t m_size;
uint16_t m_type;
uint16_t m_flags;
uint8_t m_data[0];
static const uint16_t FORWARD_FLAG = 0x1;
inline Data *init(uint32_t size, uint16_t type){
m_size = size;
m_type = type;
m_flags = 0;
return this;
}
template <typename tPtr>
static Data *from_ptr(const tPtr *ptr)
{
assert(Channel9::in_nursery(ptr));
return (Data*)ptr - 1;
}
template <typename tObj>
void set_forward(tObj *to)
{
m_flags |= FORWARD_FLAG;
*(tObj**)m_data = to;
}
uint8_t *forward_addr() const
{
if (m_flags & FORWARD_FLAG)
return *(uint8_t**)m_data;
else
return NULL;
}
};
public:
Nursery(size_t size = 1<<22)
: m_state(STATE_NORMAL),
m_size(size),
m_free(size),
m_min_free(1<<14)
{
m_data = m_next_pos = (uint8_t*)malloc(size);
m_remembered_end = m_remembered_set = (Remembered*)(m_data + size);
}
// extra is how much to allocate, type is one of Channel9::ValueType, return the new location
// likely to call one of the more specific versions below
template <typename tObj>
tObj *alloc(size_t extra, uint16_t type, bool pinned = false)
{
size_t object_size = sizeof(tObj) + extra;
size_t data_size = sizeof(Data) + object_size;
if (!pinned && data_size < m_free)
{
Data *data = (Data*)m_next_pos;
m_next_pos += data_size;
m_free -= data_size;
data->init(object_size, type);
return (tObj*)data->m_data;
} else {
return m_inner_gc.alloc<tObj>(extra, type, pinned);
}
}
//potentially faster versions to be called only if the size is known at compile time
template <typename tObj>
tObj *alloc_small(size_t extra, uint16_t type)
{
return alloc<tObj>(extra, type);
}
template <typename tObj>
tObj *alloc_med(size_t extra, uint16_t type)
{
return m_inner_gc.alloc_med<tObj>(extra, type);
}
template <typename tObj>
tObj *alloc_big(size_t extra, uint16_t type)
{
return m_inner_gc.alloc_big<tObj>(extra, type);
}
template <typename tObj>
tObj *alloc_pinned(size_t extra, uint16_t type)
{
return m_inner_gc.alloc_pinned<tObj>(extra, type);
}
// notify the gc that an obj is pointed to, might mark it, might move it, might do something else. Returns true if it moved
template <typename tObj>
bool mark(tObj ** from);
// is this object valid? only to be used for debugging
template <typename tObj> bool validate(tObj * obj)
{
return true;
}
// read a pointer and do anything necessary to it.
template <typename tRef>
tRef read_ptr(const tRef &obj)
{
return m_inner_gc.read_ptr(obj);
}
// tell the GC that obj will contain a reference to the object pointed to by ptr
template <typename tRef, typename tVal>
void write_ptr(tRef &ref, const tVal &val)
{
assert(sizeof(val) == sizeof(uintptr_t));
if (!Channel9::in_nursery(&ref) && Channel9::in_nursery(val))
{
// TODO: What to do when this happens? Maybe it should be a deque anyways.
assert(m_free >= sizeof(Remembered));
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Write barrier, adding: %p(%s) <- %p(%s)\n", &ref, Channel9::in_nursery(&ref)? "yes":"no", *(void**)&val, Channel9::in_nursery(val)? "yes":"no");
m_free -= sizeof(Remembered);
Remembered *r = --m_remembered_set;
r->location = (uintptr_t*)&ref;
r->val = *(uintptr_t*)&val;
}
m_inner_gc.write_ptr(ref, val);
}
template <typename tPtr>
bool in_nursery(const tPtr *ptr)
{
return ((uint8_t*)ptr >= m_data && (uint8_t*)ptr < (uint8_t*)m_remembered_set);
}
template <typename tObj>
void update_ptr(Data *data, tObj **ptr)
{
// we have to be careful in here because the pointer may have originally been a
// value. If so, we need to do the right thing here.
// TODO: If the location has been changed to an integer that just happens to correspond
// to a pointer, how do we deal with that?
uintptr_t *manip_ptr = (uintptr_t*)ptr;
tObj *optr = (tObj*)(*manip_ptr & POINTER_MASK);
tObj *nptr = m_inner_gc.alloc<tObj>(data->m_size - sizeof(tObj), data->m_type);
memcpy(nptr, optr, data->m_size);
data->set_forward(nptr);
*manip_ptr = (*manip_ptr & ~POINTER_MASK) | ((uintptr_t)nptr & POINTER_MASK);
TRACE_QUIET_PRINTF(TRACE_GC, TRACE_DEBUG, " moved to %p\n", nptr);
gc_scan(nptr);
TRACE_DO(TRACE_GC, TRACE_INFO){
m_moved_bytes += data->m_size + sizeof(Data);
m_moved_data++;
}
}
void collect();
void safe_point()
{
if (m_inner_gc.need_collect() || m_free < m_min_free)
{
m_state = STATE_NURSERY_COLLECT;
collect();
}
m_state = STATE_INNER_COLLECT;
m_inner_gc.safe_point();
m_state = STATE_NORMAL;
}
void register_root(GCRoot *root)
{
m_inner_gc.register_root(root);
m_roots.insert(root);
}
void unregister_root(GCRoot *root)
{
m_inner_gc.unregister_root(root);
m_roots.erase(root);
}
};
template <typename tInnerGC>
template <typename tObj>
bool GC::Nursery<tInnerGC>::mark(tObj ** from)
{
switch (m_state)
{
case STATE_NURSERY_COLLECT:
if (in_nursery(*from))
{
Data *data = Data::from_ptr(*from);
tObj *nptr = (tObj*)data->forward_addr();
if (nptr)
{
*from = nptr;
} else {
nptr = m_inner_gc.alloc<tObj>(data->m_size - sizeof(tObj), data->m_type);
memcpy(nptr, *from, data->m_size);
data->set_forward(nptr);
*from = nptr;
gc_scan(nptr);
TRACE_DO(TRACE_GC, TRACE_INFO){
m_moved_bytes += data->m_size + sizeof(Data);
m_moved_data++;
}
}
return true;
}
// the nursery collector stops when it reaches an object not
// in the nursery.
return false;
case STATE_INNER_COLLECT:
return m_inner_gc.mark(from);
case STATE_NORMAL:
assert(false && "Marking object while not in a collection.");
return false;
}
return false;
}
template <typename tInnerGC>
void GC::Nursery<tInnerGC>::collect()
{
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Nursery collection begun (free: %"PRIu64"/%"PRIu64")\n", (uint64_t)m_free, uint64_t(m_size));
TRACE_DO(TRACE_GC, TRACE_INFO) m_moved_bytes = m_moved_data = 0;
// first, scan the roots, which triggers a DFS through part the live set in the nursery
for (std::set<GCRoot*>::iterator it = m_roots.begin(); it != m_roots.end(); it++)
{
(*it)->scan();
}
// we only look through the external pointers in the remembered set,
// not the full root set. This also triggers a partial dfs through the live set,
// and updates the forwarding pointers
Remembered *it = m_remembered_set;
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Updating %"PRIu64" pointers in remembered set\n", uint64_t(m_remembered_end - m_remembered_set));
while (it != m_remembered_end)
{
uintptr_t raw = (*it->location & POINTER_MASK);
TRACE_PRINTF(TRACE_GC, TRACE_DEBUG, "Updating pointer %p (was set to %p, current value %p):", it->location, (void*)it->val, (void*)*it->location);
if (it->val == *it->location)
{
Data *data = Data::from_ptr((uint8_t*)raw);
uint8_t *nptr = data->forward_addr();
if (nptr)
{
TRACE_QUIET_PRINTF(TRACE_GC, TRACE_DEBUG, " to %p (in forward table)\n", nptr);
*it->location = (*it->location & ~POINTER_MASK) | ((uintptr_t)nptr & POINTER_MASK);
} else {
switch(data->m_type)
{
case STRING: update_ptr(data, (String**) it->location); break;
case TUPLE: update_ptr(data, (Tuple**) it->location); break;
case MESSAGE: update_ptr(data, (Message**) it->location); break;
case CALLABLE_CONTEXT: update_ptr(data, (CallableContext**) it->location); break;
case RUNNING_CONTEXT: update_ptr(data, (RunningContext**) it->location); break;
case RUNNABLE_CONTEXT: update_ptr(data, (RunnableContext**) it->location); break;
case VARIABLE_FRAME: update_ptr(data, (VariableFrame**) it->location); break;
default: assert(false && "Unknown GC type");
}
}
} else {
TRACE_QUIET_PRINTF(TRACE_GC, TRACE_DEBUG, " did nothing.\n");
}
it++;
}
// and then reset the nursery space
m_next_pos = m_data;
m_remembered_set = m_remembered_end = (Remembered*)(m_data + m_size);
m_free = m_size;
TRACE_PRINTF(TRACE_GC, TRACE_INFO, "Nursery collection done, moved %"PRIu64" Data/%"PRIu64" bytes to the inner collector\n", uint64_t(m_moved_data), uint64_t(m_moved_bytes));
}
template <typename tPtr>
bool in_nursery(const tPtr *ptr)
{
return value_pool.in_nursery(ptr);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int> > threeSum(vector<int>& nums)
{
const size_t numsSize=nums.size();
if(numsSize < 3)
{
return {};
}
vector<vector<int>> result;
sort(begin(nums), end(nums));
for(int i=0;i<numsSize;)
{
int start=i+1
int end=numsSize-1;
while(start < end)
{
if(nums[i]+nums[start]+nums[end]==0)
{
result.push_back({nums[i],nums[start],nums[end]});
start++;
end--;
while(start < end && nums[start]==nums[start-1])
{
start++;
}
while(start < end && nums[end]==nums[end+1])
{
end--;
}
}
else if(nums[i] + nums[start] + nums[end] < 0)
{
start++;
while(start < end && nums[start]==nums[start-1])
{
start++;
}
}
else
{
end--;
while(start < end && nums[end]==nums[end+1])
{
end--;
}
}
}
i++;
while(i< numsSize && nums[i]==nums[i-1])
{
i++;
}
}
return result;
}<commit_msg>Fixing spacing issue<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> threeSum(vector<int>& nums)
{
const size_t numsSize=nums.size();
if(numsSize < 3)
{
return {};
}
vector<vector<int>> result;
sort(begin(nums), end(nums));
for(int i=0;i<numsSize;)
{
int start=i+1
int end=numsSize-1;
while(start < end)
{
if(nums[i]+nums[start]+nums[end]==0)
{
result.push_back({nums[i],nums[start],nums[end]});
start++;
end--;
while(start < end && nums[start]==nums[start-1])
{
start++;
}
while(start < end && nums[end]==nums[end+1])
{
end--;
}
}
else if(nums[i] + nums[start] + nums[end] < 0)
{
start++;
while(start < end && nums[start]==nums[start-1])
{
start++;
}
}
else
{
end--;
while(start < end && nums[end]==nums[end+1])
{
end--;
}
}
}
i++;
while(i< numsSize && nums[i]==nums[i-1])
{
i++;
}
}
return result;
}<|endoftext|> |
<commit_before><commit_msg>#87379# colliding value-checking<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: GraphicObjectBar.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2006-07-25 11:46:00 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "GraphicObjectBar.hxx"
#include <limits.h>
#include <vcl/msgbox.hxx>
#include <svtools/whiter.hxx>
#include <svtools/itempool.hxx>
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_GRFFLT_HXX //autogen
#include <svx/grfflt.hxx>
#endif
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SVX_GRAFCTRL_HXX
#include <svx/grafctrl.hxx>
#endif
#pragma hdrstop
#include <sfx2/objface.hxx>
#include "app.hrc"
#include "res_bmp.hrc"
#include "glob.hrc"
#include "strings.hrc"
#include "DrawDocShell.hxx"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
using namespace sd;
#define GraphicObjectBar
#include "sdslots.hxx"
namespace sd {
SFX_DECL_TYPE( 13 );
// -----------------------
// - GraphicObjectBar -
// -----------------------
SFX_IMPL_INTERFACE( GraphicObjectBar, SfxShell, SdResId( STR_GRAFOBJECTBARSHELL ) )
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( GraphicObjectBar, SfxShell );
// -----------------------------------------------------------------------------
GraphicObjectBar::GraphicObjectBar (
ViewShell* pSdViewShell,
::sd::View* pSdView )
: SfxShell (pSdViewShell->GetViewShell()),
pView ( pSdView ),
pViewSh ( pSdViewShell ),
nMappedSlotFilter ( SID_GRFFILTER_INVERT )
{
DrawDocShell* pDocShell = pViewSh->GetDocSh();
SetPool( &pDocShell->GetPool() );
SetUndoManager( pDocShell->GetUndoManager() );
SetRepeatTarget( pView );
SetHelpId( SD_IF_SDDRAWGRAFOBJECTBAR );
SetName( String( RTL_CONSTASCII_USTRINGPARAM( "Graphic objectbar" )));
}
// -----------------------------------------------------------------------------
GraphicObjectBar::~GraphicObjectBar()
{
SetRepeatTarget( NULL );
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::GetAttrState( SfxItemSet& rSet )
{
if( pView )
SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::Execute( SfxRequest& rReq )
{
if( pView )
{
SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );
Invalidate();
}
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::GetFilterState( SfxItemSet& rSet )
{
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
BOOL bEnable = FALSE;
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetMarkedSdrObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )
bEnable = TRUE;
}
if( !bEnable )
SvxGraphicFilter::DisableGraphicFilterSlots( rSet );
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::ExecuteFilter( SfxRequest& rReq )
{
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetMarkedSdrObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )
{
GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );
if( SVX_GRAPHICFILTER_ERRCODE_NONE ==
SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )
{
SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );
if( pPageView )
{
SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();
String aStr( pView->GetDescriptionOfMarkedObjects() );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( SdResId( STR_UNDO_GRAFFILTER ) ) );
pView->BegUndo( aStr );
pFilteredObj->SetGraphicObject( aFilterObj );
pView->ReplaceObject( pObj, *pPageView, pFilteredObj );
pView->EndUndo();
}
}
}
}
Invalidate();
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.28); FILE MERGED 2006/09/01 17:37:32 kaib 1.7.28.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: GraphicObjectBar.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 19:30:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "GraphicObjectBar.hxx"
#include <limits.h>
#include <vcl/msgbox.hxx>
#include <svtools/whiter.hxx>
#include <svtools/itempool.hxx>
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_GRFFLT_HXX //autogen
#include <svx/grfflt.hxx>
#endif
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SVX_GRAFCTRL_HXX
#include <svx/grafctrl.hxx>
#endif
#include <sfx2/objface.hxx>
#include "app.hrc"
#include "res_bmp.hrc"
#include "glob.hrc"
#include "strings.hrc"
#include "DrawDocShell.hxx"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "sdresid.hxx"
#include "drawdoc.hxx"
using namespace sd;
#define GraphicObjectBar
#include "sdslots.hxx"
namespace sd {
SFX_DECL_TYPE( 13 );
// -----------------------
// - GraphicObjectBar -
// -----------------------
SFX_IMPL_INTERFACE( GraphicObjectBar, SfxShell, SdResId( STR_GRAFOBJECTBARSHELL ) )
{
}
// -----------------------------------------------------------------------------
TYPEINIT1( GraphicObjectBar, SfxShell );
// -----------------------------------------------------------------------------
GraphicObjectBar::GraphicObjectBar (
ViewShell* pSdViewShell,
::sd::View* pSdView )
: SfxShell (pSdViewShell->GetViewShell()),
pView ( pSdView ),
pViewSh ( pSdViewShell ),
nMappedSlotFilter ( SID_GRFFILTER_INVERT )
{
DrawDocShell* pDocShell = pViewSh->GetDocSh();
SetPool( &pDocShell->GetPool() );
SetUndoManager( pDocShell->GetUndoManager() );
SetRepeatTarget( pView );
SetHelpId( SD_IF_SDDRAWGRAFOBJECTBAR );
SetName( String( RTL_CONSTASCII_USTRINGPARAM( "Graphic objectbar" )));
}
// -----------------------------------------------------------------------------
GraphicObjectBar::~GraphicObjectBar()
{
SetRepeatTarget( NULL );
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::GetAttrState( SfxItemSet& rSet )
{
if( pView )
SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::Execute( SfxRequest& rReq )
{
if( pView )
{
SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );
Invalidate();
}
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::GetFilterState( SfxItemSet& rSet )
{
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
BOOL bEnable = FALSE;
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetMarkedSdrObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )
bEnable = TRUE;
}
if( !bEnable )
SvxGraphicFilter::DisableGraphicFilterSlots( rSet );
}
// -----------------------------------------------------------------------------
void GraphicObjectBar::ExecuteFilter( SfxRequest& rReq )
{
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetMarkedSdrObj();
if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )
{
GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );
if( SVX_GRAPHICFILTER_ERRCODE_NONE ==
SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )
{
SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );
if( pPageView )
{
SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();
String aStr( pView->GetDescriptionOfMarkedObjects() );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( SdResId( STR_UNDO_GRAFFILTER ) ) );
pView->BegUndo( aStr );
pFilteredObj->SetGraphicObject( aFilterObj );
pView->ReplaceObject( pObj, *pPageView, pFilteredObj );
pView->EndUndo();
}
}
}
}
Invalidate();
}
} // end of namespace sd
<|endoftext|> |
<commit_before>#include <muduo/base/CountDownLatch.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/Thread.h>
#include <muduo/base/Timestamp.h>
#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <vector>
#include <stdio.h>
using namespace muduo;
using namespace std;
MutexLock g_mutex;
vector<int> g_vec;
const int kCount = 10*1000*1000;
void threadFunc()
{
for (int i = 0; i < kCount; ++i)
{
MutexLockGuard lock(g_mutex);
g_vec.push_back(i);
}
}
int main()
{
const int kMaxThreads = 8;
g_vec.reserve(kMaxThreads * kCount);
Timestamp start(Timestamp::now());
for (int i = 0; i < kCount; ++i)
{
g_vec.push_back(i);
}
printf("single thread without lock %f\n", timeDifference(Timestamp::now(), start));
start = Timestamp::now();
threadFunc();
printf("single thread with lock %f\n", timeDifference(Timestamp::now(), start));
for (int nthreads = 1; nthreads < kMaxThreads; ++nthreads)
{
boost::ptr_vector<Thread> threads;
g_vec.clear();
start = Timestamp::now();
for (int i = 0; i < nthreads; ++i)
{
threads.push_back(new Thread(&threadFunc));
threads.back().start();
}
for (int i = 0; i < nthreads; ++i)
{
threads[i].join();
}
printf("%d thread(s) with lock %f\n", nthreads, timeDifference(Timestamp::now(), start));
}
}
<commit_msg>add check for MCHECK().<commit_after>#include <muduo/base/CountDownLatch.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/Thread.h>
#include <muduo/base/Timestamp.h>
#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <vector>
#include <stdio.h>
using namespace muduo;
using namespace std;
MutexLock g_mutex;
vector<int> g_vec;
const int kCount = 10*1000*1000;
void threadFunc()
{
for (int i = 0; i < kCount; ++i)
{
MutexLockGuard lock(g_mutex);
g_vec.push_back(i);
}
}
int foo() __attribute__ ((noinline));
int g_count = 0;
int foo()
{
++g_count;
return 0;
}
int main()
{
MCHECK(foo());
if (g_count != 1)
{
printf("MCHECK calls twice.\n");
abort();
}
const int kMaxThreads = 8;
g_vec.reserve(kMaxThreads * kCount);
Timestamp start(Timestamp::now());
for (int i = 0; i < kCount; ++i)
{
g_vec.push_back(i);
}
printf("single thread without lock %f\n", timeDifference(Timestamp::now(), start));
start = Timestamp::now();
threadFunc();
printf("single thread with lock %f\n", timeDifference(Timestamp::now(), start));
for (int nthreads = 1; nthreads < kMaxThreads; ++nthreads)
{
boost::ptr_vector<Thread> threads;
g_vec.clear();
start = Timestamp::now();
for (int i = 0; i < nthreads; ++i)
{
threads.push_back(new Thread(&threadFunc));
threads.back().start();
}
for (int i = 0; i < nthreads; ++i)
{
threads[i].join();
}
printf("%d thread(s) with lock %f\n", nthreads, timeDifference(Timestamp::now(), start));
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
//
// Class AliMUONGeometryStore
// -------------------------------------
// The class contains the array of the detection elements,
// which are sorted using the AliMUONVGeometryDEIndexing class.
// The class provides fast access to detection element via DetElemId.
//
// Author: Ivana Hrivnacova, IPN Orsay
#include <Riostream.h>
#include <TGeoMatrix.h>
#include "AliLog.h"
#include "AliMUONGeometryStore.h"
#include "AliMUONVGeometryDEIndexing.h"
ClassImp(AliMUONGeometryStore)
const Int_t AliMUONGeometryStore::fgkInitSize = 100;
//______________________________________________________________________________
AliMUONGeometryStore::AliMUONGeometryStore(
AliMUONVGeometryDEIndexing* indexing,
Bool_t isOwner)
: TObject(),
fObjects(fgkInitSize),
fDEIndexing(indexing)
{
// Standard constructor
fObjects.SetOwner(isOwner);
for (Int_t i=0; i<fgkInitSize; i++) fObjects[i] = 0;
}
//______________________________________________________________________________
AliMUONGeometryStore::AliMUONGeometryStore()
: TObject(),
fObjects(),
fDEIndexing(0)
{
// Default constructor
}
//______________________________________________________________________________
AliMUONGeometryStore::AliMUONGeometryStore(
const AliMUONGeometryStore& rhs)
: TObject(rhs)
{
AliFatal("Copy constructor is not implemented.");
}
//______________________________________________________________________________
AliMUONGeometryStore::~AliMUONGeometryStore() {
//
fObjects.Delete();
}
//______________________________________________________________________________
AliMUONGeometryStore&
AliMUONGeometryStore::operator = (const AliMUONGeometryStore& rhs)
{
// check assignement to self
if (this == &rhs) return *this;
AliFatal("Assignment operator is not implemented.");
return *this;
}
//
// public methods
//
//______________________________________________________________________________
void AliMUONGeometryStore::Add(Int_t objectId, TObject* object)
{
// Add detection element in the array
// if detection element with the same Id is not yet present.
// ---
//cout << ".. adding " << objectId
// << " index: " << fDEIndexing->GetDetElementIndex(objectId) << endl;
// Expand array if the init size has been reached
Int_t index = fDEIndexing->GetDetElementIndex(objectId);
while ( index >= fObjects.GetSize() ) {
Int_t size = fObjects.GetSize();
fObjects.Expand(size + fgkInitSize);
for (Int_t i=size; i<fObjects.GetSize(); i++) fObjects[i] = 0;
}
// Add to the map
if ( !Get(objectId, false) )
fObjects.AddAt(object, index);
else
AliWarning(Form("The detection element %d is already present", objectId));
}
//______________________________________________________________________________
TObject*
AliMUONGeometryStore::Get(Int_t objectId, Bool_t warn) const
{
// Returns transformation for the specified detector element Id
// ---
Int_t index = fDEIndexing->GetDetElementIndex(objectId);
if ( index >= 0 && index < fObjects.GetEntriesFast() )
return (TObject*) fObjects.At(index);
else {
if (warn) AliWarning(Form("Index %d out of limits", index));
return 0;
}
}
//______________________________________________________________________________
Int_t AliMUONGeometryStore::GetNofEntries() const
{
// Add check if the array is already filled
return fObjects.GetEntriesFast();
}
//______________________________________________________________________________
TObject*
AliMUONGeometryStore::GetEntry(Int_t index) const
{
//
// Add check if the array is already filled
return (TObject*) fObjects.At(index);
}
<commit_msg>Remove delete from class destructor (Ch. Finck)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
//
// Class AliMUONGeometryStore
// -------------------------------------
// The class contains the array of the detection elements,
// which are sorted using the AliMUONVGeometryDEIndexing class.
// The class provides fast access to detection element via DetElemId.
//
// Author: Ivana Hrivnacova, IPN Orsay
#include <Riostream.h>
#include <TGeoMatrix.h>
#include "AliLog.h"
#include "AliMUONGeometryStore.h"
#include "AliMUONVGeometryDEIndexing.h"
ClassImp(AliMUONGeometryStore)
const Int_t AliMUONGeometryStore::fgkInitSize = 100;
//______________________________________________________________________________
AliMUONGeometryStore::AliMUONGeometryStore(
AliMUONVGeometryDEIndexing* indexing,
Bool_t isOwner)
: TObject(),
fObjects(fgkInitSize),
fDEIndexing(indexing)
{
// Standard constructor
fObjects.SetOwner(isOwner);
for (Int_t i=0; i<fgkInitSize; i++) fObjects[i] = 0;
}
//______________________________________________________________________________
AliMUONGeometryStore::AliMUONGeometryStore()
: TObject(),
fObjects(),
fDEIndexing(0)
{
// Default constructor
}
//______________________________________________________________________________
AliMUONGeometryStore::AliMUONGeometryStore(
const AliMUONGeometryStore& rhs)
: TObject(rhs)
{
AliFatal("Copy constructor is not implemented.");
}
//______________________________________________________________________________
AliMUONGeometryStore::~AliMUONGeometryStore()
{
}
//______________________________________________________________________________
AliMUONGeometryStore&
AliMUONGeometryStore::operator = (const AliMUONGeometryStore& rhs)
{
// check assignement to self
if (this == &rhs) return *this;
AliFatal("Assignment operator is not implemented.");
return *this;
}
//
// public methods
//
//______________________________________________________________________________
void AliMUONGeometryStore::Add(Int_t objectId, TObject* object)
{
// Add detection element in the array
// if detection element with the same Id is not yet present.
// ---
//cout << ".. adding " << objectId
// << " index: " << fDEIndexing->GetDetElementIndex(objectId) << endl;
// Expand array if the init size has been reached
Int_t index = fDEIndexing->GetDetElementIndex(objectId);
while ( index >= fObjects.GetSize() ) {
Int_t size = fObjects.GetSize();
fObjects.Expand(size + fgkInitSize);
for (Int_t i=size; i<fObjects.GetSize(); i++) fObjects[i] = 0;
}
// Add to the map
if ( !Get(objectId, false) )
fObjects.AddAt(object, index);
else
AliWarning(Form("The detection element %d is already present", objectId));
}
//______________________________________________________________________________
TObject*
AliMUONGeometryStore::Get(Int_t objectId, Bool_t warn) const
{
// Returns transformation for the specified detector element Id
// ---
Int_t index = fDEIndexing->GetDetElementIndex(objectId);
if ( index >= 0 && index < fObjects.GetEntriesFast() )
return (TObject*) fObjects.At(index);
else {
if (warn) AliWarning(Form("Index %d out of limits", index));
return 0;
}
}
//______________________________________________________________________________
Int_t AliMUONGeometryStore::GetNofEntries() const
{
// Add check if the array is already filled
return fObjects.GetEntriesFast();
}
//______________________________________________________________________________
TObject*
AliMUONGeometryStore::GetEntry(Int_t index) const
{
//
// Add check if the array is already filled
return (TObject*) fObjects.At(index);
}
<|endoftext|> |
<commit_before><commit_msg>Add a dump of the currently outstanding jobs when enabling DNS tracing. Before it would just output the count.<commit_after><|endoftext|> |
<commit_before>y/*
kopeteglobalawaydialog.cpp - Kopete Global Away Dialog
Copyright (c) 2002 by Christopher TenHarmsel <tenharmsel@users.sourceforge.net>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopeteglobalawaydialog.h"
#include "kopeteaccountmanager.h"
#include "kopeteaway.h"
#include <kdebug.h>
KopeteGlobalAwayDialog::KopeteGlobalAwayDialog(QWidget *parent, const char *name)
: KopeteAwayDialog(parent, name)
{
}
void KopeteGlobalAwayDialog::setAway( int /*awayType*/ )
{
kdDebug(14000) << k_funcinfo << "Setting all protocols away " << endl;
// Set the global away message
awayInstance->setGlobalAwayMessage( getSelectedAwayMessage() );
// Tell all the protocols to set themselves away.
KopeteAccountManager::manager()->setAwayAll( getSelectedAwayMessage() );
}
#include "kopeteglobalawaydialog.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>CVS_SILENT CVS_EVEN_MORE_SILENT grmbl<commit_after>/*
kopeteglobalawaydialog.cpp - Kopete Global Away Dialog
Copyright (c) 2002 by Christopher TenHarmsel <tenharmsel@users.sourceforge.net>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopeteglobalawaydialog.h"
#include "kopeteaccountmanager.h"
#include "kopeteaway.h"
#include <kdebug.h>
KopeteGlobalAwayDialog::KopeteGlobalAwayDialog(QWidget *parent, const char *name)
: KopeteAwayDialog(parent, name)
{
}
void KopeteGlobalAwayDialog::setAway( int /*awayType*/ )
{
kdDebug(14000) << k_funcinfo << "Setting all protocols away " << endl;
// Set the global away message
awayInstance->setGlobalAwayMessage( getSelectedAwayMessage() );
// Tell all the protocols to set themselves away.
KopeteAccountManager::manager()->setAwayAll( getSelectedAwayMessage() );
}
#include "kopeteglobalawaydialog.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before><commit_msg>Disk cache: Small adjustment so that we continue with the process of creating a new entry after we detect a dirty entry with a partial hash collision.<commit_after><|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "webdavhandler.h"
#include <libkdepim/kpimprefs.h>
#include <kdebug.h>
#include <kconfig.h>
#include <qfile.h>
SloxItem::SloxItem()
: status( Invalid )
{
}
WebdavHandler::WebdavHandler()
: mLogCount( 0 )
{
KConfig cfg( "sloxrc" );
cfg.setGroup( "General" );
mLogFile = cfg.readEntry( "LogFile" );
kdDebug() << "LOG FILE: " << mLogFile << endl;
}
void WebdavHandler::log( const QString &text )
{
if ( mLogFile.isEmpty() ) return;
QString filename = mLogFile + "-" + QString::number( mLogCount );
QFile file( filename );
if ( !file.open( IO_WriteOnly ) ) {
kdWarning() << "Unable to open log file '" << filename << "'" << endl;
return;
}
QCString textUtf8 = text.utf8();
file.writeBlock( textUtf8.data(), textUtf8.size() - 1 );
if ( ++mLogCount > 5 ) mLogCount = 0;
}
QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc )
{
kdDebug() << "getSloxItems" << endl;
QValueList<SloxItem> items;
QDomElement docElement = doc.documentElement();
QDomNode responseNode;
for( responseNode = docElement.firstChild(); !responseNode.isNull();
responseNode = responseNode.nextSibling() ) {
QDomElement responseElement = responseNode.toElement();
if ( responseElement.tagName() == "response" ) {
QDomNode propstat = responseElement.namedItem( "propstat" );
if ( propstat.isNull() ) {
kdError() << "Unable to find propstat tag." << endl;
continue;
}
QDomNode prop = propstat.namedItem( "prop" );
if ( prop.isNull() ) {
kdError() << "Unable to find WebDAV property" << endl;
continue;
}
QDomNode sloxId = prop.namedItem( "sloxid" );
if ( sloxId.isNull() ) {
kdError() << "Unable to find SLOX id." << endl;
continue;
}
QDomElement idElement = sloxId.toElement();
QString uid = "KResources_SLOX_" + idElement.text();
QDomNode sloxStatus = prop.namedItem( "sloxstatus" );
if ( sloxStatus.isNull() ) {
kdError() << "Unable to find SLOX status." << endl;
continue;
}
SloxItem item;
item.uid = uid;
item.domNode = prop;
QDomElement sloxStatusElement = sloxStatus.toElement();
if ( sloxStatusElement.text() == "DELETE" ) {
item.status = SloxItem::Delete;
} else if ( sloxStatusElement.text() == "CREATE" ) {
item.status = SloxItem::Create;
}
items.append( item );
}
}
return items;
}
QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt )
{
uint ticks = dt.toTime_t();
return QString::number( ticks );
}
QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt,
const QString &timeZoneId )
{
uint ticks = dt.toTime_t();
return QString::number( ticks );
}
QDateTime WebdavHandler::sloxToQDateTime( const QString &str )
{
QString s = str.mid( 0, str.length() - 3 );
unsigned long ticks = s.toULong();
QDateTime dt;
dt.setTime_t( ticks, Qt::UTC );
return dt;
}
QDateTime WebdavHandler::sloxToQDateTime( const QString &str,
const QString &timeZoneId )
{
QString s = str.mid( 0, str.length() - 3 );
unsigned long ticks = s.toULong();
QDateTime dt;
dt.setTime_t( ticks, Qt::UTC );
return KPimPrefs::utcToLocalTime( dt, timeZoneId );
}
QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node,
const QString &tag )
{
QDomElement el = doc.createElementNS( "DAV", tag );
node.appendChild( el );
return el;
}
QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node,
const QString &tag,
const QString &text )
{
QDomElement el = doc.createElementNS( "SLOX", tag );
if ( !text.isEmpty() ) {
QDomText textnode = doc.createTextNode( text );
el.appendChild( textnode );
}
node.appendChild( el );
return el;
}
<commit_msg>SLOX uses milliseconds time, not seconds.<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "webdavhandler.h"
#include <libkdepim/kpimprefs.h>
#include <kdebug.h>
#include <kconfig.h>
#include <qfile.h>
SloxItem::SloxItem()
: status( Invalid )
{
}
WebdavHandler::WebdavHandler()
: mLogCount( 0 )
{
KConfig cfg( "sloxrc" );
cfg.setGroup( "General" );
mLogFile = cfg.readEntry( "LogFile" );
kdDebug() << "LOG FILE: " << mLogFile << endl;
}
void WebdavHandler::log( const QString &text )
{
if ( mLogFile.isEmpty() ) return;
QString filename = mLogFile + "-" + QString::number( mLogCount );
QFile file( filename );
if ( !file.open( IO_WriteOnly ) ) {
kdWarning() << "Unable to open log file '" << filename << "'" << endl;
return;
}
QCString textUtf8 = text.utf8();
file.writeBlock( textUtf8.data(), textUtf8.size() - 1 );
if ( ++mLogCount > 5 ) mLogCount = 0;
}
QValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc )
{
kdDebug() << "getSloxItems" << endl;
QValueList<SloxItem> items;
QDomElement docElement = doc.documentElement();
QDomNode responseNode;
for( responseNode = docElement.firstChild(); !responseNode.isNull();
responseNode = responseNode.nextSibling() ) {
QDomElement responseElement = responseNode.toElement();
if ( responseElement.tagName() == "response" ) {
QDomNode propstat = responseElement.namedItem( "propstat" );
if ( propstat.isNull() ) {
kdError() << "Unable to find propstat tag." << endl;
continue;
}
QDomNode prop = propstat.namedItem( "prop" );
if ( prop.isNull() ) {
kdError() << "Unable to find WebDAV property" << endl;
continue;
}
QDomNode sloxId = prop.namedItem( "sloxid" );
if ( sloxId.isNull() ) {
kdError() << "Unable to find SLOX id." << endl;
continue;
}
QDomElement idElement = sloxId.toElement();
QString uid = "KResources_SLOX_" + idElement.text();
QDomNode sloxStatus = prop.namedItem( "sloxstatus" );
if ( sloxStatus.isNull() ) {
kdError() << "Unable to find SLOX status." << endl;
continue;
}
SloxItem item;
item.uid = uid;
item.domNode = prop;
QDomElement sloxStatusElement = sloxStatus.toElement();
if ( sloxStatusElement.text() == "DELETE" ) {
item.status = SloxItem::Delete;
} else if ( sloxStatusElement.text() == "CREATE" ) {
item.status = SloxItem::Create;
}
items.append( item );
}
}
return items;
}
QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt )
{
uint ticks = dt.toTime_t();
return QString::number( ticks ) + "000";
}
QString WebdavHandler::qDateTimeToSlox( const QDateTime &dt,
const QString &timeZoneId )
{
uint ticks = dt.toTime_t();
return QString::number( ticks ) + "000";
}
QDateTime WebdavHandler::sloxToQDateTime( const QString &str )
{
QString s = str.mid( 0, str.length() - 3 );
unsigned long ticks = s.toULong();
QDateTime dt;
dt.setTime_t( ticks, Qt::UTC );
return dt;
}
QDateTime WebdavHandler::sloxToQDateTime( const QString &str,
const QString &timeZoneId )
{
QString s = str.mid( 0, str.length() - 3 );
unsigned long ticks = s.toULong();
QDateTime dt;
dt.setTime_t( ticks, Qt::UTC );
return KPimPrefs::utcToLocalTime( dt, timeZoneId );
}
QDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node,
const QString &tag )
{
QDomElement el = doc.createElementNS( "DAV", tag );
node.appendChild( el );
return el;
}
QDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node,
const QString &tag,
const QString &text )
{
QDomElement el = doc.createElementNS( "SLOX", tag );
if ( !text.isEmpty() ) {
QDomText textnode = doc.createTextNode( text );
el.appendChild( textnode );
}
node.appendChild( el );
return el;
}
<|endoftext|> |
<commit_before>// Copyright 2018 Google LLC. All Rights Reserved.
/*
Copyright (C) 2007 Steven L. Scott
This library 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 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef BOOM_EM_MIXTURE_COMPONENT_HPP
#define BOOM_EM_MIXTURE_COMPONENT_HPP
#include "Models/DataTypes.hpp"
#include "Models/ModelTypes.hpp"
namespace BOOM {
class EmMixtureComponent : virtual public MixtureComponent,
virtual public MLE_Model,
virtual public PosteriorModeModel {
public:
EmMixtureComponent *clone() const override = 0;
virtual void add_mixture_data(const Ptr<Data> &, double weight) = 0;
};
} // namespace BOOM
#endif // BOOM_EM_MIXTURE_COMPONENT_HPP
<commit_msg>Explicitly define rule-of-five members for EmMixtureComponent.<commit_after>// Copyright 2018 Google LLC. All Rights Reserved.
/*
Copyright (C) 2007 Steven L. Scott
This library 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 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef BOOM_EM_MIXTURE_COMPONENT_HPP
#define BOOM_EM_MIXTURE_COMPONENT_HPP
#include "Models/DataTypes.hpp"
#include "Models/ModelTypes.hpp"
namespace BOOM {
class EmMixtureComponent : virtual public MixtureComponent,
virtual public MLE_Model,
virtual public PosteriorModeModel {
public:
// The rule-of-five members are explicitly defined below because the
// implicit virtual assignment move operator has trouble with virtual base
// classes and had to be defined explicitly. Defining one means you need to
// define all, or you get stupid compiler warnings.
EmMixtureComponent() = default;
~EmMixtureComponent() = default;
EmMixtureComponent(const EmMixtureComponent &rhs)
: Model(rhs),
MixtureComponent(rhs),
MLE_Model(rhs),
PosteriorModeModel(rhs)
{}
EmMixtureComponent(EmMixtureComponent &&rhs)
: Model(rhs),
MixtureComponent(rhs),
MLE_Model(rhs),
PosteriorModeModel(rhs)
{}
EmMixtureComponent *clone() const override = 0;
virtual void add_mixture_data(const Ptr<Data> &, double weight) = 0;
EmMixtureComponent &operator=(const EmMixtureComponent &rhs) {
if (&rhs != this) {
MixtureComponent::operator=(rhs);
MLE_Model::operator=(rhs);
PosteriorModeModel::operator=(rhs);
}
return *this;
}
EmMixtureComponent &operator=(EmMixtureComponent &&rhs) {
if (&rhs != this) {
MixtureComponent::operator=(rhs);
MLE_Model::operator=(rhs);
PosteriorModeModel::operator=(rhs);
}
return *this;
}
};
} // namespace BOOM
#endif // BOOM_EM_MIXTURE_COMPONENT_HPP
<|endoftext|> |
<commit_before>#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <irrlicht/Keycodes.h>
#include <stdio.h>
#include <unistd.h>
#define RETURN 13
#define BS 8
#define SPACE 32
XKeyEvent createKeyEvent(Display *display,
Window &win,
Window &winRoot,
bool press,
int keycode,
int modifiers)
{
// Largely lifted from
// http://www.doctort.org/adam/nerd-notes/x11-fake-keypress-event.html
XKeyEvent event;
event.display = display;
event.window = win;
event.root = winRoot;
event.subwindow = None;
event.time = CurrentTime;
event.x = 1;
event.y = 1;
event.x_root = 1;
event.y_root = 1;
event.same_screen = True;
event.keycode = XKeysymToKeycode(display, keycode);
event.state = modifiers;
if(press)
event.type = KeyPress;
else
event.type = KeyRelease;
return event;
}
class X11Display {
public:
Display *display;
Window winRoot;
X11Display(const char* dispName);
~X11Display();
int sendKeyEvent(int keycode, bool keyDown);
};
// TODO: fail out if display doesn't initialize
X11Display::X11Display(const char* dispName) :
display(XOpenDisplay(dispName)),
winRoot(XDefaultRootWindow(display)) {}
X11Display::~X11Display() { XCloseDisplay(display); }
int X11Display::sendKeyEvent(int keycode, bool keyDown)
{
if(-1==keycode)
return 0;
printf("sendKeyEvent keycode: %d\n", keycode);
Window winFocus;
int revert;
XGetInputFocus(display, &winFocus, &revert);
XKeyEvent event = createKeyEvent(display, winFocus, winRoot, keyDown, keycode, 0);
XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);
return 0;
}
int mapKeyCode(int irrcode){
switch(irrcode){
//FIXME: only to get rid of arrow spam
case 37 ... 40:
return -1;
case irr::KEY_BACK :
return XK_BackSpace;
case irr::KEY_TAB :
return XK_Tab;
case irr::KEY_RETURN :
return XK_Return;
case irr::KEY_MINUS :
return XK_minus;
case irr::KEY_OEM_7 :
return XK_apostrophe;
default:
return irrcode;
}
}
<commit_msg>Added mod arg for sending key events<commit_after>#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <irrlicht/Keycodes.h>
#include <stdio.h>
#include <unistd.h>
#define RETURN 13
#define BS 8
#define SPACE 32
XKeyEvent createKeyEvent(Display *display,
Window &win,
Window &winRoot,
bool press,
int keycode,
int modifiers)
{
// Largely lifted from
// http://www.doctort.org/adam/nerd-notes/x11-fake-keypress-event.html
XKeyEvent event;
event.display = display;
event.window = win;
event.root = winRoot;
event.subwindow = None;
event.time = CurrentTime;
event.x = 1;
event.y = 1;
event.x_root = 1;
event.y_root = 1;
event.same_screen = True;
event.keycode = XKeysymToKeycode(display, keycode);
event.state = modifiers;
if(press)
event.type = KeyPress;
else
event.type = KeyRelease;
return event;
}
class X11Display {
public:
Display *display;
Window winRoot;
X11Display(const char* dispName);
~X11Display();
int sendKeyEvent(int keycode, bool keyDown, int mod);
};
// TODO: fail out if display doesn't initialize
X11Display::X11Display(const char* dispName) :
display(XOpenDisplay(dispName)),
winRoot(XDefaultRootWindow(display)) {}
X11Display::~X11Display() { XCloseDisplay(display); }
int X11Display::sendKeyEvent(int keycode, bool keyDown, int mod = 0)
{
if(-1==keycode)
return 0;
printf("sendKeyEvent keycode: %d\n", keycode);
Window winFocus;
int revert;
XGetInputFocus(display, &winFocus, &revert);
XKeyEvent event = createKeyEvent(display, winFocus, winRoot, keyDown, keycode, mod);
XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);
return 0;
}
int mapKeyCode(int irrcode){
switch(irrcode){
//FIXME: only to get rid of arrow spam
case 37 ... 40:
return -1;
case irr::KEY_BACK :
return XK_BackSpace;
case irr::KEY_TAB :
return XK_Tab;
case irr::KEY_RETURN :
return XK_Return;
case irr::KEY_MINUS :
return XK_minus;
case irr::KEY_OEM_7 :
return XK_apostrophe;
case irr::KEY_LSHIFT :
return XK_Shift_L;
default:
return irrcode;
}
}
<|endoftext|> |
<commit_before>#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <irrlicht/Keycodes.h>
#include <stdio.h>
#include <unistd.h>
#define RETURN 13
#define BS 8
#define SPACE 32
XKeyEvent createKeyEvent(Display *display,
Window &win,
Window &winRoot,
bool press,
int keycode,
int modifiers)
{
// Largely lifted from
// http://www.doctort.org/adam/nerd-notes/x11-fake-keypress-event.html
XKeyEvent event;
event.display = display;
event.window = win;
event.root = winRoot;
event.subwindow = None;
event.time = CurrentTime;
event.x = 1;
event.y = 1;
event.x_root = 1;
event.y_root = 1;
event.same_screen = True;
event.keycode = XKeysymToKeycode(display, keycode);
event.state = modifiers;
if(press)
event.type = KeyPress;
else
event.type = KeyRelease;
return event;
}
class X11Display {
public:
Display *display;
X11Display(const char* dispName);
~X11Display();
};
X11Display::X11Display(const char* dispName) :
display(XOpenDisplay(dispName)){}
X11Display::~X11Display() { XCloseDisplay(display); }
int mapKeyCode(int irrcode){
switch(irrcode){
//FIXME: only to get rid of arrow spam
case 37 ... 40:
return -1;
case irr::KEY_BACK :
return XK_BackSpace;
case irr::KEY_TAB :
return XK_Tab;
case irr::KEY_RETURN :
return XK_Return;
case irr::KEY_MINUS :
return XK_minus;
case irr::KEY_OEM_7 :
return XK_apostrophe;
default:
return irrcode;
}
}
int sendKeyEvent(const char* disp, int keycode)
{
if(-1==keycode)
return 0;
printf("sendKeyEvent keycode: %d\n", keycode);
Window winFocus;
int revert;
X11Display xdisp(disp);
//Display *display = XOpenDisplay(disp);
//if(NULL == display)
// return -1;
Window winRoot = XDefaultRootWindow(xdisp.display);
//XSetInputFocus(display, 1, revert, CurrentTime);
XGetInputFocus(xdisp.display, &winFocus, &revert);
XKeyEvent event = createKeyEvent(xdisp.display, winFocus, winRoot, true, keycode, 0);
XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);
event = createKeyEvent(xdisp.display, winFocus, winRoot, false, keycode, 0);
XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);
//XCloseDisplay(display);
return 0;
}
<commit_msg>Moved winroot into X11Display<commit_after>#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <irrlicht/Keycodes.h>
#include <stdio.h>
#include <unistd.h>
#define RETURN 13
#define BS 8
#define SPACE 32
XKeyEvent createKeyEvent(Display *display,
Window &win,
Window &winRoot,
bool press,
int keycode,
int modifiers)
{
// Largely lifted from
// http://www.doctort.org/adam/nerd-notes/x11-fake-keypress-event.html
XKeyEvent event;
event.display = display;
event.window = win;
event.root = winRoot;
event.subwindow = None;
event.time = CurrentTime;
event.x = 1;
event.y = 1;
event.x_root = 1;
event.y_root = 1;
event.same_screen = True;
event.keycode = XKeysymToKeycode(display, keycode);
event.state = modifiers;
if(press)
event.type = KeyPress;
else
event.type = KeyRelease;
return event;
}
class X11Display {
public:
Display *display;
Window winRoot;
X11Display(const char* dispName);
~X11Display();
};
// TODO: fail out if display doesn't initialize
X11Display::X11Display(const char* dispName) :
display(XOpenDisplay(dispName)),
winRoot(XDefaultRootWindow(display)) {}
X11Display::~X11Display() { XCloseDisplay(display); }
int mapKeyCode(int irrcode){
switch(irrcode){
//FIXME: only to get rid of arrow spam
case 37 ... 40:
return -1;
case irr::KEY_BACK :
return XK_BackSpace;
case irr::KEY_TAB :
return XK_Tab;
case irr::KEY_RETURN :
return XK_Return;
case irr::KEY_MINUS :
return XK_minus;
case irr::KEY_OEM_7 :
return XK_apostrophe;
default:
return irrcode;
}
}
int sendKeyEvent(const char* disp, int keycode)
{
if(-1==keycode)
return 0;
printf("sendKeyEvent keycode: %d\n", keycode);
Window winFocus;
int revert;
X11Display xdisp(disp);
XGetInputFocus(xdisp.display, &winFocus, &revert);
XKeyEvent event = createKeyEvent(xdisp.display, winFocus, xdisp.winRoot, true, keycode, 0);
XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);
event = createKeyEvent(xdisp.display, winFocus, xdisp.winRoot, false, keycode, 0);
XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Fix window title frame rate formatting<commit_after><|endoftext|> |
<commit_before>/*
* Converts media wiki markup into plaintext
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string.h>
#include <pcre.h>
#include <math.h>
#include <dirent.h>
using namespace std;
char* substr(char* dest, const char* src, int start, int len, int n)
{
if(start >= n)
throw string("Start index outside of string.");
int actual_length = min(len, n-start);
strncpy(dest, &src[start], actual_length);
dest[actual_length] = '\0';
return dest;
}
typedef struct _State
{
int N; // input length
int pos; // current position within input
const char* markup; // the markup input we're converting
char* out; // output string
int M; // maximum length of output without the terminating \0
int pos_out; // position within output string
string groups[10]; // will store regexp matches
} State;
class Textifier
{
private:
State state;
bool starts_with(string& str);
bool starts_with(const char* str);
const char* get_remaining();
char* get_current_out();
void skip_match();
void append_group_and_skip(int group);
void do_link();
void do_format();
void do_tag();
void do_meta();
void do_nowiki();
void do_heading();
void ignore_nested(string name, char open, char close);
bool get_link_boundaries(int& start, int& end, int& next);
string get_err(string name);
string* match(string name, pcre* regexp);
pcre* make_pcre(const char* expr, int options);
pcre* re_nowiki;
pcre* re_format;
pcre* re_heading;
public:
Textifier();
~Textifier();
char* textify(const char* markup, const int markup_len,
char* out, const int out_len);
void find_location(long& line, long& col);
string get_snippet();
};
Textifier::Textifier()
{
// Compile all the regexes we'll need
re_nowiki = make_pcre("^<nowiki>(.*?)</nowiki>", PCRE_MULTILINE | PCRE_DOTALL);
re_format = make_pcre("^(''+)(.*?)(\\1|\n)", 0);
re_heading = make_pcre("^(=+)\\s*(.+?)\\s*\\1", 0);
}
Textifier::~Textifier()
{
}
pcre* Textifier::make_pcre(const char* expr, int options)
{
const char* error;
int erroffset;
pcre *re = pcre_compile(expr, options, &error, &erroffset, NULL);
if(re == NULL) {
ostringstream os;
os << "PCRE compilation failed at offset " << erroffset << ": "
<< error << endl;
throw string(os.str());
}
return re;
}
bool Textifier::get_link_boundaries(int& start, int& end, int& next)
{
int i = state.pos; // current search position
int level = 0; // nesting level
do {
char ch = state.markup[i];
switch(ch) {
case '[':
if(level++ == 0)
start = i+1;
break;
case ']':
if(--level == 0)
end = i;
break;
case '|':
if(level == 1) { // does the pipe belong to current link or a nested one?
start = i+1;
end = start;
}
break;
default:
end++;
break;
}
i++;
} while(level > 0 &&
i < state.N &&
state.markup[i] != '\n');
next = i;
return level == 0; // if 0, then brackets match and this is a correct link
}
void Textifier::find_location(long& line, long& column)
{
line = 1;
column = 0;
for(int i = 0; i <= state.pos && i < state.N; i++) {
if(state.markup[i] == '\n') {
line++;
column = 0;
}
else
column++;
}
}
bool Textifier::starts_with(string& str)
{
return starts_with(str.c_str());
}
bool Textifier::starts_with(const char* str)
{
int i = state.pos;
int j = 0;
while(str[j] != '\0' &&
i < state.N) {
if(state.markup[i] != str[j])
return false;
i++;
j++;
}
return j == strlen(str);
}
string Textifier::get_snippet()
{
char snippet[30];
strncpy(snippet, get_remaining(), 30);
const int snippet_len = min(29, state.N-state.pos);
snippet[snippet_len] = '\0';
if(snippet_len < state.N - state.pos)
strncpy(&snippet[snippet_len-3], "...", 3);
return string(snippet);
}
string Textifier::get_err(string name)
{
ostringstream os;
os << "Expected markup type '" << name << "'";
return os.str();
}
string* Textifier::match(string name, pcre* regexp)
{
const int ovector_size = 3*sizeof(state.groups)/sizeof(string);
int ovector[ovector_size];
int rc = pcre_exec(regexp, NULL, get_remaining(), state.N-state.pos, 0, 0, ovector, ovector_size);
if(rc == PCRE_ERROR_NOMATCH || rc == 0)
return NULL;
else if(rc < 0)
throw get_err(name);
// from pcredemo.c
for(int i = 0; i < rc; i++) {
const char *substring_start = get_remaining() + ovector[2*i];
int substring_length = ovector[2*i+1] - ovector[2*i];
char substr[substring_length+1];
strncpy(substr, substring_start, substring_length);
substr[substring_length]='\0';
state.groups[i].assign(substr);
}
return state.groups;
}
const char* Textifier::get_remaining()
{
return &state.markup[state.pos];
}
char* Textifier::get_current_out()
{
return &state.out[state.pos_out];
}
void Textifier::skip_match()
{
state.pos += state.groups[0].length();
}
void Textifier::append_group_and_skip(int group)
{
string* val = &state.groups[group];
strncpy(get_current_out(), val->c_str(), val->length());
state.pos += state.groups[0].length();
state.pos_out += val->length();
}
void Textifier::do_link()
{
int start, end, next;
if(get_link_boundaries(start, end, next)) {
char contents[end-start+1];
substr(contents, state.markup, start, end-start, state.N);
if(strchr(contents, ':') != NULL) {
// this is a link to the page in a different language ignore it
state.pos = next;
}
else {
State state_copy = state;
try {
textify(contents, end-start, &state.out[state.pos_out], state.M-state.pos_out);
}
catch(string error) {
state_copy.pos = start + state.pos; // move the pointer to where recursive call failed
state = state_copy;
throw error;
}
state_copy.pos_out += state.pos_out;
state_copy.pos = next;
state = state_copy;
}
} else {
// Apparently mediawiki allows unmatched open brackets...
// If that's what we got, it's not a link.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
}
void Textifier::do_heading()
{
if(!match(string("heading"), re_heading))
{
// Not really a heading. Just copy to output.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
append_group_and_skip(2);
}
void Textifier::do_tag()
{
ignore_nested(string("tag"), '<', '>');
}
void Textifier::do_meta()
{
ignore_nested(string("meta"), '{', '}');
}
void Textifier::do_nowiki()
{
if(!match(string("nowiki"), re_nowiki))
throw get_err("nowiki");
skip_match();
}
void Textifier::do_format()
{
// ignore all immediate occurences of two or more apostrophes
while(state.pos < state.N && state.markup[state.pos] == '\'') {
state.pos++;
}
}
void Textifier::ignore_nested(string name, char open, char close)
{
if(state.markup[state.pos] != open)
throw get_err(name);
int level = 0;
do {
if(state.markup[state.pos] == open) level++;
else if(state.markup[state.pos] == close) level--;
} while(state.pos++ < state.N && level > 0);
}
/**
* Converts state.markup to plain text. */
char* Textifier::textify(const char* markup, const int markup_len,
char* out, const int out_len)
{
this->state.N = markup_len;
this->state.pos = 0;
this->state.markup = markup;
this->state.out = out;
this->state.M = out_len;
this->state.pos_out = 0;
while(state.pos < state.N && state.pos_out < state.M) {
if(starts_with("<nowiki>"))
do_nowiki();
else if(starts_with("["))
do_link();
else if(starts_with("<"))
do_tag();
else if(starts_with("{{") || starts_with("{|"))
do_meta();
else if(starts_with("="))
do_heading();
else if(starts_with("''"))
do_format();
else {
if(state.pos_out == 0 ||
state.out[state.pos_out-1] != state.markup[state.pos] ||
state.markup[state.pos] != '\n')
out[state.pos_out++] = state.markup[state.pos++];
else
state.pos++;
}
}
out[state.pos_out] = '\0';
return out;
}
int main(int argc, char** argv)
{
if(argc != 2) {
cerr << "Usage: " << argv[0] << " input-file" << endl;
return 1;
}
char* path = argv[1];
ifstream file(path, ios::in|ios::ate);
if(!file) {
cerr << "The file '" << path << "' does not exist" << endl;
return 1;
}
long size = file.tellg();
char* markup = new char[size+1];
file.seekg(0, ios::beg);
file.read(markup, size);
markup[size] = '\0';
file.close();
Textifier tf;
const int markup_len = strlen(markup);
char* plaintext = new char[markup_len+1];
try {
cout << tf.textify(markup, markup_len, plaintext, markup_len) << endl;
}
catch(string err) {
long line;
long column;
tf.find_location(line, column);
cerr << "ERROR (" << path << ":" << line << ":" << column << ") " << err
<< " at: " << tf.get_snippet() << endl;
return 1;
}
delete plaintext;
delete markup;
return 0;
}
<commit_msg>Ignore XML comments. Better handling of XML tags.<commit_after>/*
* Converts media wiki markup into plaintext
*/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string.h>
#include <pcre.h>
#include <math.h>
#include <dirent.h>
using namespace std;
char* substr(char* dest, const char* src, int start, int len, int n)
{
if(start >= n)
throw string("Start index outside of string.");
int actual_length = min(len, n-start);
strncpy(dest, &src[start], actual_length);
dest[actual_length] = '\0';
return dest;
}
typedef struct _State
{
int N; // input length
int pos; // current position within input
const char* markup; // the markup input we're converting
char* out; // output string
int M; // maximum length of output without the terminating \0
int pos_out; // position within output string
string groups[10]; // will store regexp matches
} State;
class Textifier
{
private:
State state;
bool starts_with(string& str);
bool starts_with(const char* str);
const char* get_remaining();
char* get_current_out();
void skip_match();
void skip_line();
void append_group_and_skip(int group);
void do_link();
void do_format();
void do_tag();
void do_meta_box();
void do_meta_pipe();
void do_heading();
void do_comment();
void ignore_nested(string name, char open, char close);
bool get_link_boundaries(int& start, int& end, int& next);
string get_err(string name);
string* match(string name, pcre* regexp);
pcre* make_pcre(const char* expr, int options);
pcre* re_nowiki;
pcre* re_format;
pcre* re_heading;
pcre* re_comment;
public:
Textifier();
~Textifier();
char* textify(const char* markup, const int markup_len,
char* out, const int out_len);
void find_location(long& line, long& col);
string get_snippet();
};
Textifier::Textifier()
{
// Compile all the regexes we'll need
re_nowiki = make_pcre("^<nowiki>(.*?)</nowiki>", PCRE_MULTILINE | PCRE_DOTALL);
re_format = make_pcre("^(''+)(.*?)(\\1|\n)", 0);
re_heading = make_pcre("^(=+)\\s*(.+?)\\s*\\1", 0);
re_comment = make_pcre("<!--.*?-->", PCRE_MULTILINE | PCRE_DOTALL);
}
Textifier::~Textifier()
{
}
pcre* Textifier::make_pcre(const char* expr, int options)
{
const char* error;
int erroffset;
pcre *re = pcre_compile(expr, options, &error, &erroffset, NULL);
if(re == NULL) {
ostringstream os;
os << "PCRE compilation failed at offset " << erroffset << ": "
<< error << endl;
throw string(os.str());
}
return re;
}
bool Textifier::get_link_boundaries(int& start, int& end, int& next)
{
int i = state.pos; // current search position
int level = 0; // nesting level
do {
char ch = state.markup[i];
switch(ch) {
case '[':
if(level++ == 0)
start = i+1;
break;
case ']':
if(--level == 0)
end = i;
break;
case '|':
if(level == 1) { // does the pipe belong to current link or a nested one?
start = i+1;
end = start;
}
break;
default:
end++;
break;
}
i++;
} while(level > 0 &&
i < state.N);
next = i;
return level == 0; // if 0, then brackets match and this is a correct link
}
void Textifier::find_location(long& line, long& column)
{
line = 1;
column = 0;
for(int i = 0; i <= state.pos && i < state.N; i++) {
if(state.markup[i] == '\n') {
line++;
column = 0;
}
else
column++;
}
}
bool Textifier::starts_with(string& str)
{
return starts_with(str.c_str());
}
bool Textifier::starts_with(const char* str)
{
if(state.N-state.pos < strlen(str))
return false;
int i = state.pos;
int j = 0;
while(str[j] != '\0' &&
i < state.N) {
if(state.markup[i] != str[j])
return false;
i++;
j++;
}
return j == strlen(str);
}
string Textifier::get_snippet()
{
char snippet[30];
strncpy(snippet, get_remaining(), 30);
const int snippet_len = min(29, state.N-state.pos);
snippet[snippet_len] = '\0';
if(snippet_len < state.N - state.pos)
strncpy(&snippet[snippet_len-3], "...", 3);
return string(snippet);
}
string Textifier::get_err(string name)
{
ostringstream os;
os << "Expected markup type '" << name << "'";
return os.str();
}
string* Textifier::match(string name, pcre* regexp)
{
const int ovector_size = 3*sizeof(state.groups)/sizeof(string);
int ovector[ovector_size];
int rc = pcre_exec(regexp, NULL, get_remaining(), state.N-state.pos, 0, 0, ovector, ovector_size);
if(rc == PCRE_ERROR_NOMATCH || rc == 0)
return NULL;
else if(rc < 0)
throw get_err(name);
// from pcredemo.c
for(int i = 0; i < rc; i++) {
const char *substring_start = get_remaining() + ovector[2*i];
int substring_length = ovector[2*i+1] - ovector[2*i];
char substr[substring_length+1];
strncpy(substr, substring_start, substring_length);
substr[substring_length]='\0';
state.groups[i].assign(substr);
}
return state.groups;
}
const char* Textifier::get_remaining()
{
return &state.markup[state.pos];
}
char* Textifier::get_current_out()
{
return &state.out[state.pos_out];
}
void Textifier::skip_match()
{
state.pos += state.groups[0].length();
}
void Textifier::skip_line()
{
while(state.pos < state.N && state.markup[state.pos++] != '\n');
}
void Textifier::append_group_and_skip(int group)
{
string* val = &state.groups[group];
strncpy(get_current_out(), val->c_str(), val->length());
state.pos += state.groups[0].length();
state.pos_out += val->length();
}
void Textifier::do_link()
{
int start, end, next;
if(get_link_boundaries(start, end, next)) {
char contents[end-start+1];
substr(contents, state.markup, start, end-start, state.N);
if(strchr(contents, ':') != NULL) {
// this is a link to the page in a different language ignore it
state.pos = next;
}
else {
State state_copy = state;
try {
textify(contents, end-start, &state.out[state.pos_out], state.M-state.pos_out);
}
catch(string error) {
state_copy.pos = start + state.pos; // move the pointer to where recursive call failed
state = state_copy;
throw error;
}
state_copy.pos_out += state.pos_out;
state_copy.pos = next;
state = state_copy;
}
} else {
// Apparently mediawiki allows unmatched open brackets...
// If that's what we got, it's not a link.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
}
void Textifier::do_heading()
{
if(!match(string("heading"), re_heading))
{
// Not really a heading. Just copy to output.
state.out[state.pos_out++] = state.markup[state.pos++];
return;
}
append_group_and_skip(2);
}
void Textifier::do_tag()
{
int level = 0;
bool closed = false;
do {
char ch = state.markup[state.pos];
switch(ch) {
case '<':
level++;
break;
case '>':
level--;
break;
case '/':
closed = (level == 1); // we must be inside the right closing tag
break;
}
state.pos++;
} while((level > 0 || !closed) && state.pos < state.N);
}
void Textifier::do_comment()
{
if(!match(string("comment"), re_comment))
throw get_err("comment");
skip_match();
}
void Textifier::do_meta_box()
{
ignore_nested(string("meta"), '{', '}');
}
void Textifier::do_meta_pipe()
{
skip_line();
}
void Textifier::do_format()
{
// ignore all immediate occurences of two or more apostrophes
while(state.pos < state.N && state.markup[state.pos] == '\'') {
state.pos++;
}
}
void Textifier::ignore_nested(string name, char open, char close)
{
if(state.markup[state.pos] != open)
throw get_err(name);
int level = 0;
do {
if(state.markup[state.pos] == open) level++;
else if(state.markup[state.pos] == close) level--;
} while(state.pos++ < state.N && level > 0);
}
/**
* Converts state.markup to plain text. */
char* Textifier::textify(const char* markup, const int markup_len,
char* out, const int out_len)
{
this->state.N = markup_len;
this->state.pos = 0;
this->state.markup = markup;
this->state.out = out;
this->state.M = out_len;
this->state.pos_out = 0;
while(state.pos < state.N && state.pos_out < state.M) {
if(starts_with("["))
do_link();
else if(starts_with("<!--"))
do_comment();
else if(starts_with("<"))
do_tag();
else if(starts_with("{{") || starts_with("{|"))
do_meta_box();
else if(starts_with("|") && (state.pos==0 || state.markup[state.pos-1]=='\n'))
do_meta_pipe();
else if(starts_with("="))
do_heading();
else if(starts_with("''"))
do_format();
else {
if(state.pos_out == 0 ||
state.out[state.pos_out-1] != state.markup[state.pos] ||
state.markup[state.pos] != '\n')
out[state.pos_out++] = state.markup[state.pos++];
else
state.pos++;
}
}
out[state.pos_out] = '\0';
return out;
}
int main(int argc, char** argv)
{
if(argc != 2) {
cerr << "Usage: " << argv[0] << " input-file" << endl;
return 1;
}
char* path = argv[1];
ifstream file(path, ios::in|ios::ate);
if(!file) {
cerr << "The file '" << path << "' does not exist" << endl;
return 1;
}
long size = file.tellg();
char* markup = new char[size+1];
file.seekg(0, ios::beg);
file.read(markup, size);
markup[size] = '\0';
file.close();
Textifier tf;
const int markup_len = strlen(markup);
char* plaintext = new char[markup_len+1];
try {
cout << tf.textify(markup, markup_len, plaintext, markup_len) << endl;
}
catch(string err) {
long line;
long column;
tf.find_location(line, column);
cerr << "ERROR (" << path << ":" << line << ":" << column << ") " << err
<< " at: " << tf.get_snippet() << endl;
return 1;
}
delete plaintext;
delete markup;
return 0;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2013-2014 Tomas Dzetkulic
* Copyright (c) 2013-2014 Pavol Rusnak
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// Source:
// https://github.com/trezor/trezor-crypto
#include "bip39.h"
#include "bip39_english.h"
#include "crypto/sha256.h"
#include "random.h"
#include <openssl/evp.h>
SecureString CMnemonic::Generate(int strength)
{
if (strength % 32 || strength < 128 || strength > 256) {
return SecureString();
}
SecureVector data(32);
GetRandBytes(&data[0], 32);
SecureString mnemonic = FromData(data, strength / 8);
return mnemonic;
}
// SecureString CMnemonic::FromData(const uint8_t *data, int len)
SecureString CMnemonic::FromData(const SecureVector& data, int len)
{
if (len % 4 || len < 16 || len > 32) {
return SecureString();
}
SecureVector checksum(32);
CSHA256().Write(&data[0], len).Finalize(&checksum[0]);
// data
SecureVector bits(len);
memcpy(&bits[0], &data[0], len);
// checksum
bits.push_back(checksum[0]);
int mlen = len * 3 / 4;
SecureString mnemonic;
int i, j, idx;
for (i = 0; i < mlen; i++) {
idx = 0;
for (j = 0; j < 11; j++) {
idx <<= 1;
idx += (bits[(i * 11 + j) / 8] & (1 << (7 - ((i * 11 + j) % 8)))) > 0;
}
mnemonic.append(wordlist[idx]);
if (i < mlen - 1) {
mnemonic += ' ';
}
}
return mnemonic;
}
bool CMnemonic::Check(SecureString mnemonic)
{
if (mnemonic.empty()) {
return false;
}
uint32_t nWordCount{};
for (size_t i = 0; i < mnemonic.size(); ++i) {
if (mnemonic[i] == ' ') {
nWordCount++;
}
}
nWordCount++;
// check number of words
if (nWordCount != 12 && nWordCount != 18 && nWordCount != 24) {
return false;
}
SecureString ssCurrentWord;
SecureVector bits(32 + 1);
uint32_t nWordIndex, ki, nBitsCount{};
for (size_t i = 0; i < mnemonic.size(); ++i)
{
ssCurrentWord = "";
while (i + ssCurrentWord.size() < mnemonic.size() && mnemonic[i + ssCurrentWord.size()] != ' ') {
if (ssCurrentWord.size() >= 9) {
return false;
}
ssCurrentWord += mnemonic[i + ssCurrentWord.size()];
}
i += ssCurrentWord.size();
nWordIndex = 0;
for (;;) {
if (!wordlist[nWordIndex]) { // word not found
return false;
}
if (ssCurrentWord == wordlist[nWordIndex]) { // word found on index nWordIndex
for (ki = 0; ki < 11; ki++) {
if (nWordIndex & (1 << (10 - ki))) {
bits[nBitsCount / 8] |= 1 << (7 - (nBitsCount % 8));
}
nBitsCount++;
}
break;
}
nWordIndex++;
}
}
if (nBitsCount != nWordCount * 11) {
return false;
}
bits[32] = bits[nWordCount * 4 / 3];
CSHA256().Write(&bits[0], nWordCount * 4 / 3).Finalize(&bits[0]);
bool fResult = 0;
if (nWordCount == 12) {
fResult = (bits[0] & 0xF0) == (bits[32] & 0xF0); // compare first 4 bits
} else
if (nWordCount == 18) {
fResult = (bits[0] & 0xFC) == (bits[32] & 0xFC); // compare first 6 bits
} else
if (nWordCount == 24) {
fResult = bits[0] == bits[32]; // compare 8 bits
}
return fResult;
}
// passphrase must be at most 256 characters or code may crash
void CMnemonic::ToSeed(SecureString mnemonic, SecureString passphrase, SecureVector& seedRet)
{
SecureString ssSalt = SecureString("mnemonic") + passphrase;
SecureVector vchSalt(ssSalt.begin(), ssSalt.end());
seedRet.resize(64);
// int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
// const unsigned char *salt, int saltlen, int iter,
// const EVP_MD *digest,
// int keylen, unsigned char *out);
PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), &vchSalt[0], vchSalt.size(), 2048, EVP_sha512(), 64, &seedRet[0]);
}
<commit_msg>Use GetStrongRandBytes in CMnemonic::Generate<commit_after>/**
* Copyright (c) 2013-2014 Tomas Dzetkulic
* Copyright (c) 2013-2014 Pavol Rusnak
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// Source:
// https://github.com/trezor/trezor-crypto
#include "bip39.h"
#include "bip39_english.h"
#include "crypto/sha256.h"
#include "random.h"
#include <openssl/evp.h>
SecureString CMnemonic::Generate(int strength)
{
if (strength % 32 || strength < 128 || strength > 256) {
return SecureString();
}
SecureVector data(32);
GetStrongRandBytes(&data[0], 32);
SecureString mnemonic = FromData(data, strength / 8);
return mnemonic;
}
// SecureString CMnemonic::FromData(const uint8_t *data, int len)
SecureString CMnemonic::FromData(const SecureVector& data, int len)
{
if (len % 4 || len < 16 || len > 32) {
return SecureString();
}
SecureVector checksum(32);
CSHA256().Write(&data[0], len).Finalize(&checksum[0]);
// data
SecureVector bits(len);
memcpy(&bits[0], &data[0], len);
// checksum
bits.push_back(checksum[0]);
int mlen = len * 3 / 4;
SecureString mnemonic;
int i, j, idx;
for (i = 0; i < mlen; i++) {
idx = 0;
for (j = 0; j < 11; j++) {
idx <<= 1;
idx += (bits[(i * 11 + j) / 8] & (1 << (7 - ((i * 11 + j) % 8)))) > 0;
}
mnemonic.append(wordlist[idx]);
if (i < mlen - 1) {
mnemonic += ' ';
}
}
return mnemonic;
}
bool CMnemonic::Check(SecureString mnemonic)
{
if (mnemonic.empty()) {
return false;
}
uint32_t nWordCount{};
for (size_t i = 0; i < mnemonic.size(); ++i) {
if (mnemonic[i] == ' ') {
nWordCount++;
}
}
nWordCount++;
// check number of words
if (nWordCount != 12 && nWordCount != 18 && nWordCount != 24) {
return false;
}
SecureString ssCurrentWord;
SecureVector bits(32 + 1);
uint32_t nWordIndex, ki, nBitsCount{};
for (size_t i = 0; i < mnemonic.size(); ++i)
{
ssCurrentWord = "";
while (i + ssCurrentWord.size() < mnemonic.size() && mnemonic[i + ssCurrentWord.size()] != ' ') {
if (ssCurrentWord.size() >= 9) {
return false;
}
ssCurrentWord += mnemonic[i + ssCurrentWord.size()];
}
i += ssCurrentWord.size();
nWordIndex = 0;
for (;;) {
if (!wordlist[nWordIndex]) { // word not found
return false;
}
if (ssCurrentWord == wordlist[nWordIndex]) { // word found on index nWordIndex
for (ki = 0; ki < 11; ki++) {
if (nWordIndex & (1 << (10 - ki))) {
bits[nBitsCount / 8] |= 1 << (7 - (nBitsCount % 8));
}
nBitsCount++;
}
break;
}
nWordIndex++;
}
}
if (nBitsCount != nWordCount * 11) {
return false;
}
bits[32] = bits[nWordCount * 4 / 3];
CSHA256().Write(&bits[0], nWordCount * 4 / 3).Finalize(&bits[0]);
bool fResult = 0;
if (nWordCount == 12) {
fResult = (bits[0] & 0xF0) == (bits[32] & 0xF0); // compare first 4 bits
} else
if (nWordCount == 18) {
fResult = (bits[0] & 0xFC) == (bits[32] & 0xFC); // compare first 6 bits
} else
if (nWordCount == 24) {
fResult = bits[0] == bits[32]; // compare 8 bits
}
return fResult;
}
// passphrase must be at most 256 characters or code may crash
void CMnemonic::ToSeed(SecureString mnemonic, SecureString passphrase, SecureVector& seedRet)
{
SecureString ssSalt = SecureString("mnemonic") + passphrase;
SecureVector vchSalt(ssSalt.begin(), ssSalt.end());
seedRet.resize(64);
// int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
// const unsigned char *salt, int saltlen, int iter,
// const EVP_MD *digest,
// int keylen, unsigned char *out);
PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), &vchSalt[0], vchSalt.size(), 2048, EVP_sha512(), 64, &seedRet[0]);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: types.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 10:40:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TYPES_HXX
#define _TYPES_HXX
#include <tools/ref.hxx>
#include <basobj.hxx>
class SvSlotElementList;
struct SvSlotElement;
/******************** class SvMetaAttribute *****************************/
SV_DECL_REF(SvMetaType)
SV_DECL_REF(SvMetaAttribute)
SV_DECL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *)
class SvMetaAttribute : public SvMetaReference
{
SvMetaTypeRef aType;
SvNumberIdentifier aSlotId;
SvBOOL aAutomation;
SvBOOL aExport;
SvBOOL aReadonly;
SvBOOL aIsCollection;
SvBOOL aReadOnlyDoc;
SvBOOL aHidden;
BOOL bNewAttr;
protected:
#ifdef IDL_COMPILER
virtual void WriteCSource( SvIdlDataBase & rBase,
SvStream & rOutStm, BOOL bSet );
ULONG MakeSlotValue( SvIdlDataBase & rBase, BOOL bVariable ) const;
virtual void WriteAttributes( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
virtual void ReadAttributesSvIdl( SvIdlDataBase & rBase,
SvTokenStream & rInStm );
virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab );
#endif
public:
SV_DECL_META_FACTORY1( SvMetaAttribute, SvMetaReference, 2 )
SvMetaAttribute();
SvMetaAttribute( SvMetaType * );
void SetNewAttribute( BOOL bNew )
{ bNewAttr = bNew; }
BOOL IsNewAttribute() const
{ return bNewAttr; }
BOOL GetReadonly() const;
void SetSlotId( const SvNumberIdentifier & rId )
{ aSlotId = rId; }
const SvNumberIdentifier & GetSlotId() const;
void SetExport( BOOL bSet )
{ aExport = bSet; }
BOOL GetExport() const;
void SetHidden( BOOL bSet )
{ aHidden = bSet; }
BOOL GetHidden() const;
void SetAutomation( BOOL bSet )
{ aAutomation = bSet; }
BOOL GetAutomation() const;
void SetIsCollection( BOOL bSet )
{ aIsCollection = bSet; }
BOOL GetIsCollection() const;
void SetReadOnlyDoc( BOOL bSet )
{ aReadOnlyDoc = bSet; }
BOOL GetReadOnlyDoc() const;
void SetType( SvMetaType * pT ) { aType = pT; }
SvMetaType * GetType() const;
virtual BOOL IsMethod() const;
virtual BOOL IsVariable() const;
virtual ByteString GetMangleName( BOOL bVariable ) const;
// void FillSbxObject( SbxInfo * pInfo, USHORT nSbxFlags = 0 );
// virtual void FillSbxObject( SvIdlDataBase & rBase, SbxObject * pObj, BOOL bVariable );
#ifdef IDL_COMPILER
virtual BOOL Test( SvIdlDataBase &, SvTokenStream & rInStm );
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void WriteParam( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType );
void WriteRecursiv_Impl( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
ULONG MakeSfx( ByteString * pAtrrArray );
virtual void Insert( SvSlotElementList&, const ByteString & rPrefix,
SvIdlDataBase& );
virtual void WriteHelpId( SvIdlDataBase & rBase, SvStream & rOutStm,
Table * pIdTable );
virtual void WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm,
Table * pIdTable );
virtual void WriteCSV( SvIdlDataBase&, SvStream& );
void FillIDTable(Table *pIDTable);
ByteString Compare( SvMetaAttribute *pAttr );
#endif
};
SV_IMPL_REF(SvMetaAttribute)
SV_IMPL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *)
/******************** class SvType *********************************/
enum { CALL_VALUE, CALL_POINTER, CALL_REFERENCE };
enum { TYPE_METHOD, TYPE_STRUCT, TYPE_BASE, TYPE_ENUM, TYPE_UNION,
TYPE_CLASS, TYPE_POINTER };
class SvMetaType : public SvMetaExtern
{
SvBOOL aIn; // Eingangsparameter
SvBOOL aOut; // Returnparameter
Svint aCall0, aCall1;
Svint aSbxDataType;
SvIdentifier aSvName;
SvIdentifier aSbxName;
SvIdentifier aOdlName;
SvIdentifier aCName;
SvIdentifier aBasicPostfix;
SvIdentifier aBasicName;
SvMetaAttributeMemberList * pAttrList;
int nType;
BOOL bIsItem;
BOOL bIsShell;
char cParserChar;
#ifdef IDL_COMPILER
void WriteSfxItem( const ByteString & rItemName, SvIdlDataBase & rBase,
SvStream & rOutStm );
protected:
BOOL ReadNamesSvIdl( SvIdlDataBase & rBase,
SvTokenStream & rInStm );
virtual void ReadAttributesSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm,
USHORT nTab );
virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm,
USHORT nTab,
WriteType, WriteAttribute = 0 );
virtual void WriteAttributes( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
BOOL ReadHeaderSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
void WriteHeaderSvIdl( SvIdlDataBase &, SvStream & rOutStm,
USHORT nTab );
#endif
public:
SV_DECL_META_FACTORY1( SvMetaType, SvMetaExtern, 18 )
SvMetaType();
SvMetaType( const ByteString & rTypeName, char cParserChar,
const ByteString & rCName );
SvMetaType( const ByteString & rTypeName, const ByteString & rSbxName,
const ByteString & rOdlName, char cParserChar,
const ByteString & rCName, const ByteString & rBasicName,
const ByteString & rBasicPostfix/*, SbxDataType nT = SbxEMPTY */);
SvMetaAttributeMemberList & GetAttrList() const;
ULONG GetAttrCount() const
{
return pAttrList ? pAttrList->Count() : 0L;
}
void AppendAttr( SvMetaAttribute * pAttr )
{
GetAttrList().Append( pAttr );
}
void SetType( int nT );
int GetType() const { return nType; }
SvMetaType * GetBaseType() const;
SvMetaType * GetReturnType() const;
BOOL IsItem() const { return bIsItem; }
BOOL IsShell() const { return bIsShell; }
// void SetSbxDataType( SbxDataType nT )
// { aSbxDataType = (int)nT; }
// SbxDataType GetSbxDataType() const;
void SetIn( BOOL b ) { aIn = b; }
BOOL GetIn() const;
void SetOut( BOOL b ) { aOut = b; }
BOOL GetOut() const;
void SetCall0( int e );
int GetCall0() const;
void SetCall1( int e);
int GetCall1() const;
void SetBasicName(const ByteString& rName)
{ aBasicName = rName; }
const ByteString & GetBasicName() const;
ByteString GetBasicPostfix() const;
const ByteString & GetSvName() const;
const ByteString & GetSbxName() const;
const ByteString & GetOdlName() const;
const ByteString & GetCName() const;
char GetParserChar() const { return cParserChar; }
virtual BOOL SetName( const ByteString & rName, SvIdlDataBase * = NULL );
// void FillSbxObject( SbxVariable * pObj, BOOL bVariable );
#ifdef IDL_COMPILER
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
ByteString GetCString() const;
void WriteSvIdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
void WriteOdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
void AppendParserString (ByteString &rString);
ULONG MakeSfx( ByteString * pAtrrArray );
virtual void WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm );
//BOOL ReadTypePrefix( SvIdlDataBase &, SvTokenStream & rInStm );
BOOL ReadMethodArgs( SvIdlDataBase & rBase,
SvTokenStream & rInStm );
void WriteTypePrefix( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType );
void WriteMethodArgs( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType );
void WriteTheType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType );
ByteString GetParserString() const;
void WriteParamNames( SvIdlDataBase & rBase, SvStream & rOutStm,
const ByteString & rChief );
#endif
};
SV_IMPL_REF(SvMetaType)
DECLARE_LIST(SvMetaTypeList,SvMetaType *)
SV_DECL_IMPL_PERSIST_LIST(SvMetaType,SvMetaType *)
/******************** class SvTypeString *********************************/
class SvMetaTypeString : public SvMetaType
{
public:
SV_DECL_META_FACTORY1( SvMetaTypeString, SvMetaType, 19 )
SvMetaTypeString();
};
SV_DECL_IMPL_REF(SvMetaTypeString)
SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeString,SvMetaTypeString *)
/******************** class SvMetaEnumValue **********************************/
class SvMetaEnumValue : public SvMetaName
{
ByteString aEnumValue;
public:
SV_DECL_META_FACTORY1( SvMetaEnumValue, SvMetaName, 20 )
SvMetaEnumValue();
#ifdef IDL_COMPILER
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
#endif
};
SV_DECL_IMPL_REF(SvMetaEnumValue)
SV_DECL_IMPL_PERSIST_LIST(SvMetaEnumValue,SvMetaEnumValue *)
/******************** class SvTypeEnum *********************************/
class SvMetaTypeEnum : public SvMetaType
{
SvMetaEnumValueMemberList aEnumValueList;
ByteString aPrefix;
protected:
#ifdef IDL_COMPILER
virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm,
USHORT nTab );
virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
#endif
public:
SV_DECL_META_FACTORY1( SvMetaTypeEnum, SvMetaType, 21 )
SvMetaTypeEnum();
USHORT GetMaxValue() const;
ULONG Count() const { return aEnumValueList.Count(); }
const ByteString & GetPrefix() const { return aPrefix; }
SvMetaEnumValue * GetObject( ULONG n ) const
{ return aEnumValueList.GetObject( n ); }
#ifdef IDL_COMPILER
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm,
USHORT nTab,
WriteType, WriteAttribute = 0 );
#endif
};
SV_DECL_IMPL_REF(SvMetaTypeEnum)
SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeEnum,SvMetaTypeEnum *)
/******************** class SvTypeVoid ***********************************/
class SvMetaTypevoid : public SvMetaType
{
public:
SV_DECL_META_FACTORY1( SvMetaTypevoid, SvMetaName, 22 )
SvMetaTypevoid();
};
SV_DECL_IMPL_REF(SvMetaTypevoid)
SV_DECL_IMPL_PERSIST_LIST(SvMetaTypevoid,SvMetaTypevoid *)
#endif // _TYPES_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.38); FILE MERGED 2008/03/31 13:34:13 rt 1.3.38.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: types.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _TYPES_HXX
#define _TYPES_HXX
#include <tools/ref.hxx>
#include <basobj.hxx>
class SvSlotElementList;
struct SvSlotElement;
/******************** class SvMetaAttribute *****************************/
SV_DECL_REF(SvMetaType)
SV_DECL_REF(SvMetaAttribute)
SV_DECL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *)
class SvMetaAttribute : public SvMetaReference
{
SvMetaTypeRef aType;
SvNumberIdentifier aSlotId;
SvBOOL aAutomation;
SvBOOL aExport;
SvBOOL aReadonly;
SvBOOL aIsCollection;
SvBOOL aReadOnlyDoc;
SvBOOL aHidden;
BOOL bNewAttr;
protected:
#ifdef IDL_COMPILER
virtual void WriteCSource( SvIdlDataBase & rBase,
SvStream & rOutStm, BOOL bSet );
ULONG MakeSlotValue( SvIdlDataBase & rBase, BOOL bVariable ) const;
virtual void WriteAttributes( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
virtual void ReadAttributesSvIdl( SvIdlDataBase & rBase,
SvTokenStream & rInStm );
virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab );
#endif
public:
SV_DECL_META_FACTORY1( SvMetaAttribute, SvMetaReference, 2 )
SvMetaAttribute();
SvMetaAttribute( SvMetaType * );
void SetNewAttribute( BOOL bNew )
{ bNewAttr = bNew; }
BOOL IsNewAttribute() const
{ return bNewAttr; }
BOOL GetReadonly() const;
void SetSlotId( const SvNumberIdentifier & rId )
{ aSlotId = rId; }
const SvNumberIdentifier & GetSlotId() const;
void SetExport( BOOL bSet )
{ aExport = bSet; }
BOOL GetExport() const;
void SetHidden( BOOL bSet )
{ aHidden = bSet; }
BOOL GetHidden() const;
void SetAutomation( BOOL bSet )
{ aAutomation = bSet; }
BOOL GetAutomation() const;
void SetIsCollection( BOOL bSet )
{ aIsCollection = bSet; }
BOOL GetIsCollection() const;
void SetReadOnlyDoc( BOOL bSet )
{ aReadOnlyDoc = bSet; }
BOOL GetReadOnlyDoc() const;
void SetType( SvMetaType * pT ) { aType = pT; }
SvMetaType * GetType() const;
virtual BOOL IsMethod() const;
virtual BOOL IsVariable() const;
virtual ByteString GetMangleName( BOOL bVariable ) const;
// void FillSbxObject( SbxInfo * pInfo, USHORT nSbxFlags = 0 );
// virtual void FillSbxObject( SvIdlDataBase & rBase, SbxObject * pObj, BOOL bVariable );
#ifdef IDL_COMPILER
virtual BOOL Test( SvIdlDataBase &, SvTokenStream & rInStm );
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void WriteParam( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType );
void WriteRecursiv_Impl( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
ULONG MakeSfx( ByteString * pAtrrArray );
virtual void Insert( SvSlotElementList&, const ByteString & rPrefix,
SvIdlDataBase& );
virtual void WriteHelpId( SvIdlDataBase & rBase, SvStream & rOutStm,
Table * pIdTable );
virtual void WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm,
Table * pIdTable );
virtual void WriteCSV( SvIdlDataBase&, SvStream& );
void FillIDTable(Table *pIDTable);
ByteString Compare( SvMetaAttribute *pAttr );
#endif
};
SV_IMPL_REF(SvMetaAttribute)
SV_IMPL_PERSIST_LIST(SvMetaAttribute,SvMetaAttribute *)
/******************** class SvType *********************************/
enum { CALL_VALUE, CALL_POINTER, CALL_REFERENCE };
enum { TYPE_METHOD, TYPE_STRUCT, TYPE_BASE, TYPE_ENUM, TYPE_UNION,
TYPE_CLASS, TYPE_POINTER };
class SvMetaType : public SvMetaExtern
{
SvBOOL aIn; // Eingangsparameter
SvBOOL aOut; // Returnparameter
Svint aCall0, aCall1;
Svint aSbxDataType;
SvIdentifier aSvName;
SvIdentifier aSbxName;
SvIdentifier aOdlName;
SvIdentifier aCName;
SvIdentifier aBasicPostfix;
SvIdentifier aBasicName;
SvMetaAttributeMemberList * pAttrList;
int nType;
BOOL bIsItem;
BOOL bIsShell;
char cParserChar;
#ifdef IDL_COMPILER
void WriteSfxItem( const ByteString & rItemName, SvIdlDataBase & rBase,
SvStream & rOutStm );
protected:
BOOL ReadNamesSvIdl( SvIdlDataBase & rBase,
SvTokenStream & rInStm );
virtual void ReadAttributesSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteAttributesSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm,
USHORT nTab );
virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm,
USHORT nTab,
WriteType, WriteAttribute = 0 );
virtual void WriteAttributes( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
BOOL ReadHeaderSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
void WriteHeaderSvIdl( SvIdlDataBase &, SvStream & rOutStm,
USHORT nTab );
#endif
public:
SV_DECL_META_FACTORY1( SvMetaType, SvMetaExtern, 18 )
SvMetaType();
SvMetaType( const ByteString & rTypeName, char cParserChar,
const ByteString & rCName );
SvMetaType( const ByteString & rTypeName, const ByteString & rSbxName,
const ByteString & rOdlName, char cParserChar,
const ByteString & rCName, const ByteString & rBasicName,
const ByteString & rBasicPostfix/*, SbxDataType nT = SbxEMPTY */);
SvMetaAttributeMemberList & GetAttrList() const;
ULONG GetAttrCount() const
{
return pAttrList ? pAttrList->Count() : 0L;
}
void AppendAttr( SvMetaAttribute * pAttr )
{
GetAttrList().Append( pAttr );
}
void SetType( int nT );
int GetType() const { return nType; }
SvMetaType * GetBaseType() const;
SvMetaType * GetReturnType() const;
BOOL IsItem() const { return bIsItem; }
BOOL IsShell() const { return bIsShell; }
// void SetSbxDataType( SbxDataType nT )
// { aSbxDataType = (int)nT; }
// SbxDataType GetSbxDataType() const;
void SetIn( BOOL b ) { aIn = b; }
BOOL GetIn() const;
void SetOut( BOOL b ) { aOut = b; }
BOOL GetOut() const;
void SetCall0( int e );
int GetCall0() const;
void SetCall1( int e);
int GetCall1() const;
void SetBasicName(const ByteString& rName)
{ aBasicName = rName; }
const ByteString & GetBasicName() const;
ByteString GetBasicPostfix() const;
const ByteString & GetSvName() const;
const ByteString & GetSbxName() const;
const ByteString & GetOdlName() const;
const ByteString & GetCName() const;
char GetParserChar() const { return cParserChar; }
virtual BOOL SetName( const ByteString & rName, SvIdlDataBase * = NULL );
// void FillSbxObject( SbxVariable * pObj, BOOL bVariable );
#ifdef IDL_COMPILER
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase,
SvStream & rOutStm, USHORT nTab );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
ByteString GetCString() const;
void WriteSvIdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
void WriteOdlType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
void AppendParserString (ByteString &rString);
ULONG MakeSfx( ByteString * pAtrrArray );
virtual void WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm );
//BOOL ReadTypePrefix( SvIdlDataBase &, SvTokenStream & rInStm );
BOOL ReadMethodArgs( SvIdlDataBase & rBase,
SvTokenStream & rInStm );
void WriteTypePrefix( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType );
void WriteMethodArgs( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType );
void WriteTheType( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab, WriteType );
ByteString GetParserString() const;
void WriteParamNames( SvIdlDataBase & rBase, SvStream & rOutStm,
const ByteString & rChief );
#endif
};
SV_IMPL_REF(SvMetaType)
DECLARE_LIST(SvMetaTypeList,SvMetaType *)
SV_DECL_IMPL_PERSIST_LIST(SvMetaType,SvMetaType *)
/******************** class SvTypeString *********************************/
class SvMetaTypeString : public SvMetaType
{
public:
SV_DECL_META_FACTORY1( SvMetaTypeString, SvMetaType, 19 )
SvMetaTypeString();
};
SV_DECL_IMPL_REF(SvMetaTypeString)
SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeString,SvMetaTypeString *)
/******************** class SvMetaEnumValue **********************************/
class SvMetaEnumValue : public SvMetaName
{
ByteString aEnumValue;
public:
SV_DECL_META_FACTORY1( SvMetaEnumValue, SvMetaName, 20 )
SvMetaEnumValue();
#ifdef IDL_COMPILER
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
#endif
};
SV_DECL_IMPL_REF(SvMetaEnumValue)
SV_DECL_IMPL_PERSIST_LIST(SvMetaEnumValue,SvMetaEnumValue *)
/******************** class SvTypeEnum *********************************/
class SvMetaTypeEnum : public SvMetaType
{
SvMetaEnumValueMemberList aEnumValueList;
ByteString aPrefix;
protected:
#ifdef IDL_COMPILER
virtual void ReadContextSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteContextSvIdl( SvIdlDataBase &, SvStream & rOutStm,
USHORT nTab );
virtual void WriteContext( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab,
WriteType, WriteAttribute = 0 );
#endif
public:
SV_DECL_META_FACTORY1( SvMetaTypeEnum, SvMetaType, 21 )
SvMetaTypeEnum();
USHORT GetMaxValue() const;
ULONG Count() const { return aEnumValueList.Count(); }
const ByteString & GetPrefix() const { return aPrefix; }
SvMetaEnumValue * GetObject( ULONG n ) const
{ return aEnumValueList.GetObject( n ); }
#ifdef IDL_COMPILER
virtual BOOL ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
virtual void WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, USHORT nTab );
virtual void Write( SvIdlDataBase & rBase, SvStream & rOutStm,
USHORT nTab,
WriteType, WriteAttribute = 0 );
#endif
};
SV_DECL_IMPL_REF(SvMetaTypeEnum)
SV_DECL_IMPL_PERSIST_LIST(SvMetaTypeEnum,SvMetaTypeEnum *)
/******************** class SvTypeVoid ***********************************/
class SvMetaTypevoid : public SvMetaType
{
public:
SV_DECL_META_FACTORY1( SvMetaTypevoid, SvMetaName, 22 )
SvMetaTypevoid();
};
SV_DECL_IMPL_REF(SvMetaTypevoid)
SV_DECL_IMPL_PERSIST_LIST(SvMetaTypevoid,SvMetaTypevoid *)
#endif // _TYPES_HXX
<|endoftext|> |
<commit_before><commit_msg>Added handling of short (<=4 points) polygons as tri fans and the rest as polygons which are tesselated, to improve load and build time, yet still resselating the large polygons that need it.<commit_after><|endoftext|> |
<commit_before><commit_msg>Skip CopyTextureVariationsTest failing on Ozone<commit_after><|endoftext|> |
<commit_before>#ifndef SHAPE_HPP_
#define SHAPE_HPP_
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include "PointXY.hpp"
class Shape
{
public:
Shape()
{
m_radius = -1;
}
cv::Point getCentroid()
{
std::pair<int,int> centroid;
for(unsigned short i = 0; i < m_point_list.size(); ++i)
{
centroid.first += m_point_list[i].x;
centroid.second += m_point_list[i].y;
}
centroid.first /= m_point_list.size();
centroid.second /= m_point_list.size();
return cv::Point(centroid.second, centroid.first);
}
std::string get_semantic_shape()
{
std::string shape_name_ = "unk";
unsigned int v_ = m_vertices.size();
if (m_radius > 0)
shape_name_ = "circle";
if (v_ == 3)
shape_name_ = "triangle";
else if (v_ == 4)
shape_name_ = "square";
else if (v_ == 5)
shape_name_ = "pentagon";
else if (v_ == 6)
shape_name_ = "hexagon";
else if (v_ == 12)
shape_name_ = "star";
return shape_name_;
}
std::string getSemanticAverageColorHSV()
{
PointXY point_ = getAverageColor();
return point_.getSemanticColorHSV();
}
std::string getSemanticAverageColorLAB()
{
PointXY point_ = getAverageColor();
return point_.getSemanticColorLAB();
}
PointXY getAverageColor()
{
PointXY color_avg_;
for(unsigned short i = 0; i < m_point_list.size(); ++i)
{
color_avg_.values[0] += m_point_list[i].values[0];
color_avg_.values[1] += m_point_list[i].values[1];
color_avg_.values[2] += m_point_list[i].values[2];
}
color_avg_.values[0] /= m_point_list.size();
color_avg_.values[1] /= m_point_list.size();
color_avg_.values[2] /= m_point_list.size();
return color_avg_;
}
void set_radius(const int & crRadius)
{
m_radius = crRadius;
}
void add_point(PointXY point)
{
m_point_list.push_back(point);
}
void add_vertex (const cv::Point & crVertex)
{
m_vertices.push_back(crVertex);
}
void draw_contour (cv::Mat & rImage, const cv::Scalar & crColor)
{
if (m_radius > 0.0)
{
cv::circle(rImage, m_vertices[0], 3, crColor, -1, 8, 0 );
cv::circle(rImage, m_vertices[0], m_radius, crColor, 3, 8, 0);
}
else
{
for (unsigned int i = 0; i < m_vertices.size()-1; ++i)
{
cv::line(rImage, m_vertices[i], m_vertices[i+1], crColor, 10);
}
if (m_vertices.size() > 2)
cv::line(rImage, m_vertices[m_vertices.size()-1], m_vertices[0], crColor, 10);
}
}
void draw_name (cv::Mat & rImage, const cv::Scalar & crColor)
{
cv::putText(rImage, get_semantic_shape(), m_vertices[0], cv::FONT_HERSHEY_SIMPLEX, 5, crColor, 5);
}
private:
std::vector<PointXY> m_point_list;
std::vector<cv::Point> m_vertices;
int m_radius;
};
#endif
<commit_msg>add shape postprocessing routine<commit_after>#ifndef SHAPE_HPP_
#define SHAPE_HPP_
#include <iostream>
#include <cmath>
#include <vector>
#include <opencv2/opencv.hpp>
#include "PointXY.hpp"
class Shape
{
public:
Shape()
{
m_radius = -1;
}
cv::Point getCentroid()
{
std::pair<int,int> centroid;
for(unsigned short i = 0; i < m_point_list.size(); ++i)
{
centroid.first += m_point_list[i].x;
centroid.second += m_point_list[i].y;
}
centroid.first /= m_point_list.size();
centroid.second /= m_point_list.size();
return cv::Point(centroid.second, centroid.first);
}
cv::Point get_vertex_centroid()
{
cv::Point centroid_;
centroid_.x = 0;
centroid_.y = 0;
for (cv::Point p_: m_vertices)
{
centroid_.x += p_.x;
centroid_.y += p_.y;
}
centroid_.x /= m_vertices.size();
centroid_.y /= m_vertices.size();
return centroid_;
}
std::string get_semantic_shape()
{
std::string shape_name_ = "unk";
unsigned int v_ = m_vertices.size();
if (m_radius > 0)
shape_name_ = "circle";
if (v_ == 3)
shape_name_ = "triangle";
else if (v_ == 4)
shape_name_ = "square";
else if (v_ == 5)
shape_name_ = "pentagon";
else if (v_ == 6)
shape_name_ = "hexagon";
else if (v_ == 12)
shape_name_ = "star";
return shape_name_;
}
std::string getSemanticAverageColorHSV()
{
PointXY point_ = getAverageColor();
return point_.getSemanticColorHSV();
}
std::string getSemanticAverageColorLAB()
{
PointXY point_ = getAverageColor();
return point_.getSemanticColorLAB();
}
PointXY getAverageColor()
{
PointXY color_avg_;
for(unsigned short i = 0; i < m_point_list.size(); ++i)
{
color_avg_.values[0] += m_point_list[i].values[0];
color_avg_.values[1] += m_point_list[i].values[1];
color_avg_.values[2] += m_point_list[i].values[2];
}
color_avg_.values[0] /= m_point_list.size();
color_avg_.values[1] /= m_point_list.size();
color_avg_.values[2] /= m_point_list.size();
return color_avg_;
}
void set_radius(const int & crRadius)
{
m_radius = crRadius;
}
void add_point(PointXY point)
{
m_point_list.push_back(point);
}
void add_vertex (const cv::Point & crVertex)
{
m_vertices.push_back(crVertex);
}
void postprocess ()
{
// Not a circle
if (m_radius < 0 && m_vertices.size() <= 6)
{
float avg_side_ = 0.0f;
for (unsigned int i = 0; i < m_vertices.size(); ++i)
{
unsigned int j = (i == m_vertices.size() - 1) ? 0 : i+1;
avg_side_ = std::max((float)cv::norm(m_vertices[i]-m_vertices[j]), avg_side_);
}
for (unsigned int i = 0; i < m_vertices.size(); ++i)
{
unsigned int j = (i == m_vertices.size() - 1) ? 0 : i+1;
float side_ = cv::norm(m_vertices[i]-m_vertices[j]);
if (std::abs(avg_side_ - side_) > avg_side_ * 0.5f)
{
m_vertices.erase(m_vertices.begin()+i);
i--;
}
}
m_area = cv::contourArea(m_vertices);
}
}
void draw_contour (cv::Mat & rImage, const cv::Scalar & crColor)
{
if (m_radius > 0.0)
{
cv::circle(rImage, m_vertices[0], 3, crColor, -1, 8, 0 );
cv::circle(rImage, m_vertices[0], m_radius, crColor, 3, 8, 0);
}
else
{
for (unsigned int i = 0; i < m_vertices.size()-1; ++i)
{
cv::line(rImage, m_vertices[i], m_vertices[i+1], crColor, 10);
}
if (m_vertices.size() > 2)
cv::line(rImage, m_vertices[m_vertices.size()-1], m_vertices[0], crColor, 10);
cv::circle(rImage, get_vertex_centroid(), 3, crColor, -1, 8, 0);
}
}
void draw_name (cv::Mat & rImage, const cv::Scalar & crColor)
{
cv::putText(rImage, get_semantic_shape() + ":" + std::to_string(m_area),
get_vertex_centroid(), cv::FONT_HERSHEY_SIMPLEX, 3, crColor, 5);
}
private:
std::vector<PointXY> m_point_list;
std::vector<cv::Point> m_vertices;
int m_radius;
double m_area;
};
#endif
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef UTILS_H
#define UTILS_H
#include <sstream>
namespace eddic {
template <typename T>
T toNumber (const std::string& text) {
std::stringstream ss(text);
T result;
ss >> result;
return result;
}
template <typename T>
const std::string& toString(T number) {
std::stringstream out;
out << number;
return out.str();
}
} //end of eddic
#endif
<commit_msg>Do no return a temporary string by reference<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef UTILS_H
#define UTILS_H
#include <sstream>
namespace eddic {
template <typename T>
T toNumber (const std::string& text) {
std::stringstream ss(text);
T result;
ss >> result;
return result;
}
template <typename T>
std::string toString(T number) {
std::stringstream out;
out << number;
return out.str();
}
} //end of eddic
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more
* contributor license agreements.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <getopt.h>
#include <stdint.h>
#include <sys/time.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <stdexcept>
#include <vector>
#include <openssl/sha.h>
#include <jansson.h>
#include <readosm.h>
#include "throwstream.h"
#include "scoped.h"
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/aerospike_query.h>
#include <aerospike/as_hashmap.h>
#include <aerospike/as_key.h>
#include <aerospike/as_query.h>
#include <aerospike/as_record.h>
using namespace std;
namespace {
// Some things have defaults
char const * DEF_HOST = "localhost";
int const DEF_PORT = 3000;
char const * DEF_NAMESPACE = "test";
char const * DEF_SET = "osm";
string g_host = DEF_HOST;
int g_port = DEF_PORT;
string g_user;
string g_pass;
string g_namespace = DEF_NAMESPACE;
string g_set = DEF_SET;
string g_infile;
char const * g_valbin = "val";
char const * g_locbin = "loc";
char const * g_mapbin = "map";
char const * g_hshbin = "hash";
char const * g_locndx = "osm-loc-index";
size_t g_npoints = 0;
int64_t id_to_hash(int64_t const & id)
{
uint8_t obuf[32];
SHA256((uint8_t *) &id, sizeof(id), obuf);
int64_t hshval;
memcpy((void *) &hshval, obuf, sizeof(hshval));
hshval &= 0x7fffffffffffffff; // Don't be negative
return hshval;
}
int
handle_node(void const * user_data, readosm_node const * node)
{
aerospike * asp = (aerospike *) user_data;
// First scan the tags to see if there is a name.
char const * name = NULL;
for (int ii = 0; ii < node->tag_count; ++ii) {
if (strcmp(node->tags[ii].key, "name") == 0) {
name = node->tags[ii].value;
break;
}
}
if (!name)
return READOSM_OK;
int64_t hshval = id_to_hash(node->id);
size_t ntags = node->tag_count;
// We'll insert all the tags + osmid, lat and long.
as_map * asmap = (as_map *) as_hashmap_new(ntags + 3);
Scoped<json_t *> valobj(json_object(), NULL, json_decref);
for (int ii = 0; ii < node->tag_count; ++ii) {
as_map_set(asmap,
(as_val *) as_string_new((char *) node->tags[ii].key, false),
(as_val *) as_string_new((char *) node->tags[ii].value, false));
json_object_set_new(valobj,
node->tags[ii].key,
json_string(node->tags[ii].value));
}
// Insert osmid
as_map_set(asmap,
(as_val *) as_string_new((char *) "osmid", false),
(as_val *) as_integer_new(node->id));
json_object_set_new(valobj, "osmid", json_real(node->id));
// Insert latitude and longitude
as_map_set(asmap,
(as_val *) as_string_new((char *) "latitude", false),
(as_val *) as_double_new(node->latitude));
as_map_set(asmap,
(as_val *) as_string_new((char *) "longitude", false),
(as_val *) as_double_new(node->longitude));
json_object_set_new(valobj, "latitude", json_real(node->latitude));
json_object_set_new(valobj, "longitude", json_real(node->longitude));
Scoped<char *> valstr(json_dumps(valobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
// cout << valstr << endl;
// Construct the GeoJSON loc bin value.
Scoped<json_t *> locobj(json_object(), NULL, json_decref);
json_object_set_new(locobj, "type", json_string("Point"));
Scoped<json_t *> coordobj(json_array(), NULL, json_decref);
json_array_append_new(coordobj, json_real(node->longitude));
json_array_append_new(coordobj, json_real(node->latitude));
json_object_set(locobj, "coordinates", coordobj);
Scoped<char *> locstr(json_dumps(locobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
as_key key;
as_key_init_int64(&key, g_namespace.c_str(), g_set.c_str(), node->id);
uint16_t nbins = 4;
as_record rec;
as_record_inita(&rec, nbins);
as_record_set_geojson_str(&rec, g_locbin, locstr);
as_record_set_str(&rec, g_valbin, valstr);
as_record_set_map(&rec, g_mapbin, asmap);
as_record_set_int64(&rec, g_hshbin, hshval);
as_error err;
as_status rv = aerospike_key_put(asp, &err, NULL, &key, &rec);
as_record_destroy(&rec);
as_key_destroy(&key);
if (rv != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_key_put failed: "
<< err.code << " - " << err.message);
++g_npoints;
if (g_npoints % 1000 == 0)
cerr << '.';
// cout << json_dumps(rootobj, JSON_COMPACT) << endl;
return READOSM_OK;
}
uint64_t
now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * (uint64_t) 1000000) + tv.tv_usec;
}
void
setup_aerospike(aerospike * asp)
{
as_config cfg;
as_config_init(&cfg);
as_config_add_host(&cfg, g_host.c_str(), g_port);
if (! g_user.empty())
as_config_set_user(&cfg, g_user.c_str(), g_pass.c_str());
aerospike_init(asp, &cfg);
as_error err;
if (aerospike_connect(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_connect failed: "
<< err.code << " - " << err.message);
}
void
create_indexes(aerospike * asp)
{
{
as_error err;
as_index_task task;
if (aerospike_index_create(asp, &err, &task, NULL,
g_namespace.c_str(), g_set.c_str(),
g_locbin, g_locndx,
AS_INDEX_GEO2DSPHERE) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_index_create() returned "
<< err.code << " - " << err.message);
// Wait for the system metadata to spread to all nodes.
aerospike_index_create_wait(&err, &task, 0);
}
}
void
cleanup_aerospike(aerospike * asp)
{
as_error err;
if (aerospike_close(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_close failed: "
<< err.code << " - " << err.message);
aerospike_destroy(asp);
}
void
usage(int & argc, char ** & argv)
{
cerr << "usage: " << argv[0] << " [options] <infile>" << endl
<< " options:" << endl
<< " -u, --usage display usage" << endl
<< " -h, --host=HOST database host [" << DEF_HOST << "]" << endl
<< " -p, --port=PORT database port [" << DEF_PORT << "]" << endl
<< " -U, --user=USER username [<none>]" << endl
<< " -P, --password=PASSWORD password [<none>]" << endl
<< " -n, --namespace=NAMESPACE query namespace [" << DEF_NAMESPACE << "]" << endl
<< " -s, --set=SET query set [" << DEF_SET << "]" << endl
;
}
void
parse_arguments(int & argc, char ** & argv)
{
char * endp;
static struct option long_options[] =
{
{"usage", no_argument, 0, 'u'},
{"host", required_argument, 0, 'h'},
{"port", required_argument, 0, 'p'},
{"user", required_argument, 0, 'U'},
{"password", required_argument, 0, 'P'},
{"namespace", required_argument, 0, 'n'},
{"set", required_argument, 0, 's'},
{0, 0, 0, 0}
};
while (true)
{
int optndx = 0;
int opt = getopt_long(argc, argv, "uh:p:U:P:n:s:",
long_options, &optndx);
// Are we done processing arguments?
if (opt == -1)
break;
switch (opt) {
case 'u':
usage(argc, argv);
exit(0);
break;
case 'h':
g_host = optarg;
break;
case 'p':
g_port = strtol(optarg, &endp, 0);
if (*endp != '\0')
throwstream(runtime_error, "invalid port value: " << optarg);
break;
case 'U':
g_user = optarg;
break;
case 'P':
g_pass = optarg;
break;
case 'n':
g_namespace = optarg;
break;
case 's':
g_set = optarg;
break;
case'?':
// getopt_long already printed an error message
usage(argc, argv);
exit(1);
break;
default:
throwstream(runtime_error, "unexpected option: " << char(opt));
break;
}
}
if (optind >= argc)
throwstream(runtime_error, "missing input-file argument");
g_infile = argv[optind];
}
int
run(int & argc, char ** & argv)
{
parse_arguments(argc, argv);
const void * osm_handle;
int ret;
ret = readosm_open (g_infile.c_str(), &osm_handle);
if (ret != READOSM_OK)
throwstream(runtime_error, "OPEN error: " << ret);
Scoped<void const *> osm(osm_handle, NULL,
(void (*)(const void*)) readosm_close);
uint64_t t0 = now();
aerospike as;
Scoped<aerospike *> asp(&as, NULL, cleanup_aerospike);
setup_aerospike(asp);
create_indexes(asp);
ret = readosm_parse(osm_handle,
(const void *) asp,
handle_node,
NULL,
NULL);
if (ret != READOSM_OK)
throwstream(runtime_error, "PARSE error: " << ret);
uint64_t t1 = now();
cerr << endl;
cerr << "Loaded " << dec << g_npoints << " points"
<< " in " << ((t1 - t0) / 1e6) << " seconds" << endl;
return 0;
}
} // end namespace
int
main(int argc, char ** argv)
{
try
{
return run(argc, argv);
}
catch (exception const & ex)
{
cerr << "EXCEPTION: " << ex.what() << endl;
return 1;
}
}
<commit_msg>osm_load/cplusplus: made index names contain selected set name, added hash index<commit_after>/*
* Copyright 2015 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more
* contributor license agreements.
*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <getopt.h>
#include <stdint.h>
#include <sys/time.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <stdexcept>
#include <vector>
#include <openssl/sha.h>
#include <jansson.h>
#include <readosm.h>
#include "throwstream.h"
#include "scoped.h"
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/aerospike_query.h>
#include <aerospike/as_hashmap.h>
#include <aerospike/as_key.h>
#include <aerospike/as_query.h>
#include <aerospike/as_record.h>
using namespace std;
namespace {
// Some things have defaults
char const * DEF_HOST = "localhost";
int const DEF_PORT = 3000;
char const * DEF_NAMESPACE = "test";
char const * DEF_SET = "osm";
string g_host = DEF_HOST;
int g_port = DEF_PORT;
string g_user;
string g_pass;
string g_namespace = DEF_NAMESPACE;
string g_set = DEF_SET;
string g_infile;
char const * g_valbin = "val";
char const * g_locbin = "loc";
char const * g_mapbin = "map";
char const * g_hshbin = "hash";
string g_locndx;
string g_hshndx;
size_t g_npoints = 0;
int64_t id_to_hash(int64_t const & id)
{
uint8_t obuf[32];
SHA256((uint8_t *) &id, sizeof(id), obuf);
int64_t hshval;
memcpy((void *) &hshval, obuf, sizeof(hshval));
hshval &= 0x7fffffffffffffff; // Don't be negative
return hshval;
}
int
handle_node(void const * user_data, readosm_node const * node)
{
aerospike * asp = (aerospike *) user_data;
// First scan the tags to see if there is a name.
char const * name = NULL;
for (int ii = 0; ii < node->tag_count; ++ii) {
if (strcmp(node->tags[ii].key, "name") == 0) {
name = node->tags[ii].value;
break;
}
}
if (!name)
return READOSM_OK;
int64_t hshval = id_to_hash(node->id);
size_t ntags = node->tag_count;
// We'll insert all the tags + osmid, lat and long.
as_map * asmap = (as_map *) as_hashmap_new(ntags + 3);
Scoped<json_t *> valobj(json_object(), NULL, json_decref);
for (int ii = 0; ii < node->tag_count; ++ii) {
as_map_set(asmap,
(as_val *) as_string_new((char *) node->tags[ii].key, false),
(as_val *) as_string_new((char *) node->tags[ii].value, false));
json_object_set_new(valobj,
node->tags[ii].key,
json_string(node->tags[ii].value));
}
// Insert osmid
as_map_set(asmap,
(as_val *) as_string_new((char *) "osmid", false),
(as_val *) as_integer_new(node->id));
json_object_set_new(valobj, "osmid", json_real(node->id));
// Insert latitude and longitude
as_map_set(asmap,
(as_val *) as_string_new((char *) "latitude", false),
(as_val *) as_double_new(node->latitude));
as_map_set(asmap,
(as_val *) as_string_new((char *) "longitude", false),
(as_val *) as_double_new(node->longitude));
json_object_set_new(valobj, "latitude", json_real(node->latitude));
json_object_set_new(valobj, "longitude", json_real(node->longitude));
Scoped<char *> valstr(json_dumps(valobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
// cout << valstr << endl;
// Construct the GeoJSON loc bin value.
Scoped<json_t *> locobj(json_object(), NULL, json_decref);
json_object_set_new(locobj, "type", json_string("Point"));
Scoped<json_t *> coordobj(json_array(), NULL, json_decref);
json_array_append_new(coordobj, json_real(node->longitude));
json_array_append_new(coordobj, json_real(node->latitude));
json_object_set(locobj, "coordinates", coordobj);
Scoped<char *> locstr(json_dumps(locobj, JSON_COMPACT), NULL,
(void (*)(char*)) free);
as_key key;
as_key_init_int64(&key, g_namespace.c_str(), g_set.c_str(), node->id);
uint16_t nbins = 4;
as_record rec;
as_record_inita(&rec, nbins);
as_record_set_geojson_str(&rec, g_locbin, locstr);
as_record_set_str(&rec, g_valbin, valstr);
as_record_set_map(&rec, g_mapbin, asmap);
as_record_set_int64(&rec, g_hshbin, hshval);
as_error err;
as_status rv = aerospike_key_put(asp, &err, NULL, &key, &rec);
as_record_destroy(&rec);
as_key_destroy(&key);
if (rv != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_key_put failed: "
<< err.code << " - " << err.message);
++g_npoints;
if (g_npoints % 1000 == 0)
cerr << '.';
// cout << json_dumps(rootobj, JSON_COMPACT) << endl;
return READOSM_OK;
}
uint64_t
now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * (uint64_t) 1000000) + tv.tv_usec;
}
void
setup_aerospike(aerospike * asp)
{
as_config cfg;
as_config_init(&cfg);
as_config_add_host(&cfg, g_host.c_str(), g_port);
if (! g_user.empty())
as_config_set_user(&cfg, g_user.c_str(), g_pass.c_str());
aerospike_init(asp, &cfg);
as_error err;
if (aerospike_connect(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_connect failed: "
<< err.code << " - " << err.message);
}
void
create_indexes(aerospike * asp)
{
{
as_error err;
as_index_task task;
if (aerospike_index_create(asp, &err, &task, NULL,
g_namespace.c_str(), g_set.c_str(),
g_locbin, g_locndx.c_str(),
AS_INDEX_GEO2DSPHERE) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_index_create() returned "
<< err.code << " - " << err.message);
// Wait for the system metadata to spread to all nodes.
aerospike_index_create_wait(&err, &task, 0);
}
{
as_error err;
as_index_task task;
if (aerospike_index_create(asp, &err, &task, NULL,
g_namespace.c_str(), g_set.c_str(),
g_hshbin, g_hshndx.c_str(),
AS_INDEX_NUMERIC) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_index_create() returned "
<< err.code << " - " << err.message);
// Wait for the system metadata to spread to all nodes.
aerospike_index_create_wait(&err, &task, 0);
}
}
void
cleanup_aerospike(aerospike * asp)
{
as_error err;
if (aerospike_close(asp, &err) != AEROSPIKE_OK)
throwstream(runtime_error, "aerospike_close failed: "
<< err.code << " - " << err.message);
aerospike_destroy(asp);
}
void
usage(int & argc, char ** & argv)
{
cerr << "usage: " << argv[0] << " [options] <infile>" << endl
<< " options:" << endl
<< " -u, --usage display usage" << endl
<< " -h, --host=HOST database host [" << DEF_HOST << "]" << endl
<< " -p, --port=PORT database port [" << DEF_PORT << "]" << endl
<< " -U, --user=USER username [<none>]" << endl
<< " -P, --password=PASSWORD password [<none>]" << endl
<< " -n, --namespace=NAMESPACE query namespace [" << DEF_NAMESPACE << "]" << endl
<< " -s, --set=SET query set [" << DEF_SET << "]" << endl
;
}
void
parse_arguments(int & argc, char ** & argv)
{
char * endp;
static struct option long_options[] =
{
{"usage", no_argument, 0, 'u'},
{"host", required_argument, 0, 'h'},
{"port", required_argument, 0, 'p'},
{"user", required_argument, 0, 'U'},
{"password", required_argument, 0, 'P'},
{"namespace", required_argument, 0, 'n'},
{"set", required_argument, 0, 's'},
{0, 0, 0, 0}
};
while (true)
{
int optndx = 0;
int opt = getopt_long(argc, argv, "uh:p:U:P:n:s:",
long_options, &optndx);
// Are we done processing arguments?
if (opt == -1)
break;
switch (opt) {
case 'u':
usage(argc, argv);
exit(0);
break;
case 'h':
g_host = optarg;
break;
case 'p':
g_port = strtol(optarg, &endp, 0);
if (*endp != '\0')
throwstream(runtime_error, "invalid port value: " << optarg);
break;
case 'U':
g_user = optarg;
break;
case 'P':
g_pass = optarg;
break;
case 'n':
g_namespace = optarg;
break;
case 's':
g_set = optarg;
break;
case'?':
// getopt_long already printed an error message
usage(argc, argv);
exit(1);
break;
default:
throwstream(runtime_error, "unexpected option: " << char(opt));
break;
}
}
if (optind >= argc)
throwstream(runtime_error, "missing input-file argument");
g_infile = argv[optind];
// Make the index names contain the selected set name
g_locndx = g_set + "-loc-index";
g_hshndx = g_set + "-hsh-index";
}
int
run(int & argc, char ** & argv)
{
parse_arguments(argc, argv);
const void * osm_handle;
int ret;
ret = readosm_open (g_infile.c_str(), &osm_handle);
if (ret != READOSM_OK)
throwstream(runtime_error, "OPEN error: " << ret);
Scoped<void const *> osm(osm_handle, NULL,
(void (*)(const void*)) readosm_close);
uint64_t t0 = now();
aerospike as;
Scoped<aerospike *> asp(&as, NULL, cleanup_aerospike);
setup_aerospike(asp);
create_indexes(asp);
ret = readosm_parse(osm_handle,
(const void *) asp,
handle_node,
NULL,
NULL);
if (ret != READOSM_OK)
throwstream(runtime_error, "PARSE error: " << ret);
uint64_t t1 = now();
cerr << endl;
cerr << "Loaded " << dec << g_npoints << " points"
<< " in " << ((t1 - t0) / 1e6) << " seconds" << endl;
return 0;
}
} // end namespace
int
main(int argc, char ** argv)
{
try
{
return run(argc, argv);
}
catch (exception const & ex)
{
cerr << "EXCEPTION: " << ex.what() << endl;
return 1;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.