text
stringlengths 54
60.6k
|
---|
<commit_before>#include "dream_hacking/calculator.h"
logxx::Log cLog("main");
void PrintDeck(const std::shared_ptr<Medici> deck, std::ostream& s){
S_LOG("PrintDeck");
auto cardsDeck = deck->GetDeck();
auto collapses = deck->GetCollapses();
// auto &mobiles = deck->GetMobiles();
auto &stationars = deck->GetStationars();
s << "<";
for (auto it = cardsDeck.begin(); it != cardsDeck.end(); ++it){
const PlayingCard &card = *it;
std::string cardText = card.Print(true);
if (stationars.find(card) != stationars.end()){
s << "[" << cardText << "]";
} else
s << cardText;
if (collapses.find(card) != collapses.end() && it + 1 != cardsDeck.end())
s << "> <";
else if (it + 1 != cardsDeck.end())
s << " ";
}
s << ">\n";
//std::map<PlayingCard, unsigned int>
for (auto it= collapses.begin(); it != collapses.end(); ++it){
s << it->first.Print(true) << ": " << it->second << "\n";
}
}
int main(int argc, char** argv) {
S_LOG("main");
using namespace dream_hacking;
logxx::GlobalLogLevel(logxx::warning);
PlayingCard targetCard{PlayingCard::Ten, PlayingCard::Hearts};
ExistentialRangeSelector target(19, 24);
target.AddCard(targetCard);
UniversalRangeSelector ownActions(3, 7);
//ownActions.AddCard({PlayingCard::Ace, true});
ownActions.AddCard({PlayingCard::Six});
ownActions.AddCard({PlayingCard::Seven});
ownActions.AddCard({PlayingCard::Nine});
ownActions.AddCard({PlayingCard::Jack});
ownActions.AddCard({PlayingCard::Queen});
ExistentialRangeSelector firstCard(0, 0);
firstCard.AddCard({PlayingCard::Jack});
ExistentialRangeSelector secondCard(1, 1);
secondCard.AddCard({PlayingCard::Nine});
ExistentialRangeSelector thirdCard(2, 2);
thirdCard.AddCard({PlayingCard::Ace});
thirdCard.AddCard({PlayingCard::Ten});
ComplexRangeSelector conditions;
conditions.AddRangeSelectors(target, ownActions, firstCard, secondCard, thirdCard);
Calculator calc(conditions);
time_t timeLimit = 15;
if (argc > 1)
timeLimit = std::atoi(argv[1]);
if (argc > 2)
calc.SetThreads(std::atoi(argv[2]));
std::shared_ptr<Medici> deck = calc.Calculate(timeLimit, [&targetCard](const std::shared_ptr<Medici>& d) -> unsigned int {
return d->GetCollapses(targetCard);
});
log(logxx::info) << "Performance: " << (unsigned long long int)calc.GetLastPerformance() << " decks per second" << logxx::endl;
if (!deck){
log(logxx::error) << "No sequences found" << logxx::endl;
return 1;
} else {
auto &s = log(logxx::info);
deck->Collapse(true);
PrintDeck(deck, s);
s << logxx::endl;
return 0;
}
}
<commit_msg>Added i-ching to main program<commit_after>#include "dream_hacking/calculator.h"
#include "dream_hacking/i-ching/i_ching.h"
logxx::Log cLog("main");
void PrintDeck(const std::shared_ptr<Medici> deck, std::ostream& s){
S_LOG("PrintDeck");
auto cardsDeck = deck->GetDeck();
auto collapses = deck->GetCollapses();
// auto &mobiles = deck->GetMobiles();
auto &stationars = deck->GetStationars();
s << "<";
for (auto it = cardsDeck.begin(); it != cardsDeck.end(); ++it){
const PlayingCard &card = *it;
std::string cardText = card.Print(true);
if (stationars.find(card) != stationars.end()){
s << "[" << cardText << "]";
} else
s << cardText;
if (collapses.find(card) != collapses.end() && it + 1 != cardsDeck.end())
s << "> <";
else if (it + 1 != cardsDeck.end())
s << " ";
}
s << ">\n";
//std::map<PlayingCard, unsigned int>
for (auto it= collapses.begin(); it != collapses.end(); ++it){
s << it->first.Print(true) << ": " << it->second << "\n";
}
}
void PrintIChing(const dream_hacking::IChing& iching){
S_LOG("Print I-Ching");
for (auto &suitHex : iching.hexagrams){
auto &suit = suitHex.first;
auto &hex = suitHex.second;
auto &s = log(logxx::info) << PlayingCard::PrintSuit(suit, false) << "\n";
for (size_t i = 0; i != 6; ++i){
auto& state = hex.at(5 - i);
if (state == SolidLine || state == SolidLineStrong || state == SolidLineWeak)
s << "======";
else
s << "==__==";
if (i != 5)
s << "\n";
}
s << logxx::endl;
}
}
int main(int argc, char** argv) {
S_LOG("main");
using namespace dream_hacking;
logxx::GlobalLogLevel(logxx::warning);
PlayingCard targetCard{PlayingCard::Ten, PlayingCard::Hearts};
ExistentialRangeSelector target(19, 24);
target.AddCard(targetCard);
UniversalRangeSelector ownActions(3, 7);
//ownActions.AddCard({PlayingCard::Ace, true});
ownActions.AddCard({PlayingCard::Six});
ownActions.AddCard({PlayingCard::Seven});
ownActions.AddCard({PlayingCard::Nine});
ownActions.AddCard({PlayingCard::Jack});
ownActions.AddCard({PlayingCard::Queen});
ExistentialRangeSelector firstCard(0, 0);
firstCard.AddCard({PlayingCard::Jack});
ExistentialRangeSelector secondCard(1, 1);
secondCard.AddCard({PlayingCard::Nine});
ExistentialRangeSelector thirdCard(2, 2);
thirdCard.AddCard({PlayingCard::Ace});
thirdCard.AddCard({PlayingCard::Ten});
ComplexRangeSelector conditions;
conditions.AddRangeSelectors(target, ownActions, firstCard, secondCard, thirdCard);
Calculator calc(conditions);
time_t timeLimit = 15;
if (argc > 1)
timeLimit = std::atoi(argv[1]);
if (argc > 2)
calc.SetThreads(std::atoi(argv[2]));
std::shared_ptr<Medici> deck = calc.Calculate(timeLimit, [&targetCard](const std::shared_ptr<Medici>& d) -> unsigned int {
return d->GetCollapses(targetCard);
});
log(logxx::info) << "Performance: " << (unsigned long long int)calc.GetLastPerformance() << " decks per second" << logxx::endl;
if (!deck){
log(logxx::error) << "No sequences found" << logxx::endl;
return 1;
} else {
auto &s = log(logxx::info);
deck->Collapse(true);
PrintDeck(deck, s);
s << logxx::endl;
IChing iching;
iching.LoadFromDeck(*deck.get());
PrintIChing(iching);
return 0;
}
}
<|endoftext|> |
<commit_before>/**
* @file
* TODO: Describe purpose of file.
*
* @author [email protected]
*
* @section LICENSE
* @verbatim
* _ _ _
* ___| (_)___(_) ___ _ __
* / _ \ | / __| |/ _ \| '_ \
* | __/ | \__ \ | (_) | | | |
* \___|_|_|___/_|\___/|_| |_|
* The Elision Term Rewriter
*
* Copyright (c) 2014 by Stacy Prowell ([email protected])
* All rights reserved.
* @endverbatim
*/
#include "BasicLiteral.h"
#include "Term.h"
namespace elision {
namespace term {
namespace basic {
BasicSymbolLiteral::BasicSymbolLiteral(Loc const& loc, std::string const& name,
Term const& type) : BasicTerm(loc, type), name_(name) {}
BasicStringLiteral::BasicStringLiteral(Loc const& loc, std::string const& value,
Term const& type) : BasicTerm(loc, type), value_(value) {}
BasicIntegerLiteral::BasicIntegerLiteral(Loc const& loc, eint_t const& value,
Term const& type) : BasicTerm(loc, type), value_(value) {}
BasicFloatLiteral::BasicFloatLiteral(Loc const& loc, eint_t const& significand,
eint_t const& exponent, uint16_t radix, Term const& type) :
BasicTerm(loc, type), significand_(significand),
exponent_(exponent), radix_(radix) {}
BasicBitStringLiteral::BasicBitStringLiteral(Loc const& loc, eint_t const& bits,
uint16_t length, Term const& type) : BasicTerm(loc, type), bits_(bits),
length_(length) {}
BasicBooleanLiteral::BasicBooleanLiteral(Loc const& loc, bool value,
Term const& type) : BasicTerm(loc, type), value_(value) {}
BasicTermLiteral::BasicTermLiteral(Loc const& loc, Term const& value,
Term const& type) : BasicTerm(loc, type), term_(value) {}
} /* namespace basic */
} /* namespace term */
} /* namespace elision */
<commit_msg>Added missing using directive.<commit_after>/**
* @file
* TODO: Describe purpose of file.
*
* @author [email protected]
*
* @section LICENSE
* @verbatim
* _ _ _
* ___| (_)___(_) ___ _ __
* / _ \ | / __| |/ _ \| '_ \
* | __/ | \__ \ | (_) | | | |
* \___|_|_|___/_|\___/|_| |_|
* The Elision Term Rewriter
*
* Copyright (c) 2014 by Stacy Prowell ([email protected])
* All rights reserved.
* @endverbatim
*/
#include "BasicLiteral.h"
#include "Term.h"
using elision::eint_t;
namespace elision {
namespace term {
namespace basic {
BasicSymbolLiteral::BasicSymbolLiteral(Loc const& loc, std::string const& name,
Term const& type) : BasicTerm(loc, type), name_(name) {}
BasicStringLiteral::BasicStringLiteral(Loc const& loc, std::string const& value,
Term const& type) : BasicTerm(loc, type), value_(value) {}
BasicIntegerLiteral::BasicIntegerLiteral(Loc const& loc, eint_t const& value,
Term const& type) : BasicTerm(loc, type), value_(value) {}
BasicFloatLiteral::BasicFloatLiteral(Loc const& loc, eint_t const& significand,
eint_t const& exponent, uint16_t radix, Term const& type) :
BasicTerm(loc, type), significand_(significand),
exponent_(exponent), radix_(radix) {}
BasicBitStringLiteral::BasicBitStringLiteral(Loc const& loc, eint_t const& bits,
uint16_t length, Term const& type) : BasicTerm(loc, type), bits_(bits),
length_(length) {}
BasicBooleanLiteral::BasicBooleanLiteral(Loc const& loc, bool value,
Term const& type) : BasicTerm(loc, type), value_(value) {}
BasicTermLiteral::BasicTermLiteral(Loc const& loc, Term const& value,
Term const& type) : BasicTerm(loc, type), term_(value) {}
} /* namespace basic */
} /* namespace term */
} /* namespace elision */
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/stringutil.h>
#include <fnord-base/inspect.h>
#include <fnord-json/jsonoutputstream.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
namespace fnord {
namespace json {
JSONOutputStream::JSONOutputStream(
std::shared_ptr<OutputStream> output_stream) :
output_(output_stream) {
}
JSONOutputStream::JSONOutputStream(
std::unique_ptr<OutputStream> output_stream) {
output_.reset(output_stream.release());
}
void JSONOutputStream::write(const JSONObject& obj) {
for (const auto& t : obj) {
emplace_back(t.type, t.data);
}
}
void JSONOutputStream::emplace_back(kTokenType token) {
emplace_back(token, "");
}
void JSONOutputStream::emplace_back(const JSONToken& token) {
emplace_back(token.type, token.data);
}
void JSONOutputStream::emplace_back(
kTokenType token,
const std::string& data) {
switch (token) {
case JSON_ARRAY_END:
endArray();
if (!stack_.empty()) {
stack_.pop();
}
if (!stack_.empty()) {
stack_.top().second++;
}
return;
case JSON_OBJECT_END:
endObject();
if (!stack_.empty()) {
stack_.pop();
}
if (!stack_.empty()) {
stack_.top().second++;
}
return;
default:
break;
}
if (!stack_.empty() && stack_.top().second > 0) {
switch (stack_.top().first) {
case JSON_ARRAY_BEGIN:
addComma();
break;
case JSON_OBJECT_BEGIN:
(stack_.top().second % 2 == 0) ? addComma() : addColon();
break;
default:
break;
}
}
switch (token) {
case JSON_ARRAY_BEGIN:
beginArray();
stack_.emplace(JSON_ARRAY_BEGIN, 0);
break;
case JSON_OBJECT_BEGIN:
beginObject();
stack_.emplace(JSON_OBJECT_BEGIN, 0);
break;
case JSON_STRING:
addString(data);
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_NUMBER:
addString(data);
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_TRUE:
addTrue();
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_FALSE:
addFalse();
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_NULL:
addNull();
if (!stack_.empty()) {
stack_.top().second++;
}
break;
default:
break;
}
}
void JSONOutputStream::beginObject() {
output_->printf("{");
}
void JSONOutputStream::endObject() {
output_->printf("}");
}
void JSONOutputStream::addObjectEntry(const std::string& key) {
output_->printf("\"%s\": ", escapeString(key).c_str());
}
void JSONOutputStream::addComma() {
output_->printf(",");
}
void JSONOutputStream::addColon() {
output_->printf(":");
}
void JSONOutputStream::addString(const std::string& string) {
output_->write("\"");
output_->write(escapeString(string));
output_->write("\"");
}
void JSONOutputStream::addInteger(int64_t value) {
output_->write(StringUtil::toString(value));
}
void JSONOutputStream::addNull() {
output_->write("null");
}
void JSONOutputStream::addTrue() {
output_->write("true");
}
void JSONOutputStream::addFalse() {
output_->write("false");
}
void JSONOutputStream::addFloat(double value) {
output_->write(StringUtil::toString(value));
}
void JSONOutputStream::beginArray() {
output_->printf("[");
}
void JSONOutputStream::endArray() {
output_->printf("]");
}
/*
template <>
void JSONOutputStream::addValue(const std::string& value) {
addString(value);
}
template <>
void JSONOutputStream::addValue(const int& value) {
output_->write(StringUtil::toString(value));
}
template <>
void JSONOutputStream::addValue(const unsigned long& value) {
output_->write(StringUtil::toString(value));
}
template <>
void JSONOutputStream::addValue(const unsigned long long& value) {
output_->write(StringUtil::toString(value));
}
template <>
void JSONOutputStream::addValue(const double& value) {
addFloat(value);
}
template <>
void JSONOutputStream::addValue(const bool& value) {
value ? addTrue() : addFalse();
}
template <>
void JSONOutputStream::addValue(const std::nullptr_t& value) {
addNull();
}
*/
std::string JSONOutputStream::escapeString(const std::string& string) const {
std::string new_str;
for (int i = 0; i < string.size(); ++i) {
switch (string.at(i)) {
case '"':
new_str += "\\\"";
break;
case '\\':
new_str += "\\\\";
break;
case '\n':
new_str += "\\n";
break;
case '\t':
new_str += "\\t";
break;
default:
new_str += string.at(i);
}
}
return new_str;
}
} // namespace json
} // namespace fnord
<commit_msg>handle NaN/Inifity in JSON<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-base/stringutil.h>
#include <fnord-base/inspect.h>
#include <fnord-json/jsonoutputstream.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
namespace fnord {
namespace json {
JSONOutputStream::JSONOutputStream(
std::shared_ptr<OutputStream> output_stream) :
output_(output_stream) {
}
JSONOutputStream::JSONOutputStream(
std::unique_ptr<OutputStream> output_stream) {
output_.reset(output_stream.release());
}
void JSONOutputStream::write(const JSONObject& obj) {
for (const auto& t : obj) {
emplace_back(t.type, t.data);
}
}
void JSONOutputStream::emplace_back(kTokenType token) {
emplace_back(token, "");
}
void JSONOutputStream::emplace_back(const JSONToken& token) {
emplace_back(token.type, token.data);
}
void JSONOutputStream::emplace_back(
kTokenType token,
const std::string& data) {
switch (token) {
case JSON_ARRAY_END:
endArray();
if (!stack_.empty()) {
stack_.pop();
}
if (!stack_.empty()) {
stack_.top().second++;
}
return;
case JSON_OBJECT_END:
endObject();
if (!stack_.empty()) {
stack_.pop();
}
if (!stack_.empty()) {
stack_.top().second++;
}
return;
default:
break;
}
if (!stack_.empty() && stack_.top().second > 0) {
switch (stack_.top().first) {
case JSON_ARRAY_BEGIN:
addComma();
break;
case JSON_OBJECT_BEGIN:
(stack_.top().second % 2 == 0) ? addComma() : addColon();
break;
default:
break;
}
}
switch (token) {
case JSON_ARRAY_BEGIN:
beginArray();
stack_.emplace(JSON_ARRAY_BEGIN, 0);
break;
case JSON_OBJECT_BEGIN:
beginObject();
stack_.emplace(JSON_OBJECT_BEGIN, 0);
break;
case JSON_STRING:
addString(data);
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_NUMBER:
addString(data);
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_TRUE:
addTrue();
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_FALSE:
addFalse();
if (!stack_.empty()) {
stack_.top().second++;
}
break;
case JSON_NULL:
addNull();
if (!stack_.empty()) {
stack_.top().second++;
}
break;
default:
break;
}
}
void JSONOutputStream::beginObject() {
output_->printf("{");
}
void JSONOutputStream::endObject() {
output_->printf("}");
}
void JSONOutputStream::addObjectEntry(const std::string& key) {
output_->printf("\"%s\": ", escapeString(key).c_str());
}
void JSONOutputStream::addComma() {
output_->printf(",");
}
void JSONOutputStream::addColon() {
output_->printf(":");
}
void JSONOutputStream::addString(const std::string& string) {
output_->write("\"");
output_->write(escapeString(string));
output_->write("\"");
}
void JSONOutputStream::addInteger(int64_t value) {
output_->write(StringUtil::toString(value));
}
void JSONOutputStream::addNull() {
output_->write("null");
}
void JSONOutputStream::addTrue() {
output_->write("true");
}
void JSONOutputStream::addFalse() {
output_->write("false");
}
void JSONOutputStream::addFloat(double value) {
if (std::isnormal(value)) {
output_->write(StringUtil::toString(value));
} else {
addNull();
}
}
void JSONOutputStream::beginArray() {
output_->printf("[");
}
void JSONOutputStream::endArray() {
output_->printf("]");
}
/*
template <>
void JSONOutputStream::addValue(const std::string& value) {
addString(value);
}
template <>
void JSONOutputStream::addValue(const int& value) {
output_->write(StringUtil::toString(value));
}
template <>
void JSONOutputStream::addValue(const unsigned long& value) {
output_->write(StringUtil::toString(value));
}
template <>
void JSONOutputStream::addValue(const unsigned long long& value) {
output_->write(StringUtil::toString(value));
}
template <>
void JSONOutputStream::addValue(const double& value) {
addFloat(value);
}
template <>
void JSONOutputStream::addValue(const bool& value) {
value ? addTrue() : addFalse();
}
template <>
void JSONOutputStream::addValue(const std::nullptr_t& value) {
addNull();
}
*/
std::string JSONOutputStream::escapeString(const std::string& string) const {
std::string new_str;
for (int i = 0; i < string.size(); ++i) {
switch (string.at(i)) {
case '"':
new_str += "\\\"";
break;
case '\\':
new_str += "\\\\";
break;
case '\n':
new_str += "\\n";
break;
case '\t':
new_str += "\\t";
break;
default:
new_str += string.at(i);
}
}
return new_str;
}
} // namespace json
} // namespace fnord
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: inettbc.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: fs $ $Date: 2001-01-31 14:13:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFX_INETTBC_HXX
#define _SFX_INETTBC_HXX
// includes *****************************************************************
#include <tools/string.hxx>
#include <tools/urlobj.hxx>
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
struct SfxPickEntry_Impl;
class SfxURLBox : public ComboBox
{
friend class SfxMatchContext_Impl;
friend class SfxURLBox_Impl;
Link aOpenHdl;
String aBaseURL;
INetProtocol eSmartProtocol;
SfxMatchContext_Impl* pCtx;
SfxURLBox_Impl* pImp;
BOOL bAutoCompleteMode;
BOOL bOnlyDirectories;
BOOL bModified;
BOOL bTryAutoComplete: 1,
bCtrlClick: 1;
BOOL ProcessKey( const KeyCode& rCode );
void TryAutoComplete( BOOL bForward, BOOL bForce );
void UpdatePicklistForSmartProtocol_Impl();
DECL_LINK( AutoCompleteHdl_Impl, void* );
protected:
virtual long Notify( NotifyEvent& rNEvt );
virtual void Select();
virtual void Modify();
virtual BOOL QueryDrop( DropEvent &rEvt );
virtual BOOL Drop( const DropEvent &rEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
public:
SfxURLBox( Window* pParent, INetProtocol eSmart = INET_PROT_NOT_VALID );
SfxURLBox( Window* pParent, const ResId& _rResId, INetProtocol eSmart = INET_PROT_NOT_VALID );
void OpenURL( const String& rName, BOOL nMod ) const;
void SetBaseURL( const String& rURL ) { aBaseURL = rURL; }
const String& GetBaseURL() const { return aBaseURL; }
void SetOpenHdl( const Link& rLink ) { aOpenHdl = rLink; }
const Link& GetOpenHdl() const { return aOpenHdl; }
void SetOnlyDirectories( BOOL bDir = TRUE );
INetProtocol GetSmartProtocol() const { return eSmartProtocol; }
void SetSmartProtocol( INetProtocol eProt );
BOOL IsCtrlOpen()
{ return bCtrlClick; }
String GetURL();
};
#if _SOLAR__PRIVATE
#include "tbxctrl.hxx"
class SfxURLToolBoxControl_Impl : public SfxToolBoxControl
{
private:
SfxStatusForwarder aURLForwarder;
SfxURLBox* GetURLBox() const;
DECL_LINK( OpenHdl, void* );
DECL_LINK( SelectHdl, void* );
public:
SFX_DECL_TOOLBOX_CONTROL();
SfxURLToolBoxControl_Impl( USHORT nId,
ToolBox& rBox,
SfxBindings& rBindings );
virtual Window* CreateItemWindow( Window* pParent );
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
};
class SfxCancelToolBoxControl_Impl : public SfxToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SfxCancelToolBoxControl_Impl(
USHORT nId,
ToolBox& rBox,
SfxBindings& rBindings );
virtual SfxPopupWindowType GetPopupWindowType() const;
virtual SfxPopupWindow* CreatePopupWindow();
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
};
#endif
#endif
<commit_msg>#80941#: new dtor<commit_after>/*************************************************************************
*
* $RCSfile: inettbc.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: mba $ $Date: 2001-02-08 10:11:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFX_INETTBC_HXX
#define _SFX_INETTBC_HXX
// includes *****************************************************************
#include <tools/string.hxx>
#include <tools/urlobj.hxx>
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
struct SfxPickEntry_Impl;
class SfxURLBox : public ComboBox
{
friend class SfxMatchContext_Impl;
friend class SfxURLBox_Impl;
Link aOpenHdl;
String aBaseURL;
INetProtocol eSmartProtocol;
SfxMatchContext_Impl* pCtx;
SfxURLBox_Impl* pImp;
BOOL bAutoCompleteMode;
BOOL bOnlyDirectories;
BOOL bModified;
BOOL bTryAutoComplete: 1,
bCtrlClick: 1;
BOOL ProcessKey( const KeyCode& rCode );
void TryAutoComplete( BOOL bForward, BOOL bForce );
void UpdatePicklistForSmartProtocol_Impl();
DECL_LINK( AutoCompleteHdl_Impl, void* );
protected:
virtual long Notify( NotifyEvent& rNEvt );
virtual void Select();
virtual void Modify();
virtual BOOL QueryDrop( DropEvent &rEvt );
virtual BOOL Drop( const DropEvent &rEvt );
virtual long PreNotify( NotifyEvent& rNEvt );
public:
SfxURLBox( Window* pParent, INetProtocol eSmart = INET_PROT_NOT_VALID );
SfxURLBox( Window* pParent, const ResId& _rResId, INetProtocol eSmart = INET_PROT_NOT_VALID );
~SfxURLBox();
void OpenURL( const String& rName, BOOL nMod ) const;
void SetBaseURL( const String& rURL ) { aBaseURL = rURL; }
const String& GetBaseURL() const { return aBaseURL; }
void SetOpenHdl( const Link& rLink ) { aOpenHdl = rLink; }
const Link& GetOpenHdl() const { return aOpenHdl; }
void SetOnlyDirectories( BOOL bDir = TRUE );
INetProtocol GetSmartProtocol() const { return eSmartProtocol; }
void SetSmartProtocol( INetProtocol eProt );
BOOL IsCtrlOpen()
{ return bCtrlClick; }
String GetURL();
};
#if _SOLAR__PRIVATE
#include "tbxctrl.hxx"
class SfxURLToolBoxControl_Impl : public SfxToolBoxControl
{
private:
SfxStatusForwarder aURLForwarder;
SfxURLBox* GetURLBox() const;
DECL_LINK( OpenHdl, void* );
DECL_LINK( SelectHdl, void* );
public:
SFX_DECL_TOOLBOX_CONTROL();
SfxURLToolBoxControl_Impl( USHORT nId,
ToolBox& rBox,
SfxBindings& rBindings );
virtual Window* CreateItemWindow( Window* pParent );
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
};
class SfxCancelToolBoxControl_Impl : public SfxToolBoxControl
{
public:
SFX_DECL_TOOLBOX_CONTROL();
SfxCancelToolBoxControl_Impl(
USHORT nId,
ToolBox& rBox,
SfxBindings& rBindings );
virtual SfxPopupWindowType GetPopupWindowType() const;
virtual SfxPopupWindow* CreatePopupWindow();
virtual void StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState );
};
#endif
#endif
<|endoftext|> |
<commit_before>/*
* blinkyBlocksBlock.cpp
*
* Created on: 23 mars 2013
* Author: dom
*/
#include <iostream>
#include "blinkyBlocksBlock.h"
#include "blinkyBlocksWorld.h"
#include <sys/wait.h>
using namespace std;
namespace BlinkyBlocks {
static const GLfloat tabColors[12][4]={{1.0,0.0,0.0,1.0},{1.0,0.647058824,0.0,1.0},{1.0,1.0,0.0,1.0},{0.0,1.0,0.0,1.0},
{0.0,0.0,1.0,1.0},{0.274509804,0.509803922,0.705882353,1.0},{0.815686275,0.125490196,0.564705882,1.0},{0.5,0.5,0.5,1.0},
{0.980392157,0.5,0.456,1.0},{0.549019608,0.5,0.5,1.0},{0.980392157,0.843137255,0.0,1.0},{0.094117647,0.545098039,0.094117647,1.0}};
BlinkyBlocksBlock::BlinkyBlocksBlock(int bId, boost::shared_ptr<tcp::socket> s, pid_t p, BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::BuildingBlock(bId) {
cout << "BlinkyBlocksBlock constructor" << endl;
buildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction;
blockCode = (BaseSimulator::BlockCode*)buildNewBlockCode(this);
socket = s;
pid = p;
for (int i=0; i<6; i++) {
tabInterfaces[i] = new P2PNetworkInterface(this);
}
}
BlinkyBlocksBlock::~BlinkyBlocksBlock() {
cout << "BlinkyBlocksBlock destructor" << endl;
kill(pid, SIGTERM);
}
void BlinkyBlocksBlock::waitVMEnd() {
waitpid(pid, NULL, 0);
}
void BlinkyBlocksBlock::setPosition(const Vecteur &p) {
position=p;
getWorld()->updateGlData(this);
}
void BlinkyBlocksBlock::setColor(const Vecteur &c) {
color=c;
getWorld()->updateGlData(this);
}
void BlinkyBlocksBlock::setColor(int num) {
const GLfloat *col = tabColors[num%12];
color.set(col[0],col[1],col[2],col[3]);
getWorld()->updateGlData(this);
}
NeighborDirection BlinkyBlocksBlock::getDirection(P2PNetworkInterface *given_interface) {
if( !given_interface) {
return NeighborDirection(0);
}
for( int i(0); i < 6; ++i) {
if( tabInterfaces[i] == given_interface) return NeighborDirection(i);
}
return NeighborDirection(0);
}
}
<commit_msg>waitpid() in ~BlinkyBlocksBlock to avoid zombie process<commit_after>/*
* blinkyBlocksBlock.cpp
*
* Created on: 23 mars 2013
* Author: dom
*/
#include <iostream>
#include "blinkyBlocksBlock.h"
#include "blinkyBlocksWorld.h"
#include <sys/wait.h>
using namespace std;
namespace BlinkyBlocks {
static const GLfloat tabColors[12][4]={{1.0,0.0,0.0,1.0},{1.0,0.647058824,0.0,1.0},{1.0,1.0,0.0,1.0},{0.0,1.0,0.0,1.0},
{0.0,0.0,1.0,1.0},{0.274509804,0.509803922,0.705882353,1.0},{0.815686275,0.125490196,0.564705882,1.0},{0.5,0.5,0.5,1.0},
{0.980392157,0.5,0.456,1.0},{0.549019608,0.5,0.5,1.0},{0.980392157,0.843137255,0.0,1.0},{0.094117647,0.545098039,0.094117647,1.0}};
BlinkyBlocksBlock::BlinkyBlocksBlock(int bId, boost::shared_ptr<tcp::socket> s, pid_t p, BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::BuildingBlock(bId) {
cout << "BlinkyBlocksBlock constructor" << endl;
buildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction;
blockCode = (BaseSimulator::BlockCode*)buildNewBlockCode(this);
socket = s;
pid = p;
for (int i=0; i<6; i++) {
tabInterfaces[i] = new P2PNetworkInterface(this);
}
}
BlinkyBlocksBlock::~BlinkyBlocksBlock() {
cout << "BlinkyBlocksBlock destructor" << endl;
kill(pid, SIGTERM);
waitpid(pid, NULL, 0);
}
void BlinkyBlocksBlock::waitVMEnd() {
waitpid(pid, NULL, 0);
}
void BlinkyBlocksBlock::setPosition(const Vecteur &p) {
position=p;
getWorld()->updateGlData(this);
}
void BlinkyBlocksBlock::setColor(const Vecteur &c) {
color=c;
getWorld()->updateGlData(this);
}
void BlinkyBlocksBlock::setColor(int num) {
const GLfloat *col = tabColors[num%12];
color.set(col[0],col[1],col[2],col[3]);
getWorld()->updateGlData(this);
}
NeighborDirection BlinkyBlocksBlock::getDirection(P2PNetworkInterface *given_interface) {
if( !given_interface) {
return NeighborDirection(0);
}
for( int i(0); i < 6; ++i) {
if( tabInterfaces[i] == given_interface) return NeighborDirection(i);
}
return NeighborDirection(0);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2008 SlimDX Group
*
* 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 <d3d10.h>
#include "../Utilities.h"
#include "BlendStateDescription.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;
namespace SlimDX
{
namespace Direct3D10
{
BlendStateDescription::BlendStateDescription( const D3D10_BLEND_DESC& native )
{
m_AlphaToCoverageEnable = native.AlphaToCoverageEnable ? true : false;
m_SrcBlend = static_cast<BlendOption>( native.SrcBlend );
m_DestBlend = static_cast<BlendOption>( native.DestBlend );
m_BlendOp = static_cast<Direct3D10::BlendOperation>( native.BlendOp );
m_SrcBlendAlpha = static_cast<BlendOption>( native.SrcBlendAlpha );
m_DestBlendAlpha = static_cast<BlendOption>( native.DestBlendAlpha );
m_BlendOpAlpha = static_cast<Direct3D10::BlendOperation>( native.BlendOpAlpha );
ConstructLazyProperties();
}
D3D10_BLEND_DESC BlendStateDescription::CreateNativeVersion()
{
D3D10_BLEND_DESC native;
native.AlphaToCoverageEnable = m_AlphaToCoverageEnable;
native.SrcBlend = static_cast<D3D10_BLEND>( m_SrcBlend );
native.DestBlend = static_cast<D3D10_BLEND>( m_DestBlend );
native.BlendOp = static_cast<D3D10_BLEND_OP>( m_BlendOp );
native.SrcBlendAlpha = static_cast<D3D10_BLEND>( m_SrcBlendAlpha );
native.DestBlendAlpha = static_cast<D3D10_BLEND>( m_DestBlendAlpha );
native.BlendOpAlpha = static_cast<D3D10_BLEND_OP>( m_BlendOpAlpha );
ConstructLazyProperties();
for(int index = 0; index < 8; ++index)
{
native.BlendEnable[ index ] = m_BlendEnable[ index ];
native.RenderTargetWriteMask[ index ] = static_cast<UINT8>( m_RenderTargetWriteMask[ index ] );
}
return native;
}
bool BlendStateDescription::IsAlphaToCoverageEnabled::get()
{
return m_AlphaToCoverageEnable;
}
void BlendStateDescription::IsAlphaToCoverageEnabled::set( bool value )
{
m_AlphaToCoverageEnable = value;
}
BlendOption BlendStateDescription::SourceBlend::get()
{
return m_SrcBlend;
}
void BlendStateDescription::SourceBlend::set( BlendOption value )
{
m_SrcBlend = value;
}
BlendOption BlendStateDescription::DestinationBlend::get()
{
return m_DestBlend;
}
void BlendStateDescription::DestinationBlend::set( BlendOption value )
{
m_DestBlend = value;
}
Direct3D10::BlendOperation BlendStateDescription::BlendOperation::get()
{
return m_BlendOp;
}
void BlendStateDescription::BlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOp = value;
}
BlendOption BlendStateDescription::SourceAlphaBlend::get()
{
return m_SrcBlendAlpha;
}
void BlendStateDescription::SourceAlphaBlend::set( BlendOption value )
{
m_SrcBlendAlpha = value;
}
BlendOption BlendStateDescription::DestinationAlphaBlend::get()
{
return m_DestBlendAlpha;
}
void BlendStateDescription::DestinationAlphaBlend::set( BlendOption value )
{
m_DestBlendAlpha = value;
}
Direct3D10::BlendOperation BlendStateDescription::AlphaBlendOperation::get()
{
return m_BlendOpAlpha;
}
void BlendStateDescription::AlphaBlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOpAlpha = value;
}
bool BlendStateDescription::GetBlendEnable( UInt32 index )
{
ConstructLazyProperties();
return m_BlendEnable[ index ];
}
void BlendStateDescription::SetBlendEnable( UInt32 index, bool value )
{
ConstructLazyProperties();
m_BlendEnable[ index ] = value;
}
ColorWriteMaskFlags BlendStateDescription::GetWriteMask( UInt32 index )
{
ConstructLazyProperties();
return m_RenderTargetWriteMask[ index ];
}
void BlendStateDescription::SetWriteMask( UInt32 index, ColorWriteMaskFlags value )
{
ConstructLazyProperties();
m_RenderTargetWriteMask[ index ] = value;
}
void BlendStateDescription::ConstructLazyProperties()
{
if( m_BlendEnable == nullptr )
{
m_BlendEnable = gcnew array<bool>(8);
m_RenderTargetWriteMask = gcnew array<ColorWriteMaskFlags>(8);
for(int index = 0; index < 8; ++index)
{
m_BlendEnable[ index ] = false;
m_RenderTargetWriteMask[ index ] = ColorWriteMaskFlags::All;
}
}
}
bool BlendStateDescription::operator == ( BlendStateDescription left, BlendStateDescription right )
{
return BlendStateDescription::Equals( left, right );
}
bool BlendStateDescription::operator != ( BlendStateDescription left, BlendStateDescription right )
{
return !BlendStateDescription::Equals( left, right );
}
int BlendStateDescription::GetHashCode()
{
return (
m_AlphaToCoverageEnable.GetHashCode() +
m_BlendEnable->GetHashCode() +
m_SrcBlend.GetHashCode() +
m_DestBlend.GetHashCode() +
m_BlendOp.GetHashCode() +
m_SrcBlendAlpha.GetHashCode() +
m_DestBlendAlpha.GetHashCode() +
m_BlendOpAlpha.GetHashCode() +
m_RenderTargetWriteMask->GetHashCode()
);
}
bool BlendStateDescription::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<BlendStateDescription>( value ) );
}
bool BlendStateDescription::Equals( BlendStateDescription value )
{
return (
m_AlphaToCoverageEnable == value.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( m_BlendEnable, value.m_BlendEnable ) &&
m_SrcBlend == value.m_SrcBlend &&
m_DestBlend == value.m_DestBlend &&
m_BlendOp == value.m_BlendOp &&
m_SrcBlendAlpha == value.m_SrcBlendAlpha &&
m_DestBlendAlpha == value.m_DestBlendAlpha &&
m_BlendOpAlpha == value.m_BlendOpAlpha &&
Utilities::CheckElementEquality( m_RenderTargetWriteMask, value.m_RenderTargetWriteMask )
);
}
bool BlendStateDescription::Equals( BlendStateDescription% value1, BlendStateDescription% value2 )
{
return (
value1.m_AlphaToCoverageEnable == value2.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( value1.m_BlendEnable, value2.m_BlendEnable ) &&
value1.m_SrcBlend == value2.m_SrcBlend &&
value1.m_DestBlend == value2.m_DestBlend &&
value1.m_BlendOp == value2.m_BlendOp &&
value1.m_SrcBlendAlpha == value2.m_SrcBlendAlpha &&
value1.m_DestBlendAlpha == value2.m_DestBlendAlpha &&
value1.m_BlendOpAlpha == value2.m_BlendOpAlpha &&
Utilities::CheckElementEquality( value1.m_RenderTargetWriteMask, value2.m_RenderTargetWriteMask )
);
}
}
}
<commit_msg>(issue #361) After constructing lazy property arrays, the BlendStateDescription internal constructor will copy values from the native struct's arrays.<commit_after>/*
* Copyright (c) 2007-2008 SlimDX Group
*
* 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 <d3d10.h>
#include "../Utilities.h"
#include "BlendStateDescription.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;
namespace SlimDX
{
namespace Direct3D10
{
BlendStateDescription::BlendStateDescription( const D3D10_BLEND_DESC& native )
{
m_AlphaToCoverageEnable = native.AlphaToCoverageEnable ? true : false;
m_SrcBlend = static_cast<BlendOption>( native.SrcBlend );
m_DestBlend = static_cast<BlendOption>( native.DestBlend );
m_BlendOp = static_cast<Direct3D10::BlendOperation>( native.BlendOp );
m_SrcBlendAlpha = static_cast<BlendOption>( native.SrcBlendAlpha );
m_DestBlendAlpha = static_cast<BlendOption>( native.DestBlendAlpha );
m_BlendOpAlpha = static_cast<Direct3D10::BlendOperation>( native.BlendOpAlpha );
ConstructLazyProperties();
for(int index = 0; index < 8; ++index)
{
m_BlendEnable[ index ] = native.BlendEnable[ index ];
m_RenderTargetWriteMask[ index ] = static_cast<ColorWriteMaskFlags>( native.RenderTargetWriteMask[ index ] );
}
}
D3D10_BLEND_DESC BlendStateDescription::CreateNativeVersion()
{
D3D10_BLEND_DESC native;
native.AlphaToCoverageEnable = m_AlphaToCoverageEnable;
native.SrcBlend = static_cast<D3D10_BLEND>( m_SrcBlend );
native.DestBlend = static_cast<D3D10_BLEND>( m_DestBlend );
native.BlendOp = static_cast<D3D10_BLEND_OP>( m_BlendOp );
native.SrcBlendAlpha = static_cast<D3D10_BLEND>( m_SrcBlendAlpha );
native.DestBlendAlpha = static_cast<D3D10_BLEND>( m_DestBlendAlpha );
native.BlendOpAlpha = static_cast<D3D10_BLEND_OP>( m_BlendOpAlpha );
ConstructLazyProperties();
for(int index = 0; index < 8; ++index)
{
native.BlendEnable[ index ] = m_BlendEnable[ index ];
native.RenderTargetWriteMask[ index ] = static_cast<UINT8>( m_RenderTargetWriteMask[ index ] );
}
return native;
}
bool BlendStateDescription::IsAlphaToCoverageEnabled::get()
{
return m_AlphaToCoverageEnable;
}
void BlendStateDescription::IsAlphaToCoverageEnabled::set( bool value )
{
m_AlphaToCoverageEnable = value;
}
BlendOption BlendStateDescription::SourceBlend::get()
{
return m_SrcBlend;
}
void BlendStateDescription::SourceBlend::set( BlendOption value )
{
m_SrcBlend = value;
}
BlendOption BlendStateDescription::DestinationBlend::get()
{
return m_DestBlend;
}
void BlendStateDescription::DestinationBlend::set( BlendOption value )
{
m_DestBlend = value;
}
Direct3D10::BlendOperation BlendStateDescription::BlendOperation::get()
{
return m_BlendOp;
}
void BlendStateDescription::BlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOp = value;
}
BlendOption BlendStateDescription::SourceAlphaBlend::get()
{
return m_SrcBlendAlpha;
}
void BlendStateDescription::SourceAlphaBlend::set( BlendOption value )
{
m_SrcBlendAlpha = value;
}
BlendOption BlendStateDescription::DestinationAlphaBlend::get()
{
return m_DestBlendAlpha;
}
void BlendStateDescription::DestinationAlphaBlend::set( BlendOption value )
{
m_DestBlendAlpha = value;
}
Direct3D10::BlendOperation BlendStateDescription::AlphaBlendOperation::get()
{
return m_BlendOpAlpha;
}
void BlendStateDescription::AlphaBlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOpAlpha = value;
}
bool BlendStateDescription::GetBlendEnable( UInt32 index )
{
ConstructLazyProperties();
return m_BlendEnable[ index ];
}
void BlendStateDescription::SetBlendEnable( UInt32 index, bool value )
{
ConstructLazyProperties();
m_BlendEnable[ index ] = value;
}
ColorWriteMaskFlags BlendStateDescription::GetWriteMask( UInt32 index )
{
ConstructLazyProperties();
return m_RenderTargetWriteMask[ index ];
}
void BlendStateDescription::SetWriteMask( UInt32 index, ColorWriteMaskFlags value )
{
ConstructLazyProperties();
m_RenderTargetWriteMask[ index ] = value;
}
void BlendStateDescription::ConstructLazyProperties()
{
if( m_BlendEnable == nullptr )
{
m_BlendEnable = gcnew array<bool>(8);
m_RenderTargetWriteMask = gcnew array<ColorWriteMaskFlags>(8);
for(int index = 0; index < 8; ++index)
{
m_BlendEnable[ index ] = false;
m_RenderTargetWriteMask[ index ] = ColorWriteMaskFlags::All;
}
}
}
bool BlendStateDescription::operator == ( BlendStateDescription left, BlendStateDescription right )
{
return BlendStateDescription::Equals( left, right );
}
bool BlendStateDescription::operator != ( BlendStateDescription left, BlendStateDescription right )
{
return !BlendStateDescription::Equals( left, right );
}
int BlendStateDescription::GetHashCode()
{
return (
m_AlphaToCoverageEnable.GetHashCode() +
m_BlendEnable->GetHashCode() +
m_SrcBlend.GetHashCode() +
m_DestBlend.GetHashCode() +
m_BlendOp.GetHashCode() +
m_SrcBlendAlpha.GetHashCode() +
m_DestBlendAlpha.GetHashCode() +
m_BlendOpAlpha.GetHashCode() +
m_RenderTargetWriteMask->GetHashCode()
);
}
bool BlendStateDescription::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<BlendStateDescription>( value ) );
}
bool BlendStateDescription::Equals( BlendStateDescription value )
{
return (
m_AlphaToCoverageEnable == value.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( m_BlendEnable, value.m_BlendEnable ) &&
m_SrcBlend == value.m_SrcBlend &&
m_DestBlend == value.m_DestBlend &&
m_BlendOp == value.m_BlendOp &&
m_SrcBlendAlpha == value.m_SrcBlendAlpha &&
m_DestBlendAlpha == value.m_DestBlendAlpha &&
m_BlendOpAlpha == value.m_BlendOpAlpha &&
Utilities::CheckElementEquality( m_RenderTargetWriteMask, value.m_RenderTargetWriteMask )
);
}
bool BlendStateDescription::Equals( BlendStateDescription% value1, BlendStateDescription% value2 )
{
return (
value1.m_AlphaToCoverageEnable == value2.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( value1.m_BlendEnable, value2.m_BlendEnable ) &&
value1.m_SrcBlend == value2.m_SrcBlend &&
value1.m_DestBlend == value2.m_DestBlend &&
value1.m_BlendOp == value2.m_BlendOp &&
value1.m_SrcBlendAlpha == value2.m_SrcBlendAlpha &&
value1.m_DestBlendAlpha == value2.m_DestBlendAlpha &&
value1.m_BlendOpAlpha == value2.m_BlendOpAlpha &&
Utilities::CheckElementEquality( value1.m_RenderTargetWriteMask, value2.m_RenderTargetWriteMask )
);
}
}
}
<|endoftext|> |
<commit_before>// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_TRAITS_HPP
#define TOML11_TRAITS_HPP
#include <type_traits>
#include <utility>
#include <chrono>
#include <tuple>
#include <string>
#if __cplusplus >= 201703L
#if __has_include(<string_view>)
#include <string_view>
#endif // has_include(<string_view>)
#endif // cplusplus >= C++17
namespace toml
{
template<typename C, template<typename ...> class T, template<typename ...> class A>
class basic_value;
namespace detail
{
// ---------------------------------------------------------------------------
// check whether type T is a kind of container/map class
struct has_iterator_impl
{
template<typename T> static std::true_type check(typename T::iterator*);
template<typename T> static std::false_type check(...);
};
struct has_value_type_impl
{
template<typename T> static std::true_type check(typename T::value_type*);
template<typename T> static std::false_type check(...);
};
struct has_key_type_impl
{
template<typename T> static std::true_type check(typename T::key_type*);
template<typename T> static std::false_type check(...);
};
struct has_mapped_type_impl
{
template<typename T> static std::true_type check(typename T::mapped_type*);
template<typename T> static std::false_type check(...);
};
struct has_reserve_method_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>().reserve(std::declval<std::size_t>()))*);
};
struct has_push_back_method_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>().push_back(std::declval<typename T::value_type>()))*);
};
struct is_comparable_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>() < std::declval<T>())*);
};
struct has_from_toml_method_impl
{
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
static std::true_type check(
decltype(std::declval<T>().from_toml(
std::declval<::toml::basic_value<C, Tb, A>>()))*);
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
static std::false_type check(...);
};
struct has_into_toml_method_impl
{
template<typename T>
static std::true_type check(decltype(std::declval<T>().into_toml())*);
template<typename T>
static std::false_type check(...);
};
/// Intel C++ compiler can not use decltype in parent class declaration, here
/// is a hack to work around it. https://stackoverflow.com/a/23953090/4692076
#ifdef __INTEL_COMPILER
#define decltype(...) std::enable_if<true, decltype(__VA_ARGS__)>::type
#endif
template<typename T>
struct has_iterator : decltype(has_iterator_impl::check<T>(nullptr)){};
template<typename T>
struct has_value_type : decltype(has_value_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_key_type : decltype(has_key_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_mapped_type : decltype(has_mapped_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_reserve_method : decltype(has_reserve_method_impl::check<T>(nullptr)){};
template<typename T>
struct has_push_back_method : decltype(has_push_back_method_impl::check<T>(nullptr)){};
template<typename T>
struct is_comparable : decltype(is_comparable_impl::check<T>(nullptr)){};
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
struct has_from_toml_method
: decltype(has_from_toml_method_impl::check<T, C, Tb, A>(nullptr)){};
template<typename T>
struct has_into_toml_method
: decltype(has_into_toml_method_impl::check<T>(nullptr)){};
#ifdef __INTEL_COMPILER
#undef decltype
#endif
// ---------------------------------------------------------------------------
// C++17 and/or/not
#if __cplusplus >= 201703L
using std::conjunction;
using std::disjunction;
using std::negation;
#else
template<typename ...> struct conjunction : std::true_type{};
template<typename T> struct conjunction<T> : T{};
template<typename T, typename ... Ts>
struct conjunction<T, Ts...> :
std::conditional<static_cast<bool>(T::value), conjunction<Ts...>, T>::type
{};
template<typename ...> struct disjunction : std::false_type{};
template<typename T> struct disjunction<T> : T {};
template<typename T, typename ... Ts>
struct disjunction<T, Ts...> :
std::conditional<static_cast<bool>(T::value), T, disjunction<Ts...>>::type
{};
template<typename T>
struct negation : std::integral_constant<bool, !static_cast<bool>(T::value)>{};
#endif
// ---------------------------------------------------------------------------
// type checkers
template<typename T> struct is_std_pair : std::false_type{};
template<typename T1, typename T2>
struct is_std_pair<std::pair<T1, T2>> : std::true_type{};
template<typename T> struct is_std_tuple : std::false_type{};
template<typename ... Ts>
struct is_std_tuple<std::tuple<Ts...>> : std::true_type{};
template<typename T> struct is_chrono_duration: std::false_type{};
template<typename Rep, typename Period>
struct is_chrono_duration<std::chrono::duration<Rep, Period>>: std::true_type{};
template<typename T>
struct is_map : conjunction< // map satisfies all the following conditions
has_iterator<T>, // has T::iterator
has_value_type<T>, // has T::value_type
has_key_type<T>, // has T::key_type
has_mapped_type<T> // has T::mapped_type
>{};
template<typename T> struct is_map<T&> : is_map<T>{};
template<typename T> struct is_map<T const&> : is_map<T>{};
template<typename T> struct is_map<T volatile&> : is_map<T>{};
template<typename T> struct is_map<T const volatile&> : is_map<T>{};
template<typename T>
struct is_container : conjunction<
negation<is_map<T>>, // not a map
negation<std::is_same<T, std::string>>, // not a std::string
#if __cplusplus >= 201703L
negation<std::is_same<T, std::string_view>>, // not a std::string_view
#endif
has_iterator<T>, // has T::iterator
has_value_type<T> // has T::value_type
>{};
template<typename T> struct is_container<T&> : is_container<T>{};
template<typename T> struct is_container<T const&> : is_container<T>{};
template<typename T> struct is_container<T volatile&> : is_container<T>{};
template<typename T> struct is_container<T const volatile&> : is_container<T>{};
template<typename T>
struct is_basic_value: std::false_type{};
template<typename T> struct is_basic_value<T&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T const&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T volatile&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T const volatile&> : is_basic_value<T>{};
template<typename C, template<typename ...> class M, template<typename ...> class V>
struct is_basic_value<::toml::basic_value<C, M, V>>: std::true_type{};
// ---------------------------------------------------------------------------
// C++14 index_sequence
#if __cplusplus >= 201402L
using std::index_sequence;
using std::make_index_sequence;
#else
template<std::size_t ... Ns> struct index_sequence{};
template<typename IS, std::size_t N> struct push_back_index_sequence{};
template<std::size_t N, std::size_t ... Ns>
struct push_back_index_sequence<index_sequence<Ns...>, N>
{
typedef index_sequence<Ns..., N> type;
};
template<std::size_t N>
struct index_sequence_maker
{
typedef typename push_back_index_sequence<
typename index_sequence_maker<N-1>::type, N>::type type;
};
template<>
struct index_sequence_maker<0>
{
typedef index_sequence<0> type;
};
template<std::size_t N>
using make_index_sequence = typename index_sequence_maker<N-1>::type;
#endif // __cplusplus >= 2014
// ---------------------------------------------------------------------------
// C++14 enable_if_t
#if __cplusplus >= 201402L
using std::enable_if_t;
#else
template<bool B, typename T>
using enable_if_t = typename std::enable_if<B, T>::type;
#endif // __cplusplus >= 2014
// ---------------------------------------------------------------------------
// return_type_of_t
#if __cplusplus >= 201703L
template<typename F, typename ... Args>
using return_type_of_t = std::invoke_result_t<F, Args...>;
#else
// result_of is deprecated after C++17
template<typename F, typename ... Args>
using return_type_of_t = typename std::result_of<F(Args...)>::type;
#endif
// ---------------------------------------------------------------------------
// is_string_literal
//
// to use this, pass `typename remove_reference<T>::type` to T.
template<typename T>
struct is_string_literal:
disjunction<
std::is_same<const char*, T>,
conjunction<
std::is_array<T>,
std::is_same<const char, typename std::remove_extent<T>::type>
>
>{};
// ---------------------------------------------------------------------------
// C++20 remove_cvref_t
template<typename T>
struct remove_cvref
{
using type = typename std::remove_cv<
typename std::remove_reference<T>::type>::type;
};
template<typename T>
using remove_cvref_t = typename remove_cvref<T>::type;
}// detail
}//toml
#endif // TOML_TRAITS
<commit_msg>feat: add is_std_forward_list<commit_after>// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_TRAITS_HPP
#define TOML11_TRAITS_HPP
#include <type_traits>
#include <utility>
#include <chrono>
#include <tuple>
#include <string>
#include <forward_list>
#if __cplusplus >= 201703L
#if __has_include(<string_view>)
#include <string_view>
#endif // has_include(<string_view>)
#endif // cplusplus >= C++17
namespace toml
{
template<typename C, template<typename ...> class T, template<typename ...> class A>
class basic_value;
namespace detail
{
// ---------------------------------------------------------------------------
// check whether type T is a kind of container/map class
struct has_iterator_impl
{
template<typename T> static std::true_type check(typename T::iterator*);
template<typename T> static std::false_type check(...);
};
struct has_value_type_impl
{
template<typename T> static std::true_type check(typename T::value_type*);
template<typename T> static std::false_type check(...);
};
struct has_key_type_impl
{
template<typename T> static std::true_type check(typename T::key_type*);
template<typename T> static std::false_type check(...);
};
struct has_mapped_type_impl
{
template<typename T> static std::true_type check(typename T::mapped_type*);
template<typename T> static std::false_type check(...);
};
struct has_reserve_method_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>().reserve(std::declval<std::size_t>()))*);
};
struct has_push_back_method_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>().push_back(std::declval<typename T::value_type>()))*);
};
struct is_comparable_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>() < std::declval<T>())*);
};
struct has_from_toml_method_impl
{
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
static std::true_type check(
decltype(std::declval<T>().from_toml(
std::declval<::toml::basic_value<C, Tb, A>>()))*);
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
static std::false_type check(...);
};
struct has_into_toml_method_impl
{
template<typename T>
static std::true_type check(decltype(std::declval<T>().into_toml())*);
template<typename T>
static std::false_type check(...);
};
/// Intel C++ compiler can not use decltype in parent class declaration, here
/// is a hack to work around it. https://stackoverflow.com/a/23953090/4692076
#ifdef __INTEL_COMPILER
#define decltype(...) std::enable_if<true, decltype(__VA_ARGS__)>::type
#endif
template<typename T>
struct has_iterator : decltype(has_iterator_impl::check<T>(nullptr)){};
template<typename T>
struct has_value_type : decltype(has_value_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_key_type : decltype(has_key_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_mapped_type : decltype(has_mapped_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_reserve_method : decltype(has_reserve_method_impl::check<T>(nullptr)){};
template<typename T>
struct has_push_back_method : decltype(has_push_back_method_impl::check<T>(nullptr)){};
template<typename T>
struct is_comparable : decltype(is_comparable_impl::check<T>(nullptr)){};
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
struct has_from_toml_method
: decltype(has_from_toml_method_impl::check<T, C, Tb, A>(nullptr)){};
template<typename T>
struct has_into_toml_method
: decltype(has_into_toml_method_impl::check<T>(nullptr)){};
#ifdef __INTEL_COMPILER
#undef decltype
#endif
// ---------------------------------------------------------------------------
// C++17 and/or/not
#if __cplusplus >= 201703L
using std::conjunction;
using std::disjunction;
using std::negation;
#else
template<typename ...> struct conjunction : std::true_type{};
template<typename T> struct conjunction<T> : T{};
template<typename T, typename ... Ts>
struct conjunction<T, Ts...> :
std::conditional<static_cast<bool>(T::value), conjunction<Ts...>, T>::type
{};
template<typename ...> struct disjunction : std::false_type{};
template<typename T> struct disjunction<T> : T {};
template<typename T, typename ... Ts>
struct disjunction<T, Ts...> :
std::conditional<static_cast<bool>(T::value), T, disjunction<Ts...>>::type
{};
template<typename T>
struct negation : std::integral_constant<bool, !static_cast<bool>(T::value)>{};
#endif
// ---------------------------------------------------------------------------
// type checkers
template<typename T> struct is_std_pair : std::false_type{};
template<typename T1, typename T2>
struct is_std_pair<std::pair<T1, T2>> : std::true_type{};
template<typename T> struct is_std_tuple : std::false_type{};
template<typename ... Ts>
struct is_std_tuple<std::tuple<Ts...>> : std::true_type{};
template<typename T> struct is_std_forward_list : std::false_type{};
template<typename T>
struct is_std_forward_list<std::forward_list<T>> : std::true_type{};
template<typename T> struct is_chrono_duration: std::false_type{};
template<typename Rep, typename Period>
struct is_chrono_duration<std::chrono::duration<Rep, Period>>: std::true_type{};
template<typename T>
struct is_map : conjunction< // map satisfies all the following conditions
has_iterator<T>, // has T::iterator
has_value_type<T>, // has T::value_type
has_key_type<T>, // has T::key_type
has_mapped_type<T> // has T::mapped_type
>{};
template<typename T> struct is_map<T&> : is_map<T>{};
template<typename T> struct is_map<T const&> : is_map<T>{};
template<typename T> struct is_map<T volatile&> : is_map<T>{};
template<typename T> struct is_map<T const volatile&> : is_map<T>{};
template<typename T>
struct is_container : conjunction<
negation<is_map<T>>, // not a map
negation<std::is_same<T, std::string>>, // not a std::string
#if __cplusplus >= 201703L
negation<std::is_same<T, std::string_view>>, // not a std::string_view
#endif
has_iterator<T>, // has T::iterator
has_value_type<T> // has T::value_type
>{};
template<typename T> struct is_container<T&> : is_container<T>{};
template<typename T> struct is_container<T const&> : is_container<T>{};
template<typename T> struct is_container<T volatile&> : is_container<T>{};
template<typename T> struct is_container<T const volatile&> : is_container<T>{};
template<typename T>
struct is_basic_value: std::false_type{};
template<typename T> struct is_basic_value<T&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T const&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T volatile&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T const volatile&> : is_basic_value<T>{};
template<typename C, template<typename ...> class M, template<typename ...> class V>
struct is_basic_value<::toml::basic_value<C, M, V>>: std::true_type{};
// ---------------------------------------------------------------------------
// C++14 index_sequence
#if __cplusplus >= 201402L
using std::index_sequence;
using std::make_index_sequence;
#else
template<std::size_t ... Ns> struct index_sequence{};
template<typename IS, std::size_t N> struct push_back_index_sequence{};
template<std::size_t N, std::size_t ... Ns>
struct push_back_index_sequence<index_sequence<Ns...>, N>
{
typedef index_sequence<Ns..., N> type;
};
template<std::size_t N>
struct index_sequence_maker
{
typedef typename push_back_index_sequence<
typename index_sequence_maker<N-1>::type, N>::type type;
};
template<>
struct index_sequence_maker<0>
{
typedef index_sequence<0> type;
};
template<std::size_t N>
using make_index_sequence = typename index_sequence_maker<N-1>::type;
#endif // __cplusplus >= 2014
// ---------------------------------------------------------------------------
// C++14 enable_if_t
#if __cplusplus >= 201402L
using std::enable_if_t;
#else
template<bool B, typename T>
using enable_if_t = typename std::enable_if<B, T>::type;
#endif // __cplusplus >= 2014
// ---------------------------------------------------------------------------
// return_type_of_t
#if __cplusplus >= 201703L
template<typename F, typename ... Args>
using return_type_of_t = std::invoke_result_t<F, Args...>;
#else
// result_of is deprecated after C++17
template<typename F, typename ... Args>
using return_type_of_t = typename std::result_of<F(Args...)>::type;
#endif
// ---------------------------------------------------------------------------
// is_string_literal
//
// to use this, pass `typename remove_reference<T>::type` to T.
template<typename T>
struct is_string_literal:
disjunction<
std::is_same<const char*, T>,
conjunction<
std::is_array<T>,
std::is_same<const char, typename std::remove_extent<T>::type>
>
>{};
// ---------------------------------------------------------------------------
// C++20 remove_cvref_t
template<typename T>
struct remove_cvref
{
using type = typename std::remove_cv<
typename std::remove_reference<T>::type>::type;
};
template<typename T>
using remove_cvref_t = typename remove_cvref<T>::type;
}// detail
}//toml
#endif // TOML_TRAITS
<|endoftext|> |
<commit_before>#include "layouter.h"
#include "utf-8.h"
#include <harfbuzz/hb.h>
#include <harfbuzz/hb-ft.h>
#include <fribidi/fribidi.h>
#include <linebreak.h>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
typedef struct
{
std::vector<textLayout_c::commandData> run;
int dx, dy;
FriBidiLevel embeddingLevel;
char linebreak;
std::shared_ptr<fontFace_c> font;
} runInfo;
// TODO create a sharing structure, where we only
// define structures for each configuration once
// and link to it
// but for now it is good as it is
typedef struct
{
uint8_t r, g, b;
std::shared_ptr<fontFace_c> font;
std::string lang;
} codepointAttributes;
FriBidiLevel getBidiEmbeddingLevels(const std::u32string & txt32, std::vector<FriBidiLevel> & embedding_levels)
{
std::vector<FriBidiCharType> bidiTypes(txt32.length());
fribidi_get_bidi_types((uint32_t*)txt32.c_str(), txt32.length(), bidiTypes.data());
FriBidiParType base_dir = FRIBIDI_TYPE_LTR_VAL; // TODO depends on main script of text
embedding_levels.resize(txt32.length());
FriBidiLevel max_level = fribidi_get_par_embedding_levels(bidiTypes.data(), txt32.length(),
&base_dir, embedding_levels.data());
return max_level;
}
textLayout_c layoutParagraph(const std::u32string & txt32, const std::vector<codepointAttributes> & attr,
const shape_c & shape, const std::string & align)
{
// calculate embedding types for the text
std::vector<FriBidiLevel> embedding_levels;
FriBidiLevel max_level = getBidiEmbeddingLevels(txt32, embedding_levels);
// calculate the possible linebreak positions
std::vector<char> linebreaks(txt32.length());
set_linebreaks_utf32((utf32_t*)txt32.c_str(), txt32.length(), "", linebreaks.data());
// Get our harfbuzz font structs, TODO we need to do that for all the fonts
std::map<const std::shared_ptr<fontFace_c>, hb_font_t *> hb_ft_fonts;
for (const auto & a : attr)
{
if (hb_ft_fonts.find(a.font) == hb_ft_fonts.end())
{
hb_ft_fonts[a.font] = hb_ft_font_create(a.font->getFace(), NULL);
}
}
// Create a buffer for harfbuzz to use
hb_buffer_t *buf = hb_buffer_create();
std::string lan = attr[0].lang.substr(0, 2);
std::string s = attr[0].lang.substr(3, 4);
hb_script_t scr = hb_script_from_iso15924_tag(HB_TAG(s[0], s[1], s[2], s[3]));
hb_buffer_set_script(buf, scr);
// TODO must come either from text or from rules
hb_buffer_set_language(buf, hb_language_from_string(lan.c_str(), lan.length()));
size_t runstart = 0;
std::vector<runInfo> runs;
while (runstart < txt32.length())
{
size_t spos = runstart+1;
// find end of current run
while ( (spos < txt32.length())
&& (embedding_levels[runstart] == embedding_levels[spos])
&& (attr[runstart].font == attr[spos].font)
&& ( (linebreaks[spos-1] == LINEBREAK_NOBREAK)
|| (linebreaks[spos-1] == LINEBREAK_INSIDEACHAR)
)
)
{
spos++;
}
hb_buffer_add_utf32(buf, ((uint32_t*)txt32.c_str())+runstart, spos-runstart, 0, spos-runstart);
if (embedding_levels[runstart] % 2 == 0)
{
hb_buffer_set_direction(buf, HB_DIRECTION_LTR);
}
else
{
hb_buffer_set_direction(buf, HB_DIRECTION_RTL);
}
hb_shape(hb_ft_fonts[attr[runstart].font], buf, NULL, 0);
unsigned int glyph_count;
hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count);
hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count);
runInfo run;
run.dx = run.dy = 0;
run.embeddingLevel = embedding_levels[runstart];
run.linebreak = linebreaks[spos-1];
run.font = attr[runstart].font;
for (size_t j=0; j < glyph_count; ++j)
{
textLayout_c::commandData g;
g.glyphIndex = glyph_info[j].codepoint;
g.font = attr[runstart].font;
// TODO the other parameters
g.x = run.dx + (glyph_pos[j].x_offset/64);
g.y = run.dy - (glyph_pos[j].y_offset/64);
run.dx += glyph_pos[j].x_advance/64;
run.dy -= glyph_pos[j].y_advance/64;
g.r = attr[glyph_info[j].cluster + runstart].r;
g.g = attr[glyph_info[j].cluster + runstart].g;
g.b = attr[glyph_info[j].cluster + runstart].b;
g.command = textLayout_c::commandData::CMD_GLYPH;
run.run.push_back(g);
}
runs.push_back(run);
runstart = spos;
hb_buffer_reset(buf);
}
hb_buffer_destroy(buf);
for (auto & a : hb_ft_fonts)
hb_font_destroy(a.second);
std::vector<size_t> runorder(runs.size());
int n(0);
std::generate(runorder.begin(), runorder.end(), [&]{ return n++; });
// layout a run
// TODO take care of different font sizes of the different runs
runstart = 0;
int32_t ypos = 0;
textLayout_c l;
while (runstart < runs.size())
{
int32_t curAscend = runs[runstart].font->getAscender()/64;
int32_t curDescend = runs[runstart].font->getDescender()/64;
uint32_t curWidth = runs[runstart].dx;
size_t spos = runstart + 1;
while (spos < runs.size())
{
// check, if we can add another run
// TODO keep non break runs in mind
// TODO take properly care of spaces at the end of lines (they must be left out)
int32_t newAscend = std::max(curAscend, runs[spos].font->getAscender()/64);
int32_t newDescend = std::min(curDescend, runs[spos].font->getDescender()/64);
uint32_t newWidth = curWidth + runs[spos].dx;
if (shape.getLeft(ypos, ypos+newAscend-newDescend)+newWidth >
shape.getRight(ypos, ypos+newAscend-newDescend))
{
// next run would overrun
break;
}
// additional run fits
curAscend = newAscend;
curDescend = newDescend;
curWidth = newWidth;
spos++;
}
// reorder runs for current line
for (int i = max_level-1; i >= 0; i--)
{
// find starts of regions to reverse
for (size_t j = runstart; j < spos; j++)
{
if (runs[runorder[j]].embeddingLevel > i)
{
// find the end of the current regions
size_t k = j+1;
while (k < spos && runs[runorder[k]].embeddingLevel > i)
{
k++;
}
std::reverse(runorder.begin()+j, runorder.begin()+k);
j = k;
}
}
}
int32_t spaceLeft = shape.getRight(ypos, ypos+curAscend-curDescend) -
shape.getLeft(ypos, ypos+curAscend-curDescend);
spaceLeft -= curWidth;
int32_t xpos;
double spaceadder = 0;
if (align == "left")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend);
}
else if (align == "right")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft;
}
else if (align == "center")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft/2;
}
else if (align == "justify")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend);
// don't justify last paragraph
if (spos-runstart > 1 && spos < runs.size())
spaceadder = 1.0 * spaceLeft / (spos-runstart - 1);
}
ypos += curAscend;
for (size_t i = runstart; i < spos; i++)
{
l.addCommandVector(runs[runorder[i]].run, xpos+spaceadder*(i-runstart), ypos);
xpos += runs[runorder[i]].dx;
}
ypos -= curDescend;
runstart = spos;
}
// TODO proper font handling for multiple fonts in a line
l.setHeight(ypos);
return l;
}
static std::string normalizeHTML(const std::string & in, char prev)
{
std::string out;
for (auto a : in)
{
if (a == '\n' || a == '\r')
a = ' ';
if (a != ' ' || prev != ' ')
out += a;
prev = a;
}
return out;
}
void layoutXML_text(pugi::xml_node xml, const textStyleSheet_c & rules, std::u32string & txt,
std::vector<codepointAttributes> & attr)
{
for (const auto & i : xml)
{
if (i.type() == pugi::node_pcdata)
{
if (txt.length() == 0)
txt = u8_convertToU32(normalizeHTML(i.value(), ' '));
else
txt += u8_convertToU32(normalizeHTML(i.value(), txt[txt.length()-1]));
codepointAttributes a;
evalColor(rules.getValue(xml, "color"), a.r, a.g, a.b);
std::string fontFamily = rules.getValue(xml, "font-family");
std::string fontStyle = rules.getValue(xml, "font-style");
std::string fontVariant = rules.getValue(xml, "font-variant");
std::string fontWeight = rules.getValue(xml, "font-weight");
double fontSize = evalSize(rules.getValue(xml, "font-size"));
a.font = rules.findFamily(fontFamily)->getFont(64*fontSize, fontStyle, fontVariant, fontWeight);
a.lang = "en-eng";
while (attr.size() < txt.length())
attr.push_back(a);
}
else if (i.type() == pugi::node_element && std::string("i") == i.name())
{
layoutXML_text(i, rules, txt, attr);
}
else if (i.type() == pugi::node_element && std::string("div") == i.name())
{
layoutXML_text(i, rules, txt, attr);
}
}
}
// this whole stuff is a recursive descending parser of the XHTML stuff
textLayout_c layoutXML_P(const pugi::xml_node & xml, const textStyleSheet_c & rules, const shape_c & shape)
{
std::u32string txt;
std::vector<codepointAttributes> attr;
layoutXML_text(xml, rules, txt, attr);
return layoutParagraph(txt, attr, shape, rules.getValue(xml, "text-align"));
}
textLayout_c layoutXML_BODY(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
for (const auto & i : txt)
{
if ( (i.type() == pugi::node_element)
&& ( (std::string("p") == i.name())
|| (std::string("h1") == i.name())
|| (std::string("h2") == i.name())
|| (std::string("h3") == i.name())
|| (std::string("h4") == i.name())
|| (std::string("h5") == i.name())
|| (std::string("h6") == i.name())
)
)
{
// TODO rahmen und anderes beachten
l.append(layoutXML_P(i, rules, shape), 0, l.getHeight());
}
else if (i.type() == pugi::node_element && std::string("table") == i.name())
{
}
else
{
// TODO exception nothing else supported
}
}
return l;
}
textLayout_c layoutXML_HTML(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
bool headfound = false;
bool bodyfound = false;
for (const auto & i : txt)
{
if (std::string("head") == i.name() && !headfound)
{
headfound = true;
}
else if (std::string("body") == i.name() && !bodyfound)
{
bodyfound = true;
l = layoutXML_BODY(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXML(const pugi::xml_document & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
// we must have a HTML root node
for (const auto & i : txt)
{
if (std::string("html") == i.name())
{
l = layoutXML_HTML(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXHTML(const std::string & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
pugi::xml_document doc;
// TODO preprocess to get rid of linebreaks and multiple spaces
// TODO handle parser errors
doc.load_buffer(txt.c_str(), txt.length());
return layoutXML(doc, rules, shape);
}
textLayout_c layoutRaw(const std::string & txt, const std::shared_ptr<fontFace_c> font, const shape_c & shape, const std::string & language)
{
// when we layout raw text we
// only have to convert the text to utf-32
// and assign the given font and language to all the codepoints of that text
std::u32string txt32 = u8_convertToU32(txt);
std::vector<codepointAttributes> attr(txt32.size());
for (auto & i : attr)
{
i.r = i.g = i.b = 255;
i.font = font;
i.lang = language;
}
return layoutParagraph(txt32, attr, shape, "left");
}
<commit_msg>simplify code<commit_after>#include "layouter.h"
#include "utf-8.h"
#include <harfbuzz/hb.h>
#include <harfbuzz/hb-ft.h>
#include <fribidi/fribidi.h>
#include <linebreak.h>
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
typedef struct
{
std::vector<textLayout_c::commandData> run;
int dx, dy;
FriBidiLevel embeddingLevel;
char linebreak;
std::shared_ptr<fontFace_c> font;
} runInfo;
// TODO create a sharing structure, where we only
// define structures for each configuration once
// and link to it
// but for now it is good as it is
typedef struct
{
uint8_t r, g, b;
std::shared_ptr<fontFace_c> font;
std::string lang;
} codepointAttributes;
FriBidiLevel getBidiEmbeddingLevels(const std::u32string & txt32, std::vector<FriBidiLevel> & embedding_levels)
{
std::vector<FriBidiCharType> bidiTypes(txt32.length());
fribidi_get_bidi_types((uint32_t*)txt32.c_str(), txt32.length(), bidiTypes.data());
FriBidiParType base_dir = FRIBIDI_TYPE_LTR_VAL; // TODO depends on main script of text
embedding_levels.resize(txt32.length());
FriBidiLevel max_level = fribidi_get_par_embedding_levels(bidiTypes.data(), txt32.length(),
&base_dir, embedding_levels.data());
return max_level;
}
textLayout_c layoutParagraph(const std::u32string & txt32, const std::vector<codepointAttributes> & attr,
const shape_c & shape, const std::string & align)
{
// calculate embedding types for the text
std::vector<FriBidiLevel> embedding_levels;
FriBidiLevel max_level = getBidiEmbeddingLevels(txt32, embedding_levels);
// calculate the possible linebreak positions
std::vector<char> linebreaks(txt32.length());
set_linebreaks_utf32((utf32_t*)txt32.c_str(), txt32.length(), "", linebreaks.data());
// Get our harfbuzz font structs, TODO we need to do that for all the fonts
std::map<const std::shared_ptr<fontFace_c>, hb_font_t *> hb_ft_fonts;
for (const auto & a : attr)
{
if (hb_ft_fonts.find(a.font) == hb_ft_fonts.end())
{
hb_ft_fonts[a.font] = hb_ft_font_create(a.font->getFace(), NULL);
}
}
// Create a buffer for harfbuzz to use
hb_buffer_t *buf = hb_buffer_create();
std::string lan = attr[0].lang.substr(0, 2);
std::string s = attr[0].lang.substr(3, 4);
hb_script_t scr = hb_script_from_iso15924_tag(HB_TAG(s[0], s[1], s[2], s[3]));
hb_buffer_set_script(buf, scr);
// TODO must come either from text or from rules
hb_buffer_set_language(buf, hb_language_from_string(lan.c_str(), lan.length()));
size_t runstart = 0;
std::vector<runInfo> runs;
while (runstart < txt32.length())
{
size_t spos = runstart+1;
// find end of current run
while ( (spos < txt32.length())
&& (embedding_levels[runstart] == embedding_levels[spos])
&& (attr[runstart].font == attr[spos].font)
&& ( (linebreaks[spos-1] == LINEBREAK_NOBREAK)
|| (linebreaks[spos-1] == LINEBREAK_INSIDEACHAR)
)
)
{
spos++;
}
hb_buffer_add_utf32(buf, ((uint32_t*)txt32.c_str())+runstart, spos-runstart, 0, spos-runstart);
if (embedding_levels[runstart] % 2 == 0)
{
hb_buffer_set_direction(buf, HB_DIRECTION_LTR);
}
else
{
hb_buffer_set_direction(buf, HB_DIRECTION_RTL);
}
hb_shape(hb_ft_fonts[attr[runstart].font], buf, NULL, 0);
unsigned int glyph_count;
hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count);
hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count);
runInfo run;
run.dx = run.dy = 0;
run.embeddingLevel = embedding_levels[runstart];
run.linebreak = linebreaks[spos-1];
run.font = attr[runstart].font;
for (size_t j=0; j < glyph_count; ++j)
{
textLayout_c::commandData g;
g.glyphIndex = glyph_info[j].codepoint;
g.font = attr[runstart].font;
// TODO the other parameters
g.x = run.dx + (glyph_pos[j].x_offset/64);
g.y = run.dy - (glyph_pos[j].y_offset/64);
run.dx += glyph_pos[j].x_advance/64;
run.dy -= glyph_pos[j].y_advance/64;
g.r = attr[glyph_info[j].cluster + runstart].r;
g.g = attr[glyph_info[j].cluster + runstart].g;
g.b = attr[glyph_info[j].cluster + runstart].b;
g.command = textLayout_c::commandData::CMD_GLYPH;
run.run.push_back(g);
}
runs.push_back(run);
runstart = spos;
hb_buffer_reset(buf);
}
hb_buffer_destroy(buf);
for (auto & a : hb_ft_fonts)
hb_font_destroy(a.second);
std::vector<size_t> runorder(runs.size());
int n(0);
std::generate(runorder.begin(), runorder.end(), [&]{ return n++; });
// layout a run
// TODO take care of different font sizes of the different runs
runstart = 0;
int32_t ypos = 0;
textLayout_c l;
while (runstart < runs.size())
{
int32_t curAscend = runs[runstart].font->getAscender()/64;
int32_t curDescend = runs[runstart].font->getDescender()/64;
uint32_t curWidth = runs[runstart].dx;
size_t spos = runstart + 1;
while (spos < runs.size())
{
// check, if we can add another run
// TODO keep non break runs in mind
// TODO take properly care of spaces at the end of lines (they must be left out)
int32_t newAscend = std::max(curAscend, runs[spos].font->getAscender()/64);
int32_t newDescend = std::min(curDescend, runs[spos].font->getDescender()/64);
uint32_t newWidth = curWidth + runs[spos].dx;
if (shape.getLeft(ypos, ypos+newAscend-newDescend)+newWidth >
shape.getRight(ypos, ypos+newAscend-newDescend))
{
// next run would overrun
break;
}
// additional run fits
curAscend = newAscend;
curDescend = newDescend;
curWidth = newWidth;
spos++;
}
// reorder runs for current line
for (int i = max_level-1; i >= 0; i--)
{
// find starts of regions to reverse
for (size_t j = runstart; j < spos; j++)
{
if (runs[runorder[j]].embeddingLevel > i)
{
// find the end of the current regions
size_t k = j+1;
while (k < spos && runs[runorder[k]].embeddingLevel > i)
{
k++;
}
std::reverse(runorder.begin()+j, runorder.begin()+k);
j = k;
}
}
}
int32_t spaceLeft = shape.getRight(ypos, ypos+curAscend-curDescend) -
shape.getLeft(ypos, ypos+curAscend-curDescend);
spaceLeft -= curWidth;
int32_t xpos;
double spaceadder = 0;
if (align == "left")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend);
}
else if (align == "right")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft;
}
else if (align == "center")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft/2;
}
else if (align == "justify")
{
xpos = shape.getLeft(ypos, ypos+curAscend-curDescend);
// don't justify last paragraph
if (spos-runstart > 1 && spos < runs.size())
spaceadder = 1.0 * spaceLeft / (spos-runstart - 1);
}
ypos += curAscend;
for (size_t i = runstart; i < spos; i++)
{
l.addCommandVector(runs[runorder[i]].run, xpos+spaceadder*(i-runstart), ypos);
xpos += runs[runorder[i]].dx;
}
ypos -= curDescend;
runstart = spos;
}
// TODO proper font handling for multiple fonts in a line
l.setHeight(ypos);
return l;
}
static std::string normalizeHTML(const std::string & in, char prev)
{
std::string out;
for (auto a : in)
{
if (a == '\n' || a == '\r')
a = ' ';
if (a != ' ' || prev != ' ')
out += a;
prev = a;
}
return out;
}
void layoutXML_text(pugi::xml_node xml, const textStyleSheet_c & rules, std::u32string & txt,
std::vector<codepointAttributes> & attr)
{
for (const auto & i : xml)
{
if (i.type() == pugi::node_pcdata)
{
if (txt.length() == 0)
txt = u8_convertToU32(normalizeHTML(i.value(), ' '));
else
txt += u8_convertToU32(normalizeHTML(i.value(), txt[txt.length()-1]));
codepointAttributes a;
evalColor(rules.getValue(xml, "color"), a.r, a.g, a.b);
std::string fontFamily = rules.getValue(xml, "font-family");
std::string fontStyle = rules.getValue(xml, "font-style");
std::string fontVariant = rules.getValue(xml, "font-variant");
std::string fontWeight = rules.getValue(xml, "font-weight");
double fontSize = evalSize(rules.getValue(xml, "font-size"));
a.font = rules.findFamily(fontFamily)->getFont(64*fontSize, fontStyle, fontVariant, fontWeight);
a.lang = "en-eng";
while (attr.size() < txt.length())
attr.push_back(a);
}
else if ( (i.type() == pugi::node_element)
&& ( (std::string("i") == i.name())
|| (std::string("div") == i.name())
)
)
{
layoutXML_text(i, rules, txt, attr);
}
}
}
// this whole stuff is a recursive descending parser of the XHTML stuff
textLayout_c layoutXML_P(const pugi::xml_node & xml, const textStyleSheet_c & rules, const shape_c & shape)
{
std::u32string txt;
std::vector<codepointAttributes> attr;
layoutXML_text(xml, rules, txt, attr);
return layoutParagraph(txt, attr, shape, rules.getValue(xml, "text-align"));
}
textLayout_c layoutXML_BODY(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
for (const auto & i : txt)
{
if ( (i.type() == pugi::node_element)
&& ( (std::string("p") == i.name())
|| (std::string("h1") == i.name())
|| (std::string("h2") == i.name())
|| (std::string("h3") == i.name())
|| (std::string("h4") == i.name())
|| (std::string("h5") == i.name())
|| (std::string("h6") == i.name())
)
)
{
// TODO rahmen und anderes beachten
l.append(layoutXML_P(i, rules, shape), 0, l.getHeight());
}
else if (i.type() == pugi::node_element && std::string("table") == i.name())
{
}
else
{
// TODO exception nothing else supported
}
}
return l;
}
textLayout_c layoutXML_HTML(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
bool headfound = false;
bool bodyfound = false;
for (const auto & i : txt)
{
if (std::string("head") == i.name() && !headfound)
{
headfound = true;
}
else if (std::string("body") == i.name() && !bodyfound)
{
bodyfound = true;
l = layoutXML_BODY(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXML(const pugi::xml_document & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
textLayout_c l;
// we must have a HTML root node
for (const auto & i : txt)
{
if (std::string("html") == i.name())
{
l = layoutXML_HTML(i, rules, shape);
}
else
{
// nothing else permitted -> exception TODO
}
}
return l;
}
textLayout_c layoutXHTML(const std::string & txt, const textStyleSheet_c & rules, const shape_c & shape)
{
pugi::xml_document doc;
// TODO preprocess to get rid of linebreaks and multiple spaces
// TODO handle parser errors
doc.load_buffer(txt.c_str(), txt.length());
return layoutXML(doc, rules, shape);
}
textLayout_c layoutRaw(const std::string & txt, const std::shared_ptr<fontFace_c> font, const shape_c & shape, const std::string & language)
{
// when we layout raw text we
// only have to convert the text to utf-32
// and assign the given font and language to all the codepoints of that text
std::u32string txt32 = u8_convertToU32(txt);
std::vector<codepointAttributes> attr(txt32.size());
for (auto & i : attr)
{
i.r = i.g = i.b = 255;
i.font = font;
i.lang = language;
}
return layoutParagraph(txt32, attr, shape, "left");
}
<|endoftext|> |
<commit_before>#if defined(__cplusplus) && (__cplusplus >= 201103L)
#include <iostream>
#include <iomanip>
#include <chrono>
#include <atomic>
#ifdef SEQUENTIAL_CONSISTENCY
auto update_model = std::memory_order_seq_cst;
#else
auto update_model = std::memory_order_relaxed;
#endif
#ifdef _OPENMP
# include <omp.h>
# define OMP_PARALLEL _Pragma("omp parallel")
# define OMP_BARRIER _Pragma("omp barrier")
# define OMP_CRITICAL _Pragma("omp critical")
# ifdef SEQUENTIAL_CONSISTENCY
# define OMP_ATOMIC _Pragma("omp atomic seq_cst")
# define OMP_ATOMIC_CAPTURE _Pragma("omp atomic capture seq_cst")
# else
# define OMP_ATOMIC _Pragma("omp atomic")
# define OMP_ATOMIC_CAPTURE _Pragma("omp atomic capture")
# endif
#else
# error No OpenMP support!
#endif
typedef long long integer;
int main(int argc, char * argv[])
{
int iterations = (argc>1) ? atoi(argv[1]) : 10000000;
std::cout << "thread counter benchmark\n";
std::cout << "num threads = " << omp_get_max_threads() << "\n";
std::cout << "iterations = " << iterations << "\n";
#ifdef SEQUENTIAL_CONSISTENCY
std::cout << "memory model = " << "seq_cst";
#else
std::cout << "memory model = " << "relaxed";
#endif
std::cout << std::endl;
std::cout << "1) std::atomic_fetch_add(&counter, one)\n";
std::atomic<integer> counter = {0};
integer omp_counter = 0;
const integer one = 1;
OMP_PARALLEL
{
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
std::atomic_fetch_add(&counter, one);
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
}
}
std::cout << "2) ++counter\n";
counter = 0;
OMP_PARALLEL
{
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
++counter;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
}
}
std::cout << "3) counter++\n";
counter = 0;
OMP_PARALLEL
{
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
}
}
std::cout << "4) output = counter++\n";
counter = 0;
OMP_PARALLEL
{
integer output = -1;
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
output = counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
std::cout << output << std::endl;
}
}
std::cout << "5) output = std::atomic_fetch_add(&counter, one)\n";
counter = 0;
OMP_PARALLEL
{
integer output = -1;
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
output = std::atomic_fetch_add(&counter, one);
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
std::cout << output << std::endl;
}
}
std::cout << "6) #pragma omp atomic\n";
omp_counter = 0;
OMP_PARALLEL
{
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
OMP_ATOMIC
omp_counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << omp_counter << std::endl;
}
}
std::cout << "7) #pragma omp atomic capture\n";
counter = 0;
OMP_PARALLEL
{
integer output = -1;
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
OMP_ATOMIC_CAPTURE
output = omp_counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << omp_counter << std::endl;
std::cout << output << std::endl;
}
}
return 0;
}
#else // C++11
#error You need C++11 for this test!
#endif // C++11
<commit_msg>change to int64 to match double<commit_after>#if defined(__cplusplus) && (__cplusplus >= 201103L)
#include <iostream>
#include <iomanip>
#include <chrono>
#include <atomic>
#ifdef SEQUENTIAL_CONSISTENCY
auto update_model = std::memory_order_seq_cst;
#else
auto update_model = std::memory_order_relaxed;
#endif
#ifdef _OPENMP
# include <omp.h>
# define OMP_PARALLEL _Pragma("omp parallel")
# define OMP_BARRIER _Pragma("omp barrier")
# define OMP_CRITICAL _Pragma("omp critical")
# ifdef SEQUENTIAL_CONSISTENCY
# define OMP_ATOMIC _Pragma("omp atomic seq_cst")
# define OMP_ATOMIC_CAPTURE _Pragma("omp atomic capture seq_cst")
# else
# define OMP_ATOMIC _Pragma("omp atomic")
# define OMP_ATOMIC_CAPTURE _Pragma("omp atomic capture")
# endif
#else
# error No OpenMP support!
#endif
typedef int64_t integer;
int main(int argc, char * argv[])
{
int iterations = (argc>1) ? atoi(argv[1]) : 10000000;
std::cout << "thread counter benchmark\n";
std::cout << "num threads = " << omp_get_max_threads() << "\n";
std::cout << "iterations = " << iterations << "\n";
#ifdef SEQUENTIAL_CONSISTENCY
std::cout << "memory model = " << "seq_cst";
#else
std::cout << "memory model = " << "relaxed";
#endif
std::cout << std::endl;
std::cout << "1) std::atomic_fetch_add(&counter, one)\n";
std::atomic<integer> counter = {0};
integer omp_counter = 0;
const integer one = 1;
OMP_PARALLEL
{
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
std::atomic_fetch_add(&counter, one);
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
}
}
std::cout << "2) ++counter\n";
counter = 0;
OMP_PARALLEL
{
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
++counter;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
}
}
std::cout << "3) counter++\n";
counter = 0;
OMP_PARALLEL
{
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
}
}
std::cout << "4) output = counter++\n";
counter = 0;
OMP_PARALLEL
{
integer output = -1;
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
output = counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
std::cout << output << std::endl;
}
}
std::cout << "5) output = std::atomic_fetch_add(&counter, one)\n";
counter = 0;
OMP_PARALLEL
{
integer output = -1;
std::atomic_thread_fence(std::memory_order_seq_cst);
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
output = std::atomic_fetch_add(&counter, one);
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
std::atomic_thread_fence(std::memory_order_seq_cst);
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << counter << std::endl;
std::cout << output << std::endl;
}
}
std::cout << "6) #pragma omp atomic\n";
omp_counter = 0;
OMP_PARALLEL
{
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
OMP_ATOMIC
omp_counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << omp_counter << std::endl;
}
}
std::cout << "7) #pragma omp atomic capture\n";
counter = 0;
OMP_PARALLEL
{
integer output = -1;
/// START TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();
for (int i=0; i<iterations; ++i) {
OMP_ATOMIC_CAPTURE
output = omp_counter++;
}
/// STOP TIME
OMP_BARRIER
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
/// PRINT TIME
std::chrono::duration<double> dt = std::chrono::duration_cast<std::chrono::duration<double>>(t1-t0);
OMP_CRITICAL
{
std::cout << "total time elapsed = " << dt.count() << "\n";
std::cout << "time per iteration = " << dt.count()/iterations << "\n";
std::cout << omp_counter << std::endl;
std::cout << output << std::endl;
}
}
return 0;
}
#else // C++11
#error You need C++11 for this test!
#endif // C++11
<|endoftext|> |
<commit_before>#include "UpdateDialogGtkFactory.h"
#include "FileUtils.h"
#include "Log.h"
#include "UpdateDialog.h"
#include "StringUtils.h"
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
class UpdateDialogGtk;
// GTK updater UI library embedded into
// the updater binary
extern unsigned char libupdatergtk_so[];
extern unsigned int libupdatergtk_so_len;
// pointers to helper functions in the GTK updater UI library
UpdateDialogGtk* (*update_dialog_gtk_new)() = 0;
#if __cplusplus >= 201103L
#define TYPEOF(x) decltype(x)
#else
#define TYPEOF(x) typeof(x)
#endif
#define BIND_FUNCTION(library,function) \
function = reinterpret_cast<TYPEOF(function)>(dlsym(library,#function));
bool extractFileFromBinary(int fd, const void* buffer, size_t length)
{
size_t count = write(fd,buffer,length);
close(fd);
return count >= length;
}
UpdateDialog* UpdateDialogGtkFactory::createDialog()
{
char* libPath = strdup(std::string("/tmp/mendeley-libUpdaterGtk.so.XXXXXX").c_str());
int libFd = mkostemp(libPath, O_CREAT | O_WRONLY | O_TRUNC);
if (libFd == -1)
{
LOG(Warn,"Failed to create temporary file - " + std::string(strerror(errno)));
return 0;
}
if (!extractFileFromBinary(libFd,libupdatergtk_so,libupdatergtk_so_len))
{
LOG(Warn,"Failed to load the GTK UI library - " + std::string(strerror(errno)));
return 0;
}
void* gtkLib = dlopen(libPath,RTLD_LAZY);
if (!gtkLib)
{
LOG(Warn,"Failed to load the GTK UI - " + std::string(dlerror()));
return 0;
}
BIND_FUNCTION(gtkLib,update_dialog_gtk_new);
FileUtils::removeFile(libPath);
return reinterpret_cast<UpdateDialog*>(update_dialog_gtk_new());
}
<commit_msg>Simplifies creating the char*, avoids using useless std::string<commit_after>#include "UpdateDialogGtkFactory.h"
#include "FileUtils.h"
#include "Log.h"
#include "UpdateDialog.h"
#include "StringUtils.h"
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
class UpdateDialogGtk;
// GTK updater UI library embedded into
// the updater binary
extern unsigned char libupdatergtk_so[];
extern unsigned int libupdatergtk_so_len;
// pointers to helper functions in the GTK updater UI library
UpdateDialogGtk* (*update_dialog_gtk_new)() = 0;
#if __cplusplus >= 201103L
#define TYPEOF(x) decltype(x)
#else
#define TYPEOF(x) typeof(x)
#endif
#define BIND_FUNCTION(library,function) \
function = reinterpret_cast<TYPEOF(function)>(dlsym(library,#function));
bool extractFileFromBinary(int fd, const void* buffer, size_t length)
{
size_t count = write(fd,buffer,length);
close(fd);
return count >= length;
}
UpdateDialog* UpdateDialogGtkFactory::createDialog()
{
char* libPath = strdup("/tmp/mendeley-libUpdaterGtk.so.XXXXXX");
int libFd = mkostemp(libPath, O_CREAT | O_WRONLY | O_TRUNC);
if (libFd == -1)
{
LOG(Warn,"Failed to create temporary file - " + std::string(strerror(errno)));
return 0;
}
if (!extractFileFromBinary(libFd,libupdatergtk_so,libupdatergtk_so_len))
{
LOG(Warn,"Failed to load the GTK UI library - " + std::string(strerror(errno)));
return 0;
}
void* gtkLib = dlopen(libPath,RTLD_LAZY);
if (!gtkLib)
{
LOG(Warn,"Failed to load the GTK UI - " + std::string(dlerror()));
return 0;
}
BIND_FUNCTION(gtkLib,update_dialog_gtk_new);
FileUtils::removeFile(libPath);
return reinterpret_cast<UpdateDialog*>(update_dialog_gtk_new());
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.35.50); FILE MERGED 2006/05/23 18:34:32 sb 1.35.50.3: RESYNC: (1.37-1.38); FILE MERGED 2006/04/07 18:14:16 sb 1.35.50.2: RESYNC: (1.35-1.37); FILE MERGED 2006/02/17 16:56:31 cl 1.35.50.1: warning free code changes<commit_after><|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "VideoSessionWidget.h"
#include "UiDefines.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
namespace CommunicationUI
{
VideoSessionWidget::VideoSessionWidget(QWidget *parent, Communication::VoiceSessionInterface *video_session, QString &my_name, QString &his_name)
: QWidget(parent),
video_session_(video_session),
my_name_(my_name),
his_name_(his_name),
internal_widget_(0),
internal_v_layout_(0),
internal_h_layout_(0),
internal_v_layout_local_(0),
internal_v_layout_remote_(0),
local_video_(0),
remote_video_(0),
controls_local_widget_(new QWidget(this)),
controls_remote_widget_(new QWidget(this))
{
// Init all ui elements
video_session_ui_.setupUi(this);
controls_local_ui_.setupUi(controls_local_widget_);
controls_local_ui_.horizontalLayout->insertSpacerItem(2, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_local_widget_->hide();
controls_remote_ui_.setupUi(controls_remote_widget_);
controls_remote_ui_.horizontalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_remote_ui_.audioCheckBox->setEnabled(false);
controls_remote_ui_.videoCheckBox->setEnabled(false);
controls_remote_widget_->hide();
// Update widget states
SessionStateChanged(video_session_->GetState());
AudioStreamStateChanged(video_session_->GetAudioStreamState());
VideoStreamStateChanged(video_session_->GetVideoStreamState());
UpdateLocalVideoControls(video_session_->IsSendingVideoData());
UpdateLocalAudioControls(video_session_->IsSendingAudioData());
UpdateRemoteVideoControls(video_session_->IsReceivingVideoData());
UpdateRemoteAudioControls(video_session_->IsReceivingAudioData());
// CLOSE TAB
connect(video_session_ui_.closePushButton, SIGNAL( clicked() ),
this, SLOT( CloseSession() ));
// CONNECTION AND STREAM STATES
connect(video_session_, SIGNAL( StateChanged(Communication::VoiceSessionInterface::State) ),
this, SLOT( SessionStateChanged(Communication::VoiceSessionInterface::State) ));
connect(video_session_, SIGNAL( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
connect(video_session_, SIGNAL( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
// AUDIO / VIDEO STATES
connect(video_session_, SIGNAL( SendingVideoData(bool) ),
this, SLOT( UpdateLocalVideoControls(bool) ));
connect(video_session_, SIGNAL( SendingAudioData(bool) ),
this, SLOT( UpdateLocalAudioControls(bool) ));
connect(video_session_, SIGNAL( ReceivingVideoData(bool) ),
this, SLOT( UpdateRemoteVideoControls(bool) ));
connect(video_session_, SIGNAL( ReceivingAudioData(bool) ),
this, SLOT( UpdateRemoteAudioControls(bool) ));
}
VideoSessionWidget::~VideoSessionWidget()
{
// CRASH HERE after session close
if (internal_v_layout_local_ && local_video_)
internal_v_layout_local_->removeWidget(local_video_);
if (internal_v_layout_remote_ && remote_video_)
internal_v_layout_remote_->removeWidget(remote_video_);
SAFE_DELETE(internal_widget_);
}
void VideoSessionWidget::SessionStateChanged(Communication::VoiceSessionInterface::State new_state)
{
SAFE_DELETE(internal_widget_);
switch (new_state)
{
case Communication::VoiceSessionInterface::STATE_OPEN:
ShowVideoWidgets();
video_session_ui_.connectionStatus->setText("Open");
break;
case Communication::VoiceSessionInterface::STATE_CLOSED:
video_session_ui_.connectionStatus->setText("This coversation has been closed");
break;
case Communication::VoiceSessionInterface::STATE_ERROR:
video_session_ui_.mainVerticalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding));
video_session_ui_.connectionStatus->setText("Connection failed");
break;
case Communication::VoiceSessionInterface::STATE_INITIALIZING:
video_session_ui_.connectionStatus->setText("Initializing...");
break;
case Communication::VoiceSessionInterface::STATE_RINGING_LOCAL:
ShowConfirmationWidget();
video_session_ui_.connectionStatus->setText("Waiting for your confirmation...");
break;
case Communication::VoiceSessionInterface::STATE_RINGING_REMOTE:
video_session_ui_.connectionStatus->setText(QString("Waiting confirmation from %1").arg(his_name_));
break;
}
}
void VideoSessionWidget::AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.audioStatus->setText("Connecting");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.audioStatus->setText("Connected");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.audioStatus->setText("Disconnected");
break;
}
}
void VideoSessionWidget::VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.videoStatus->setText("Connecting");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.videoStatus->setText("Connected");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.videoStatus->setText("Disconnected");
break;
}
}
void VideoSessionWidget::LocalVideoStateChange(int state)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendVideoData(enabled);
UpdateLocalVideoControls(enabled);
}
void VideoSessionWidget::UpdateLocalVideoControls(bool state)
{
controls_local_ui_.videoCheckBox->setChecked(state);
if (state)
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
else
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::LocalAudioStateChange(int state)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendAudioData(enabled);
UpdateLocalAudioControls(enabled);
}
void VideoSessionWidget::UpdateLocalAudioControls(bool state)
{
controls_local_ui_.audioCheckBox->setChecked(state);
if (state)
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::UpdateRemoteVideoControls(bool state)
{
controls_remote_ui_.videoCheckBox->setChecked(state);
if (state)
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
else
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::UpdateRemoteAudioControls(bool state)
{
controls_remote_ui_.audioCheckBox->setChecked(state);
if (state)
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::ShowConfirmationWidget()
{
// Init widgets
internal_widget_ = new QWidget();
internal_v_layout_ = new QVBoxLayout(internal_widget_);
internal_h_layout_ = new QHBoxLayout();
QLabel *question_label = new QLabel(QString("%1 wants to start a video conversation with you").arg(his_name_));
QPushButton *accept_button = new QPushButton("Accept", internal_widget_);
QPushButton *decline_button = new QPushButton("Decline", internal_widget_);
// Stylesheets for background and text color
internal_widget_->setObjectName("confirmationWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#confirmationWidget { background-color: rgb(255,255,255); } QLabel { color: rgb(0,0,0); }"));
// Add widgets to layouts
internal_h_layout_->setSpacing(6);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_h_layout_->addWidget(question_label);
internal_h_layout_->addWidget(accept_button);
internal_h_layout_->addWidget(decline_button);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
internal_v_layout_->addLayout(internal_h_layout_);
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
// Add bottom layout to widget, insert widget at top of parent widgets layout
internal_widget_->setLayout(internal_v_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
// Connect signals
connect(accept_button, SIGNAL( clicked() ), video_session_, SLOT( Accept() ));
connect(decline_button, SIGNAL( clicked() ), video_session_, SLOT( Reject() ));
}
void VideoSessionWidget::ShowVideoWidgets()
{
// Init widgets
internal_widget_ = new QWidget();
internal_h_layout_ = new QHBoxLayout(internal_widget_);
internal_v_layout_local_ = new QVBoxLayout();
internal_v_layout_remote_ = new QVBoxLayout();
// Local video and controls
local_video_ = (QWidget *)(video_session_->GetLocallyCapturedVideo());
controls_local_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
QLabel *sending_label = new QLabel("Sending", this);
sending_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
sending_label->setAlignment(Qt::AlignCenter);
sending_label->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
internal_v_layout_local_->addWidget(sending_label);
internal_v_layout_local_->addWidget(local_video_);
internal_v_layout_local_->addWidget(controls_local_widget_);
// Remote video and contols
remote_video_ = (QWidget *)(video_session_->GetReceivedVideo());
controls_remote_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
QLabel *receiving_label = new QLabel("Receiving", this);
receiving_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
receiving_label->setAlignment(Qt::AlignCenter);
receiving_label->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
internal_v_layout_remote_->addWidget(receiving_label);
internal_v_layout_remote_->addWidget(remote_video_);
internal_v_layout_remote_->addWidget(controls_remote_widget_);
// But our video containers to the main horizontal layout
internal_h_layout_->setSpacing(6);
internal_h_layout_->addLayout(internal_v_layout_local_);
internal_h_layout_->addLayout(internal_v_layout_remote_);
// Add to main widgets layout
internal_widget_->setLayout(internal_h_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
// Some stylesheets for consistent color theme
// otherwise this will inherit transparent background from parent widget
internal_widget_->setObjectName("videoSessionWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#videoSessionWidget { background-color: rgb(255,255,255); } QLabel { color: rgb(0,0,0); }"));
controls_local_widget_->show();
controls_remote_widget_->show();
// Connect checkboxes to control video and audio sending
connect(controls_local_ui_.videoCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalVideoStateChange(int) ));
connect(controls_local_ui_.audioCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalAudioStateChange(int) ));
}
void VideoSessionWidget::CloseSession()
{
video_session_->Close();
emit Closed(his_name_);
}
}<commit_msg>Added null pointer checks.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "VideoSessionWidget.h"
#include "UiDefines.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
namespace CommunicationUI
{
VideoSessionWidget::VideoSessionWidget(QWidget *parent, Communication::VoiceSessionInterface *video_session, QString &my_name, QString &his_name)
: QWidget(parent),
video_session_(video_session),
my_name_(my_name),
his_name_(his_name),
internal_widget_(0),
internal_v_layout_(0),
internal_h_layout_(0),
internal_v_layout_local_(0),
internal_v_layout_remote_(0),
local_video_(0),
remote_video_(0),
controls_local_widget_(new QWidget(this)),
controls_remote_widget_(new QWidget(this))
{
// Init all ui elements
video_session_ui_.setupUi(this);
controls_local_ui_.setupUi(controls_local_widget_);
controls_local_ui_.horizontalLayout->insertSpacerItem(2, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_local_widget_->hide();
controls_remote_ui_.setupUi(controls_remote_widget_);
controls_remote_ui_.horizontalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed));
controls_remote_ui_.audioCheckBox->setEnabled(false);
controls_remote_ui_.videoCheckBox->setEnabled(false);
controls_remote_widget_->hide();
// Update widget states
SessionStateChanged(video_session_->GetState());
AudioStreamStateChanged(video_session_->GetAudioStreamState());
VideoStreamStateChanged(video_session_->GetVideoStreamState());
UpdateLocalVideoControls(video_session_->IsSendingVideoData());
UpdateLocalAudioControls(video_session_->IsSendingAudioData());
UpdateRemoteVideoControls(video_session_->IsReceivingVideoData());
UpdateRemoteAudioControls(video_session_->IsReceivingAudioData());
// CLOSE TAB
connect(video_session_ui_.closePushButton, SIGNAL( clicked() ),
this, SLOT( CloseSession() ));
// CONNECTION AND STREAM STATES
connect(video_session_, SIGNAL( StateChanged(Communication::VoiceSessionInterface::State) ),
this, SLOT( SessionStateChanged(Communication::VoiceSessionInterface::State) ));
connect(video_session_, SIGNAL( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
connect(video_session_, SIGNAL( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ),
this, SLOT( VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState) ));
// AUDIO / VIDEO STATES
connect(video_session_, SIGNAL( SendingVideoData(bool) ),
this, SLOT( UpdateLocalVideoControls(bool) ));
connect(video_session_, SIGNAL( SendingAudioData(bool) ),
this, SLOT( UpdateLocalAudioControls(bool) ));
connect(video_session_, SIGNAL( ReceivingVideoData(bool) ),
this, SLOT( UpdateRemoteVideoControls(bool) ));
connect(video_session_, SIGNAL( ReceivingAudioData(bool) ),
this, SLOT( UpdateRemoteAudioControls(bool) ));
}
VideoSessionWidget::~VideoSessionWidget()
{
// CRASH HERE after session close
//if (internal_v_layout_local_ && local_video_)
// internal_v_layout_local_->removeWidget(local_video_);
//if (internal_v_layout_remote_ && remote_video_)
// internal_v_layout_remote_->removeWidget(remote_video_);
SAFE_DELETE(internal_widget_);
}
void VideoSessionWidget::SessionStateChanged(Communication::VoiceSessionInterface::State new_state)
{
SAFE_DELETE(internal_widget_);
switch (new_state)
{
case Communication::VoiceSessionInterface::STATE_OPEN:
ShowVideoWidgets();
video_session_ui_.connectionStatus->setText("Open");
break;
case Communication::VoiceSessionInterface::STATE_CLOSED:
video_session_ui_.connectionStatus->setText("This coversation has been closed");
break;
case Communication::VoiceSessionInterface::STATE_ERROR:
video_session_ui_.mainVerticalLayout->insertSpacerItem(0, new QSpacerItem(1,1, QSizePolicy::Fixed, QSizePolicy::Expanding));
video_session_ui_.connectionStatus->setText("Connection failed");
break;
case Communication::VoiceSessionInterface::STATE_INITIALIZING:
video_session_ui_.connectionStatus->setText("Initializing...");
break;
case Communication::VoiceSessionInterface::STATE_RINGING_LOCAL:
ShowConfirmationWidget();
video_session_ui_.connectionStatus->setText("Waiting for your confirmation...");
break;
case Communication::VoiceSessionInterface::STATE_RINGING_REMOTE:
video_session_ui_.connectionStatus->setText(QString("Waiting confirmation from %1").arg(his_name_));
break;
}
}
void VideoSessionWidget::AudioStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.audioStatus->setText("Connecting");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.audioStatus->setText("Connected");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.audioStatus->setText("Disconnected");
break;
}
}
void VideoSessionWidget::VideoStreamStateChanged(Communication::VoiceSessionInterface::StreamState new_state)
{
switch (new_state)
{
case Communication::VoiceSessionInterface::SS_CONNECTING:
video_session_ui_.videoStatus->setText("Connecting");
break;
case Communication::VoiceSessionInterface::SS_CONNECTED:
video_session_ui_.videoStatus->setText("Connected");
break;
case Communication::VoiceSessionInterface::SS_DISCONNECTED:
video_session_ui_.videoStatus->setText("Disconnected");
break;
}
}
void VideoSessionWidget::LocalVideoStateChange(int state)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendVideoData(enabled);
UpdateLocalVideoControls(enabled);
}
void VideoSessionWidget::UpdateLocalVideoControls(bool state)
{
controls_local_ui_.videoCheckBox->setChecked(state);
if (state)
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
else
controls_local_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::LocalAudioStateChange(int state)
{
bool enabled = false;
if (state == Qt::Checked)
enabled = true;
else if (state == Qt::Unchecked)
enabled = false;
video_session_->SendAudioData(enabled);
UpdateLocalAudioControls(enabled);
}
void VideoSessionWidget::UpdateLocalAudioControls(bool state)
{
controls_local_ui_.audioCheckBox->setChecked(state);
if (state)
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_local_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::UpdateRemoteVideoControls(bool state)
{
controls_remote_ui_.videoCheckBox->setChecked(state);
if (state)
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: green;"));
else
controls_remote_ui_.videoCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::UpdateRemoteAudioControls(bool state)
{
controls_remote_ui_.audioCheckBox->setChecked(state);
if (state)
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: green;"));
else
controls_remote_ui_.audioCheckBox->setStyleSheet(QString("color: red;"));
}
void VideoSessionWidget::ShowConfirmationWidget()
{
// Init widgets
internal_widget_ = new QWidget();
internal_v_layout_ = new QVBoxLayout(internal_widget_);
internal_h_layout_ = new QHBoxLayout();
QLabel *question_label = new QLabel(QString("%1 wants to start a video conversation with you").arg(his_name_));
QPushButton *accept_button = new QPushButton("Accept", internal_widget_);
QPushButton *decline_button = new QPushButton("Decline", internal_widget_);
// Stylesheets for background and text color
internal_widget_->setObjectName("confirmationWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#confirmationWidget { background-color: rgb(255,255,255); } QLabel { color: rgb(0,0,0); }"));
// Add widgets to layouts
internal_h_layout_->setSpacing(6);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_h_layout_->addWidget(question_label);
internal_h_layout_->addWidget(accept_button);
internal_h_layout_->addWidget(decline_button);
internal_h_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Preferred));
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
internal_v_layout_->addLayout(internal_h_layout_);
internal_v_layout_->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Preferred, QSizePolicy::Expanding));
// Add bottom layout to widget, insert widget at top of parent widgets layout
internal_widget_->setLayout(internal_v_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
// Connect signals
connect(accept_button, SIGNAL( clicked() ), video_session_, SLOT( Accept() ));
connect(decline_button, SIGNAL( clicked() ), video_session_, SLOT( Reject() ));
}
void VideoSessionWidget::ShowVideoWidgets()
{
// Init widgets
internal_widget_ = new QWidget();
internal_h_layout_ = new QHBoxLayout(internal_widget_);
internal_v_layout_local_ = new QVBoxLayout();
internal_v_layout_remote_ = new QVBoxLayout();
// Local video and controls
local_video_ = (QWidget *)(video_session_->GetLocallyCapturedVideo());
controls_local_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
QLabel *sending_label = new QLabel("Sending", this);
sending_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
sending_label->setAlignment(Qt::AlignCenter);
sending_label->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
internal_v_layout_local_->addWidget(sending_label);
if (local_video_)
internal_v_layout_local_->addWidget(local_video_);
internal_v_layout_local_->addWidget(controls_local_widget_);
// Remote video and contols
remote_video_ = (QWidget *)(video_session_->GetReceivedVideo());
controls_remote_widget_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
QLabel *receiving_label = new QLabel("Receiving", this);
receiving_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
receiving_label->setAlignment(Qt::AlignCenter);
receiving_label->setStyleSheet(QString("font: 12pt 'Estrangelo Edessa'; color: rgb(69, 159, 255);"));
internal_v_layout_remote_->addWidget(receiving_label);
if (remote_video_)
internal_v_layout_remote_->addWidget(remote_video_);
internal_v_layout_remote_->addWidget(controls_remote_widget_);
// But our video containers to the main horizontal layout
internal_h_layout_->setSpacing(6);
internal_h_layout_->addLayout(internal_v_layout_local_);
internal_h_layout_->addLayout(internal_v_layout_remote_);
// Add to main widgets layout
internal_widget_->setLayout(internal_h_layout_);
video_session_ui_.mainVerticalLayout->insertWidget(0, internal_widget_);
// Some stylesheets for consistent color theme
// otherwise this will inherit transparent background from parent widget
internal_widget_->setObjectName("videoSessionWidget");
internal_widget_->setStyleSheet("");
internal_widget_->setStyleSheet(QString("QWidget#videoSessionWidget { background-color: rgb(255,255,255); } QLabel { color: rgb(0,0,0); }"));
controls_local_widget_->show();
controls_remote_widget_->show();
// Connect checkboxes to control video and audio sending
connect(controls_local_ui_.videoCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalVideoStateChange(int) ));
connect(controls_local_ui_.audioCheckBox, SIGNAL( stateChanged(int) ),
this, SLOT( LocalAudioStateChange(int) ));
}
void VideoSessionWidget::CloseSession()
{
video_session_->Close();
emit Closed(his_name_);
}
}<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <unordered_set>
#include <unordered_map>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W, N;
typedef tuple<int, int> point;
set<point> S;
bool valid(int x, int y) {
return 0 <= x && x < H && 0 <= y && y < W;
}
ll ans[10];
int main () {
cin >> H >> W >> N;
for (auto i = 0; i < N; ++i) {
int a, b;
cin >> a >> b;
a--;
b--;
S.insert(point(a, b));
}
for (auto x : S) {
int a = get<0>(x);
int b = get<1>(x);
for (auto i = 0; i < 3; ++i) {
for (auto j = 0; j < 3; ++j) {
int ka = a - i;
int kb = b - j;
int cnt = 0;
bool ok = true;
for (auto k = 0; k < 3; ++k) {
for (auto l = 0; l < 3; ++l) {
int na = ka + k;
int nb = kb + l;
if (!valid(na, nb)) {
ok = false;
} else {
if (S.find(point(na, nb)) != S.end()) {
cnt++;
}
}
if (ok) {
ans[cnt]++;
}
}
}
}
}
}
ll sum = 0;
for (auto i = 1; i < 10; ++i) {
ans[i] /= i;
sum += ans[i];
}
ans[0] = (H-2) * (W-2) - sum;
for (auto i = 0; i < 10; ++i) {
cout << ans[i] << endl;
}
}
<commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <unordered_set>
#include <unordered_map>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W, N;
typedef tuple<int, int> point;
set<point> S;
bool valid(int x, int y) {
return 0 <= x && x < H && 0 <= y && y < W;
}
ll ans[10];
int main () {
cin >> H >> W >> N;
for (auto i = 0; i < N; ++i) {
int a, b;
cin >> a >> b;
a--;
b--;
S.insert(point(a, b));
}
for (auto x : S) {
int a = get<0>(x);
int b = get<1>(x);
for (auto i = 0; i < 3; ++i) {
for (auto j = 0; j < 3; ++j) {
int ka = a - i;
int kb = b - j;
int cnt = 0;
bool ok = true;
for (auto k = 0; k < 3; ++k) {
for (auto l = 0; l < 3; ++l) {
int na = ka + k;
int nb = kb + l;
if (!valid(na, nb)) {
ok = false;
} else {
if (S.find(point(na, nb)) != S.end()) {
cnt++;
}
}
}
}
if (ok) {
ans[cnt]++;
}
}
}
}
ll sum = 0;
for (auto i = 1; i < 10; ++i) {
ans[i] /= i;
sum += ans[i];
}
ans[0] = (H-2) * (W-2) - sum;
for (auto i = 0; i < 10; ++i) {
cout << ans[i] << endl;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
class SegTree { // index starts at 0.
public:
int N;
int* dat;
static int INFTY; // (1 << 31) - 1;
SegTree(int n) {
N = 1;
while (N < n) N *= 2;
dat = new int[2 * N - 1];
for (auto i = 0; i < 2 * N - 1; ++i) {
dat[i] = INFTY;
}
}
~SegTree() {
delete[] dat;
}
void update(int k, int a) {
k += N - 1;
dat[k] = a;
while (k > 0) {
k = (k - 1)/2;
dat[k] = min(dat[k * 2 + 1], dat[k * 2 + 2]);
}
}
int find(int a, int b, int k, int l, int r) {
if (r <= a || b <= l) return INFTY;
if (a <= l && r <= b) return dat[k];
int vl = find(a, b, k * 2 + 1, l, (l + r) / 2);
int vr = find(a, b, k * 2 + 2, (l + r) / 2, r);
return min(vl, vr);
}
int find(int a, int b) {
return find(a, b, 0, 0, N);
}
};
int SegTree::INFTY = 2147483647; // (1 << 31) - 1;
int N;
int b[200020];
int Q;
vector<int> V[200020];
int score(int x) {
if (b[x] == 0) return -1;
return 1;
}
int main () {
cin >> N;
for (auto i = 0; i < N; ++i) {
cin >> b[i];
}
cin >> Q;
for (auto i = 0; i < Q; ++i) {
int l, r;
cin >> l >> r;
l--;
r--;
V[l].push_back(r);
}
for (auto i = 0; i < N; ++i) {
sort(V[i].begin(), V[i].end());
}
int zeros = 0;
for (auto i = 0; i < N; ++i) {
if (b[i] == 0) ++zeros;
}
SegTree S(N+1);
S.update(0, zeros);
for (auto i = 0; i < N; ++i) {
for (auto x : V[i]) {
S.update(x, S.find(i, x+1));
}
S.update(i+1, min(S.find(i, i+1) + score(i), S.find(i+1, i+2)));
}
cout << S.find(N, N+1) << endl;
}
<commit_msg>tried F.cpp to 'F'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
class SegTree { // index starts at 0.
public:
int N;
int* dat;
static int INFTY; // (1 << 31) - 1;
SegTree(int n) {
N = 1;
while (N < n) N *= 2;
dat = new int[2 * N - 1];
for (auto i = 0; i < 2 * N - 1; ++i) {
dat[i] = INFTY;
}
}
~SegTree() {
delete[] dat;
}
void update(int k, int a) {
k += N - 1;
dat[k] = a;
while (k > 0) {
k = (k - 1)/2;
dat[k] = min(dat[k * 2 + 1], dat[k * 2 + 2]);
}
}
int find(int a, int b, int k, int l, int r) {
if (r <= a || b <= l) return INFTY;
if (a <= l && r <= b) return dat[k];
int vl = find(a, b, k * 2 + 1, l, (l + r) / 2);
int vr = find(a, b, k * 2 + 2, (l + r) / 2, r);
return min(vl, vr);
}
int find(int a, int b) {
return find(a, b, 0, 0, N);
}
};
int SegTree::INFTY = 2147483647; // (1 << 31) - 1;
int N;
int b[200020];
int Q;
vector<int> V[200020];
int score(int x) {
if (b[x] == 0) return -1;
return 1;
}
int main () {
cin >> N;
for (auto i = 0; i < N; ++i) {
cin >> b[i];
}
cin >> Q;
for (auto i = 0; i < Q; ++i) {
int l, r;
cin >> l >> r;
l--;
r--;
V[l].push_back(r);
}
for (auto i = 0; i < N; ++i) {
sort(V[i].begin(), V[i].end());
}
int zeros = 0;
for (auto i = 0; i < N; ++i) {
if (b[i] == 0) ++zeros;
}
SegTree S(N+1);
S.update(0, zeros);
for (auto i = 0; i < N; ++i) {
for (auto x : V[i]) {
S.update(x, S.find(i, x+1));
}
S.update(i+1, min(S.find(i, i+1) + score(i), S.find(i+1, i+2)));
cerr << "DP[" << i+1 << "] = " << S.find(i+1, i+2) << endl;
}
cout << S.find(N, N+1) << endl;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string rep(string c, int n) {
string ans = "";
for (auto i = 0; i < n; ++i) {
ans += c;
}
return ans;
}
string repa(int n) {
return rep("A", n);
}
string repb(int n) {
return rep("B", n);
}
ll calc_K(ll A, ll B) {
ll ub = 500000010;
ll lb = 0;
while (ub - lb > 1) {
ll t = (ub+lb)/2;
if (A <= (B+1) * t && B <= (A+1) * t) {
ub = t;
} else {
lb = t;
}
}
return ub;
}
string f(ll A, ll B, ll C, ll D) {
ll K = calc_K(A, B);
ll ub = A+B;
ll lb = -1;
while (ub - lb > 1) {
ll t = (ub+lb)/2;
ll b = t/(K+1);
ll a = t - b;
ll rema = A - a;
ll remb = B - b;
if (remb <= (rema+1) * K) {
ub = t;
} else {
lb = t;
}
}
assert(false);
ll L = ub;
if (D <= L) {
int back = (C/(K+1)) * (K+1);
C -= back;
D -= back;
string X = rep(repa(K) + "B", 100);
return X.substr(C-1, D-C+1);
} else if (C > L) {
C = A+B+1-C;
D = A+B+1-D;
int back = (C/(K+1)) * (K+1);
C -= back;
D -= back;
string X = rep(repb(K) + "A", 100);
string Y = X.substr(D-1, D-C+1);
reverse(Y.begin(), Y.end());
return Y;
} else {
int rema = L%(K+1);
int remb = (A+B-L)%(K+1);
string X = repa(rema) + repb(remb);
X = rep(repa(K) + "B", 100) + X + rep("A" + repb(K), 100);
int back = L - (100 * (K+1) + rema);
C -= back;
D -= back;
return X.substr(C-1, D-C+1);
}
}
int main () {
int Q;
cin >> Q;
int A[1010], B[1010], C[1010], D[1010];
for (auto i = 0; i < Q; ++i) {
cin >> A[i] >> B[i] >> C[i] >> D[i];
}
for (auto i = 0; i < Q; ++i) {
string X = f(A[i], B[i], C[i], D[i]);
cout << X << endl;
}
}
<commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string rep(string c, int n) {
string ans = "";
for (auto i = 0; i < n; ++i) {
ans += c;
}
return ans;
}
string repa(int n) {
return rep("A", n);
}
string repb(int n) {
return rep("B", n);
}
ll calc_K(ll A, ll B) {
ll ub = 500000010;
ll lb = 0;
while (ub - lb > 1) {
ll t = (ub+lb)/2;
if (A <= (B+1) * t && B <= (A+1) * t) {
ub = t;
} else {
lb = t;
}
}
return ub;
}
string f(ll A, ll B, ll C, ll D) {
ll K = calc_K(A, B);
ll ub = A+B;
ll lb = -1;
while (ub - lb > 1) {
ll t = (ub+lb)/2;
ll b = t/(K+1);
ll a = t - b;
ll rema = A - a;
ll remb = B - b;
if (remb <= (rema+1) * K) {
ub = t;
} else {
lb = t;
}
}
ll L = ub;
if (D <= L) {
int back = (C/(K+1)) * (K+1);
C -= back;
D -= back;
string X = rep(repa(K) + "B", 100);
return X.substr(C-1, D-C+1);
} else if (C > L) {
C = A+B+1-C;
D = A+B+1-D;
int back = (C/(K+1)) * (K+1);
C -= back;
D -= back;
string X = rep(repb(K) + "A", 100);
string Y = X.substr(D-1, C-D+1);
reverse(Y.begin(), Y.end());
return Y;
} else {
int rema = L%(K+1);
int remb = (A+B-L)%(K+1);
string X = repa(rema) + repb(remb);
X = rep(repa(K) + "B", 100) + X + rep("A" + repb(K), 100);
int back = L - (100 * (K+1) + rema);
C -= back;
D -= back;
return X.substr(C-1, D-C+1);
}
}
int main () {
int Q;
cin >> Q;
int A[1010], B[1010], C[1010], D[1010];
for (auto i = 0; i < Q; ++i) {
cin >> A[i] >> B[i] >> C[i] >> D[i];
}
for (auto i = 0; i < Q; ++i) {
string X = f(A[i], B[i], C[i], D[i]);
cout << X << endl;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: c_slots.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-11-02 15:27:28 $
*
* 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 ARY_CPP_C_SLOTS_HXX
#define ARY_CPP_C_SLOTS_HXX
// BASE CLASSES
#include <ary/ceslot.hxx>
// USED SERVICES
#include <ary/cpp/c_slntry.hxx>
namespace ary
{
namespace cpp
{
class Slot_SubNamespaces : public ary::Slot
{
public:
Slot_SubNamespaces(
const Map_NamespacePtr &
i_rData );
virtual ~Slot_SubNamespaces();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const Map_NamespacePtr *
pData;
};
class Slot_BaseClass : public ary::Slot
{
public:
Slot_BaseClass(
const List_Bases & i_rData );
virtual ~Slot_BaseClass();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const List_Bases * pData;
};
} // namespace cpp
} // namespace ary
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.22); FILE MERGED 2008/03/28 16:01:36 rt 1.3.22.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: c_slots.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 ARY_CPP_C_SLOTS_HXX
#define ARY_CPP_C_SLOTS_HXX
// BASE CLASSES
#include <ary/ceslot.hxx>
// USED SERVICES
#include <ary/cpp/c_slntry.hxx>
namespace ary
{
namespace cpp
{
class Slot_SubNamespaces : public ary::Slot
{
public:
Slot_SubNamespaces(
const Map_NamespacePtr &
i_rData );
virtual ~Slot_SubNamespaces();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const Map_NamespacePtr *
pData;
};
class Slot_BaseClass : public ary::Slot
{
public:
Slot_BaseClass(
const List_Bases & i_rData );
virtual ~Slot_BaseClass();
virtual uintt Size() const;
private:
virtual void StoreEntries(
ary::Display & o_rDestination ) const;
// DATA
const List_Bases * pData;
};
} // namespace cpp
} // namespace ary
#endif
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <cstdlib> // For rand.
#include <list>
#include <set>
#include <string>
#include <stout/duration.hpp>
#include <stout/foreach.hpp>
#include <stout/gtest.hpp>
#include <stout/hashset.hpp>
#include <stout/os.hpp>
#include <stout/stopwatch.hpp>
#include <stout/try.hpp>
#include <stout/uuid.hpp>
#ifdef __APPLE__
#include <stout/os/sysctl.hpp>
#endif
using os::Exec;
using os::Fork;
using os::Process;
using os::ProcessTree;
using std::list;
using std::set;
using std::string;
static hashset<string> listfiles(const string& directory)
{
hashset<string> fileset;
foreach (const string& file, os::ls(directory)) {
fileset.insert(file);
}
return fileset;
}
class OsTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
const Try<string>& mkdtemp = os::mkdtemp();
ASSERT_SOME(mkdtemp);
tmpdir = mkdtemp.get();
}
virtual void TearDown()
{
ASSERT_SOME(os::rmdir(tmpdir));
}
string tmpdir;
};
TEST_F(OsTest, rmdir)
{
const hashset<string> EMPTY;
hashset<string> expectedListing = EMPTY;
EXPECT_EQ(expectedListing, listfiles(tmpdir));
os::mkdir(tmpdir + "/a/b/c");
os::mkdir(tmpdir + "/a/b/d");
os::mkdir(tmpdir + "/e/f");
expectedListing = EMPTY;
expectedListing.insert("a");
expectedListing.insert("e");
EXPECT_EQ(expectedListing, listfiles(tmpdir));
expectedListing = EMPTY;
expectedListing.insert("b");
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a"));
expectedListing = EMPTY;
expectedListing.insert("c");
expectedListing.insert("d");
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a/b"));
expectedListing = EMPTY;
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a/b/c"));
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a/b/d"));
expectedListing.insert("f");
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/e"));
expectedListing = EMPTY;
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/e/f"));
}
TEST_F(OsTest, nonblock)
{
int pipes[2];
ASSERT_NE(-1, pipe(pipes));
Try<bool> isNonBlock = false;
isNonBlock = os::isNonblock(pipes[0]);
ASSERT_SOME(isNonBlock);
EXPECT_FALSE(isNonBlock.get());
ASSERT_SOME(os::nonblock(pipes[0]));
isNonBlock = os::isNonblock(pipes[0]);
ASSERT_SOME(isNonBlock);
EXPECT_TRUE(isNonBlock.get());
close(pipes[0]);
close(pipes[1]);
EXPECT_ERROR(os::nonblock(pipes[0]));
EXPECT_ERROR(os::nonblock(pipes[0]));
}
TEST_F(OsTest, touch)
{
const string& testfile = tmpdir + "/" + UUID::random().toString();
ASSERT_SOME(os::touch(testfile));
ASSERT_TRUE(os::exists(testfile));
}
TEST_F(OsTest, readWriteString)
{
const string& testfile = tmpdir + "/" + UUID::random().toString();
const string& teststr = "test";
ASSERT_SOME(os::write(testfile, teststr));
Try<string> readstr = os::read(testfile);
ASSERT_SOME(readstr);
EXPECT_EQ(teststr, readstr.get());
}
TEST_F(OsTest, find)
{
const string& testdir = tmpdir + "/" + UUID::random().toString();
const string& subdir = testdir + "/test1";
ASSERT_SOME(os::mkdir(subdir)); // Create the directories.
// Now write some files.
const string& file1 = testdir + "/file1.txt";
const string& file2 = subdir + "/file2.txt";
const string& file3 = subdir + "/file3.jpg";
ASSERT_SOME(os::touch(file1));
ASSERT_SOME(os::touch(file2));
ASSERT_SOME(os::touch(file3));
// Find "*.txt" files.
Try<std::list<string> > result = os::find(testdir, ".txt");
ASSERT_SOME(result);
hashset<string> files;
foreach (const string& file, result.get()) {
files.insert(file);
}
ASSERT_EQ(2u, files.size());
ASSERT_TRUE(files.contains(file1));
ASSERT_TRUE(files.contains(file2));
}
TEST_F(OsTest, uname)
{
const Try<os::UTSInfo>& info = os::uname();
ASSERT_SOME(info);
#ifdef __linux__
EXPECT_EQ(info.get().sysname, "Linux");
#endif
#ifdef __APPLE__
EXPECT_EQ(info.get().sysname, "Darwin");
#endif
}
TEST_F(OsTest, sysname)
{
const Try<string>& name = os::sysname();
ASSERT_SOME(name);
#ifdef __linux__
EXPECT_EQ(name.get(), "Linux");
#endif
#ifdef __APPLE__
EXPECT_EQ(name.get(), "Darwin");
#endif
}
TEST_F(OsTest, release)
{
const Try<os::Release>& info = os::release();
ASSERT_SOME(info);
}
TEST_F(OsTest, sleep)
{
Duration duration = Milliseconds(10);
Stopwatch stopwatch;
stopwatch.start();
ASSERT_SOME(os::sleep(duration));
ASSERT_LE(duration, stopwatch.elapsed());
ASSERT_ERROR(os::sleep(Milliseconds(-10)));
}
#ifdef __APPLE__
TEST_F(OsTest, sysctl)
{
Try<os::UTSInfo> uname = os::uname();
ASSERT_SOME(uname);
Try<string> release = os::sysctl(CTL_KERN, KERN_OSRELEASE).string();
ASSERT_SOME(release);
EXPECT_EQ(uname.get().release, release.get());
Try<string> type = os::sysctl(CTL_KERN, KERN_OSTYPE).string();
ASSERT_SOME(type);
EXPECT_EQ(uname.get().sysname, type.get());
Try<int> maxproc = os::sysctl(CTL_KERN, KERN_MAXPROC).integer();
ASSERT_SOME(maxproc);
Try<std::vector<kinfo_proc> > processes =
os::sysctl(CTL_KERN, KERN_PROC, KERN_PROC_ALL).table(maxproc.get());
ASSERT_SOME(processes);
std::set<pid_t> pids;
foreach (const kinfo_proc& process, processes.get()) {
pids.insert(process.kp_proc.p_pid);
}
EXPECT_EQ(1, pids.count(getpid()));
}
#endif // __APPLE__
TEST_F(OsTest, pids)
{
Try<set<pid_t> > pids = os::pids();
ASSERT_SOME(pids);
EXPECT_NE(0u, pids.get().size());
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_EQ(1u, pids.get().count(1));
pids = os::pids(getpgid(0), None());
EXPECT_SOME(pids);
EXPECT_GE(pids.get().size(), 1u);
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_ERROR(os::pids(-1, None()));
pids = os::pids(None(), getsid(0));
EXPECT_SOME(pids);
EXPECT_GE(pids.get().size(), 1u);
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_ERROR(os::pids(None(), -1));
}
TEST_F(OsTest, children)
{
Try<set<pid_t> > children = os::children(getpid());
ASSERT_SOME(children);
EXPECT_EQ(0u, children.get().size());
Try<ProcessTree> tree =
Fork(None(), // Child.
Fork(Exec("sleep 10")), // Grandchild.
Exec("sleep 10"))();
ASSERT_SOME(tree);
ASSERT_EQ(1u, tree.get().children.size());
pid_t child = tree.get().process.pid;
pid_t grandchild = tree.get().children.front().process.pid;
// Ensure the non-recursive children does not include the
// grandchild.
children = os::children(getpid(), false);
ASSERT_SOME(children);
EXPECT_EQ(1u, children.get().size());
EXPECT_EQ(1u, children.get().count(child));
children = os::children(getpid());
ASSERT_SOME(children);
EXPECT_EQ(2u, children.get().size());
EXPECT_EQ(1u, children.get().count(child));
EXPECT_EQ(1u, children.get().count(grandchild));
// Cleanup by killing the descendant processes.
EXPECT_EQ(0, kill(grandchild, SIGKILL));
EXPECT_EQ(0, kill(child, SIGKILL));
// We have to reap the child for running the tests in repetition.
ASSERT_EQ(child, waitpid(child, NULL, 0));
}
TEST_F(OsTest, process)
{
const Result<Process>& status = os::process(getpid());
ASSERT_SOME(status);
EXPECT_EQ(getpid(), status.get().pid);
EXPECT_EQ(getppid(), status.get().parent);
EXPECT_EQ(getsid(getpid()), status.get().session);
ASSERT_SOME(status.get().rss);
EXPECT_GT(status.get().rss.get(), 0);
// NOTE: On Linux /proc is a bit slow to update the CPU times,
// hence we allow 0 in this test.
ASSERT_SOME(status.get().utime);
EXPECT_GE(status.get().utime.get(), Nanoseconds(0));
ASSERT_SOME(status.get().stime);
EXPECT_GE(status.get().stime.get(), Nanoseconds(0));
EXPECT_FALSE(status.get().command.empty());
}
TEST_F(OsTest, processes)
{
const Try<list<Process> >& processes = os::processes();
ASSERT_SOME(processes);
ASSERT_GT(processes.get().size(), 2);
// Look for ourselves in the table.
bool found = false;
foreach (const Process& process, processes.get()) {
if (process.pid == getpid()) {
found = true;
EXPECT_EQ(getpid(), process.pid);
EXPECT_EQ(getppid(), process.parent);
EXPECT_EQ(getsid(getpid()), process.session);
ASSERT_SOME(process.rss);
EXPECT_GT(process.rss.get(), 0);
// NOTE: On linux /proc is a bit slow to update the cpu times,
// hence we allow 0 in this test.
ASSERT_SOME(process.utime);
EXPECT_GE(process.utime.get(), Nanoseconds(0));
ASSERT_SOME(process.stime);
EXPECT_GE(process.stime.get(), Nanoseconds(0));
EXPECT_FALSE(process.command.empty());
break;
}
}
EXPECT_TRUE(found);
}
void dosetsid(void)
{
if (::setsid() == -1) {
perror("Failed to setsid");
abort();
}
}
TEST_F(OsTest, killtree)
{
Try<ProcessTree> tree =
Fork(dosetsid, // Child.
Fork(None(), // Grandchild.
Fork(None(), // Great-grandchild.
Fork(dosetsid, // Great-great-granchild.
Exec("sleep 10")),
Exec("sleep 10")),
Exec("exit 0")),
Exec("sleep 10"))();
ASSERT_SOME(tree);
ASSERT_EQ(1u, tree.get().children.size());
ASSERT_EQ(1u, tree.get().children.front().children.size());
ASSERT_EQ(1u, tree.get().children.front().children.front().children.size());
pid_t child = tree.get();
pid_t grandchild = tree.get().children.front();
pid_t greatGrandchild = tree.get().children.front().children.front();
pid_t greatGreatGrandchild =
tree.get().children.front().children.front().children.front();
// Kill the child process tree, this is expected to
// cross the broken link to the grandchild.
EXPECT_SOME(os::killtree(child, SIGKILL, true, true, &std::cout));
// There is a delay for the process to move into the zombie state.
os::sleep(Milliseconds(50));
// Expect the pids to be wiped!
EXPECT_NONE(os::process(greatGreatGrandchild));
EXPECT_NONE(os::process(greatGrandchild));
EXPECT_NONE(os::process(grandchild));
EXPECT_SOME(os::process(child));
EXPECT_TRUE(os::process(child).get().zombie);
// We have to reap the child for running the tests in repetition.
ASSERT_EQ(child, waitpid(child, NULL, 0));
}
TEST_F(OsTest, pstree)
{
Try<ProcessTree> tree = os::pstree(getpid());
ASSERT_SOME(tree);
EXPECT_EQ(0u, tree.get().children.size());
tree =
Fork(None(), // Child.
Fork(Exec("sleep 10")), // Grandchild.
Exec("sleep 10"))();
ASSERT_SOME(tree);
ASSERT_EQ(1u, tree.get().children.size());
pid_t child = tree.get().process.pid;
pid_t grandchild = tree.get().children.front().process.pid;
// Now check pstree again.
tree = os::pstree(child);
ASSERT_SOME(tree);
EXPECT_EQ(child, tree.get().process.pid);
ASSERT_EQ(1u, tree.get().children.size());
EXPECT_EQ(grandchild, tree.get().children.front().process.pid);
// Cleanup by killing the descendant processes.
EXPECT_EQ(0, kill(grandchild, SIGKILL));
EXPECT_EQ(0, kill(child, SIGKILL));
// We have to reap the child for running the tests in repetition.
ASSERT_EQ(child, waitpid(child, NULL, 0));
}
<commit_msg>Fixed naming in a test.<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <cstdlib> // For rand.
#include <list>
#include <set>
#include <string>
#include <stout/duration.hpp>
#include <stout/foreach.hpp>
#include <stout/gtest.hpp>
#include <stout/hashset.hpp>
#include <stout/os.hpp>
#include <stout/stopwatch.hpp>
#include <stout/try.hpp>
#include <stout/uuid.hpp>
#ifdef __APPLE__
#include <stout/os/sysctl.hpp>
#endif
using os::Exec;
using os::Fork;
using os::Process;
using os::ProcessTree;
using std::list;
using std::set;
using std::string;
static hashset<string> listfiles(const string& directory)
{
hashset<string> fileset;
foreach (const string& file, os::ls(directory)) {
fileset.insert(file);
}
return fileset;
}
class OsTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
const Try<string>& mkdtemp = os::mkdtemp();
ASSERT_SOME(mkdtemp);
tmpdir = mkdtemp.get();
}
virtual void TearDown()
{
ASSERT_SOME(os::rmdir(tmpdir));
}
string tmpdir;
};
TEST_F(OsTest, rmdir)
{
const hashset<string> EMPTY;
hashset<string> expectedListing = EMPTY;
EXPECT_EQ(expectedListing, listfiles(tmpdir));
os::mkdir(tmpdir + "/a/b/c");
os::mkdir(tmpdir + "/a/b/d");
os::mkdir(tmpdir + "/e/f");
expectedListing = EMPTY;
expectedListing.insert("a");
expectedListing.insert("e");
EXPECT_EQ(expectedListing, listfiles(tmpdir));
expectedListing = EMPTY;
expectedListing.insert("b");
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a"));
expectedListing = EMPTY;
expectedListing.insert("c");
expectedListing.insert("d");
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a/b"));
expectedListing = EMPTY;
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a/b/c"));
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/a/b/d"));
expectedListing.insert("f");
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/e"));
expectedListing = EMPTY;
EXPECT_EQ(expectedListing, listfiles(tmpdir + "/e/f"));
}
TEST_F(OsTest, nonblock)
{
int pipes[2];
ASSERT_NE(-1, pipe(pipes));
Try<bool> isNonBlock = false;
isNonBlock = os::isNonblock(pipes[0]);
ASSERT_SOME(isNonBlock);
EXPECT_FALSE(isNonBlock.get());
ASSERT_SOME(os::nonblock(pipes[0]));
isNonBlock = os::isNonblock(pipes[0]);
ASSERT_SOME(isNonBlock);
EXPECT_TRUE(isNonBlock.get());
close(pipes[0]);
close(pipes[1]);
EXPECT_ERROR(os::nonblock(pipes[0]));
EXPECT_ERROR(os::nonblock(pipes[0]));
}
TEST_F(OsTest, touch)
{
const string& testfile = tmpdir + "/" + UUID::random().toString();
ASSERT_SOME(os::touch(testfile));
ASSERT_TRUE(os::exists(testfile));
}
TEST_F(OsTest, readWriteString)
{
const string& testfile = tmpdir + "/" + UUID::random().toString();
const string& teststr = "test";
ASSERT_SOME(os::write(testfile, teststr));
Try<string> readstr = os::read(testfile);
ASSERT_SOME(readstr);
EXPECT_EQ(teststr, readstr.get());
}
TEST_F(OsTest, find)
{
const string& testdir = tmpdir + "/" + UUID::random().toString();
const string& subdir = testdir + "/test1";
ASSERT_SOME(os::mkdir(subdir)); // Create the directories.
// Now write some files.
const string& file1 = testdir + "/file1.txt";
const string& file2 = subdir + "/file2.txt";
const string& file3 = subdir + "/file3.jpg";
ASSERT_SOME(os::touch(file1));
ASSERT_SOME(os::touch(file2));
ASSERT_SOME(os::touch(file3));
// Find "*.txt" files.
Try<std::list<string> > result = os::find(testdir, ".txt");
ASSERT_SOME(result);
hashset<string> files;
foreach (const string& file, result.get()) {
files.insert(file);
}
ASSERT_EQ(2u, files.size());
ASSERT_TRUE(files.contains(file1));
ASSERT_TRUE(files.contains(file2));
}
TEST_F(OsTest, uname)
{
const Try<os::UTSInfo>& info = os::uname();
ASSERT_SOME(info);
#ifdef __linux__
EXPECT_EQ(info.get().sysname, "Linux");
#endif
#ifdef __APPLE__
EXPECT_EQ(info.get().sysname, "Darwin");
#endif
}
TEST_F(OsTest, sysname)
{
const Try<string>& name = os::sysname();
ASSERT_SOME(name);
#ifdef __linux__
EXPECT_EQ(name.get(), "Linux");
#endif
#ifdef __APPLE__
EXPECT_EQ(name.get(), "Darwin");
#endif
}
TEST_F(OsTest, release)
{
const Try<os::Release>& info = os::release();
ASSERT_SOME(info);
}
TEST_F(OsTest, sleep)
{
Duration duration = Milliseconds(10);
Stopwatch stopwatch;
stopwatch.start();
ASSERT_SOME(os::sleep(duration));
ASSERT_LE(duration, stopwatch.elapsed());
ASSERT_ERROR(os::sleep(Milliseconds(-10)));
}
#ifdef __APPLE__
TEST_F(OsTest, sysctl)
{
Try<os::UTSInfo> uname = os::uname();
ASSERT_SOME(uname);
Try<string> release = os::sysctl(CTL_KERN, KERN_OSRELEASE).string();
ASSERT_SOME(release);
EXPECT_EQ(uname.get().release, release.get());
Try<string> type = os::sysctl(CTL_KERN, KERN_OSTYPE).string();
ASSERT_SOME(type);
EXPECT_EQ(uname.get().sysname, type.get());
Try<int> maxproc = os::sysctl(CTL_KERN, KERN_MAXPROC).integer();
ASSERT_SOME(maxproc);
Try<std::vector<kinfo_proc> > processes =
os::sysctl(CTL_KERN, KERN_PROC, KERN_PROC_ALL).table(maxproc.get());
ASSERT_SOME(processes);
std::set<pid_t> pids;
foreach (const kinfo_proc& process, processes.get()) {
pids.insert(process.kp_proc.p_pid);
}
EXPECT_EQ(1, pids.count(getpid()));
}
#endif // __APPLE__
TEST_F(OsTest, pids)
{
Try<set<pid_t> > pids = os::pids();
ASSERT_SOME(pids);
EXPECT_NE(0u, pids.get().size());
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_EQ(1u, pids.get().count(1));
pids = os::pids(getpgid(0), None());
EXPECT_SOME(pids);
EXPECT_GE(pids.get().size(), 1u);
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_ERROR(os::pids(-1, None()));
pids = os::pids(None(), getsid(0));
EXPECT_SOME(pids);
EXPECT_GE(pids.get().size(), 1u);
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_ERROR(os::pids(None(), -1));
}
TEST_F(OsTest, children)
{
Try<set<pid_t> > children = os::children(getpid());
ASSERT_SOME(children);
EXPECT_EQ(0u, children.get().size());
Try<ProcessTree> tree =
Fork(None(), // Child.
Fork(Exec("sleep 10")), // Grandchild.
Exec("sleep 10"))();
ASSERT_SOME(tree);
ASSERT_EQ(1u, tree.get().children.size());
pid_t child = tree.get().process.pid;
pid_t grandchild = tree.get().children.front().process.pid;
// Ensure the non-recursive children does not include the
// grandchild.
children = os::children(getpid(), false);
ASSERT_SOME(children);
EXPECT_EQ(1u, children.get().size());
EXPECT_EQ(1u, children.get().count(child));
children = os::children(getpid());
ASSERT_SOME(children);
EXPECT_EQ(2u, children.get().size());
EXPECT_EQ(1u, children.get().count(child));
EXPECT_EQ(1u, children.get().count(grandchild));
// Cleanup by killing the descendant processes.
EXPECT_EQ(0, kill(grandchild, SIGKILL));
EXPECT_EQ(0, kill(child, SIGKILL));
// We have to reap the child for running the tests in repetition.
ASSERT_EQ(child, waitpid(child, NULL, 0));
}
TEST_F(OsTest, process)
{
const Result<Process>& process = os::process(getpid());
ASSERT_SOME(process);
EXPECT_EQ(getpid(), process.get().pid);
EXPECT_EQ(getppid(), process.get().parent);
EXPECT_EQ(getsid(getpid()), process.get().session);
ASSERT_SOME(process.get().rss);
EXPECT_GT(process.get().rss.get(), 0);
// NOTE: On Linux /proc is a bit slow to update the CPU times,
// hence we allow 0 in this test.
ASSERT_SOME(process.get().utime);
EXPECT_GE(process.get().utime.get(), Nanoseconds(0));
ASSERT_SOME(process.get().stime);
EXPECT_GE(process.get().stime.get(), Nanoseconds(0));
EXPECT_FALSE(process.get().command.empty());
}
TEST_F(OsTest, processes)
{
const Try<list<Process> >& processes = os::processes();
ASSERT_SOME(processes);
ASSERT_GT(processes.get().size(), 2);
// Look for ourselves in the table.
bool found = false;
foreach (const Process& process, processes.get()) {
if (process.pid == getpid()) {
found = true;
EXPECT_EQ(getpid(), process.pid);
EXPECT_EQ(getppid(), process.parent);
EXPECT_EQ(getsid(getpid()), process.session);
ASSERT_SOME(process.rss);
EXPECT_GT(process.rss.get(), 0);
// NOTE: On linux /proc is a bit slow to update the cpu times,
// hence we allow 0 in this test.
ASSERT_SOME(process.utime);
EXPECT_GE(process.utime.get(), Nanoseconds(0));
ASSERT_SOME(process.stime);
EXPECT_GE(process.stime.get(), Nanoseconds(0));
EXPECT_FALSE(process.command.empty());
break;
}
}
EXPECT_TRUE(found);
}
void dosetsid(void)
{
if (::setsid() == -1) {
perror("Failed to setsid");
abort();
}
}
TEST_F(OsTest, killtree)
{
Try<ProcessTree> tree =
Fork(dosetsid, // Child.
Fork(None(), // Grandchild.
Fork(None(), // Great-grandchild.
Fork(dosetsid, // Great-great-granchild.
Exec("sleep 10")),
Exec("sleep 10")),
Exec("exit 0")),
Exec("sleep 10"))();
ASSERT_SOME(tree);
ASSERT_EQ(1u, tree.get().children.size());
ASSERT_EQ(1u, tree.get().children.front().children.size());
ASSERT_EQ(1u, tree.get().children.front().children.front().children.size());
pid_t child = tree.get();
pid_t grandchild = tree.get().children.front();
pid_t greatGrandchild = tree.get().children.front().children.front();
pid_t greatGreatGrandchild =
tree.get().children.front().children.front().children.front();
// Kill the child process tree, this is expected to
// cross the broken link to the grandchild.
EXPECT_SOME(os::killtree(child, SIGKILL, true, true, &std::cout));
// There is a delay for the process to move into the zombie state.
os::sleep(Milliseconds(50));
// Expect the pids to be wiped!
EXPECT_NONE(os::process(greatGreatGrandchild));
EXPECT_NONE(os::process(greatGrandchild));
EXPECT_NONE(os::process(grandchild));
EXPECT_SOME(os::process(child));
EXPECT_TRUE(os::process(child).get().zombie);
// We have to reap the child for running the tests in repetition.
ASSERT_EQ(child, waitpid(child, NULL, 0));
}
TEST_F(OsTest, pstree)
{
Try<ProcessTree> tree = os::pstree(getpid());
ASSERT_SOME(tree);
EXPECT_EQ(0u, tree.get().children.size());
tree =
Fork(None(), // Child.
Fork(Exec("sleep 10")), // Grandchild.
Exec("sleep 10"))();
ASSERT_SOME(tree);
ASSERT_EQ(1u, tree.get().children.size());
pid_t child = tree.get().process.pid;
pid_t grandchild = tree.get().children.front().process.pid;
// Now check pstree again.
tree = os::pstree(child);
ASSERT_SOME(tree);
EXPECT_EQ(child, tree.get().process.pid);
ASSERT_EQ(1u, tree.get().children.size());
EXPECT_EQ(grandchild, tree.get().children.front().process.pid);
// Cleanup by killing the descendant processes.
EXPECT_EQ(0, kill(grandchild, SIGKILL));
EXPECT_EQ(0, kill(child, SIGKILL));
// We have to reap the child for running the tests in repetition.
ASSERT_EQ(child, waitpid(child, NULL, 0));
}
<|endoftext|> |
<commit_before>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2018-4-15 21:25:15
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 1 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string S;
int N;
bool par[20010];
bool used[20010];
bool solve()
{
N = S.size();
int cnt = 0;
for (auto i = 0; i < N; i++)
{
par[i] = (S[i] == '(');
if (par[i])
{
++cnt;
}
}
if (cnt != N/2)
{
return false;
}
fill(used, used + N, false);
int c[2] = {0, 0};
int now = 0;
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (!par[now])
{
used[now] = true;
c[1]++;
}
}
else if (c[0] == c[1])
{
if (par[now])
{
used[now] = true;
c[0]++;
}
}
else
{
used[now] = true;
c[par[now]]++;
}
now++;
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
c[0] = c[1] = 0;
now = 0;
#if DEBUG == 1
cerr << "S = " << S << endl;
cerr << "S1 = ";
for (auto i = 0; i < N; i++)
{
if (used[i])
{
cerr << S[i];
}
}
cerr << endl;
cerr << "S2 = ";
for (auto i = 0; i < N; i++)
{
if (!used[i])
{
cerr << S[i];
}
}
cerr << endl;
#endif
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
if (used[now])
{
now++;
continue;
}
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (par[now])
{
used[now] = true;
c[1]++;
}
}
else if (c[0] == c[1])
{
if (!par[now])
{
used[now] = true;
c[0]++;
}
}
else
{
used[now] = true;
c[1 - (int)par[now]]++;
}
now++;
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
return true;
}
int main()
{
int Q;
cin >> Q;
for (auto i = 0; i < Q; i++)
{
cin >> S;
cout << (solve() ? "Yes" : "No") << endl;
}
}<commit_msg>tried C.cpp to 'C'<commit_after>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2018-4-15 21:25:15
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 1 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string S;
int N;
bool par[20010];
bool used[20010];
bool solve()
{
N = S.size();
int cnt = 0;
for (auto i = 0; i < N; i++)
{
par[i] = (S[i] == '(');
if (par[i])
{
++cnt;
}
}
if (cnt != N/2)
{
return false;
}
fill(used, used + N, false);
int c[2] = {0, 0};
int now = 0;
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (!par[now])
{
used[now] = true;
c[1]++;
}
}
else
{
if (c[0] == c[1])
{
if (par[now])
{
used[now] = true;
c[0]++;
}
}
else
{
used[now] = true;
c[par[now]]++;
}
now++;
}
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
c[0] = c[1] = 0;
now = 0;
#if DEBUG == 1
cerr << "S = " << S << endl;
cerr << "S1 = ";
for (auto i = 0; i < N; i++)
{
if (used[i])
{
cerr << S[i];
}
}
cerr << endl;
cerr << "S2 = ";
for (auto i = 0; i < N; i++)
{
if (!used[i])
{
cerr << S[i];
}
}
cerr << endl;
#endif
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
if (used[now])
{
now++;
continue;
}
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (par[now])
{
used[now] = true;
c[1]++;
}
}
else
{
if (c[0] == c[1])
{
if (!par[now])
{
used[now] = true;
c[0]++;
}
}
else
{
used[now] = true;
c[1 - (int)par[now]]++;
}
now++;
}
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
return true;
}
int main()
{
int Q;
cin >> Q;
for (auto i = 0; i < Q; i++)
{
cin >> S;
cout << (solve() ? "Yes" : "No") << endl;
}
}<|endoftext|> |
<commit_before>// 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 __STOUT_OS_WINDOWS_FTRUNCATE_HPP__
#define __STOUT_OS_WINDOWS_FTRUNCATE_HPP__
#include <io.h>
#include <stout/error.hpp>
#include <stout/nothing.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>
#include <stout/os/int_fd.hpp>
namespace os {
// Identical in functionality to POSIX standard `ftruncate`.
inline Try<Nothing> ftruncate(const int_fd& fd, __int64 length)
{
if (::_chsize_s(fd.crt(), length) != 0) {
return ErrnoError(
"Failed to truncate file at file descriptor '" + stringify(fd) + "' to " +
stringify(length) + " bytes.");
}
return Nothing();
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_FTRUNCATE_HPP__
<commit_msg>Windows: Fixed `os::ftruncate()` to use `FileEndOfFileInfo`.<commit_after>// 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 __STOUT_OS_WINDOWS_FTRUNCATE_HPP__
#define __STOUT_OS_WINDOWS_FTRUNCATE_HPP__
#include <stout/error.hpp>
#include <stout/nothing.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>
#include <stout/os/int_fd.hpp>
namespace os {
inline Try<Nothing> ftruncate(const int_fd& fd, off_t length)
{
FILE_END_OF_FILE_INFO info;
info.EndOfFile.QuadPart = length;
if (::SetFileInformationByHandle(
fd, FileEndOfFileInfo, &info, sizeof(info)) == FALSE) {
return WindowsError();
}
return Nothing();
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_FTRUNCATE_HPP__
<|endoftext|> |
<commit_before>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2018-4-15 21:25:15
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 1 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string S;
int N;
bool par[20010];
bool used[20010];
bool solve()
{
N = S.size();
int cnt = 0;
for (auto i = 0; i < N; i++)
{
par[i] = (S[i] == '(');
if (par[i])
{
++cnt;
}
}
if (cnt != N/2)
{
return false;
}
fill(used, used + N, false);
int c[2] = {0, 0};
int now = 0;
int K1, K2;
for (auto i = 0; i < N; i++)
{
if (par[i])
{
c[0]++;
used[i] = true;
if (c[0] == 1)
{
K1 = i;
}
}
if (c[0] == N/4)
{
break;
}
}
for (auto i = N-1; i >= 0; i--)
{
if (!par[i])
{
c[1]++;
used[i] = true;
}
if (c[1] == N/4)
{
K2 = i;
break;
}
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
#if DEBUG == 1
cerr << "S = " << S << endl;
cerr << "S1 = ";
for (auto i = 0; i < N; i++)
{
if (used[i])
{
cerr << S[i];
}
}
cerr << endl;
cerr << "S2 = ";
for (auto i = 0; i < N; i++)
{
if (!used[i])
{
cerr << S[i];
}
}
cerr << endl;
#endif
c[0] = c[1] = 0;
now = 0;
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
#if DEBUG == 1
cerr << "now = " << now << "c = {" << c[0] << ", "
<< c[1] << "}" << endl;
#endif
if (!used[now])
{
now++;
continue;
}
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (!par[now])
{
c[1]++;
}
}
else if (c[0] < N/4)
{
if (c[0] == c[1])
{
if (par[now])
{
c[0]++;
}
}
else
{
c[1 - (int)par[now]]++;
}
}
now++;
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
return true;
c[0] = c[1] = 0;
now = 0;
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
if (used[now])
{
now++;
continue;
}
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (par[now])
{
used[now] = true;
c[1]++;
}
}
else if (c[0] < N/4)
{
if (c[0] == c[1])
{
if (!par[now])
{
used[now] = true;
c[0]++;
}
}
else
{
used[now] = true;
c[(int)par[now]]++;
}
}
now++;
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
return true;
}
int main()
{
int Q;
cin >> Q;
for (auto i = 0; i < Q; i++)
{
cin >> S;
cout << (solve() ? "Yes" : "No") << endl;
}
}<commit_msg>tried C.cpp to 'C'<commit_after>/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2018-4-15 21:25:15
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 1 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string S;
int N;
bool par[20010];
bool used[20010];
bool solve()
{
N = S.size();
int cnt = 0;
for (auto i = 0; i < N; i++)
{
par[i] = (S[i] == '(');
if (par[i])
{
++cnt;
}
}
if (cnt != N/2)
{
return false;
}
fill(used, used + N, false);
int c[2] = {0, 0};
int now = 0;
int K1, K2;
for (auto i = 0; i < N; i++)
{
if (par[i])
{
c[0]++;
used[i] = true;
if (c[0] == 1)
{
K1 = i;
}
}
if (c[0] == N/4)
{
break;
}
}
for (auto i = N-1; i >= 0; i--)
{
if (!par[i])
{
c[1]++;
used[i] = true;
}
if (c[1] == N/4)
{
K2 = i;
break;
}
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
#if DEBUG == 1
cerr << "S = " << S << endl;
cerr << "S1 = ";
for (auto i = 0; i < N; i++)
{
if (used[i])
{
cerr << S[i];
}
}
cerr << endl;
cerr << "S2 = ";
for (auto i = 0; i < N; i++)
{
if (!used[i])
{
cerr << S[i];
}
}
cerr << endl;
#endif
c[0] = c[1] = 0;
now = 0;
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
if (!used[now])
{
now++;
continue;
}
#if DEBUG == 1
cerr << "now = " << now << ", c = {" << c[0] << ", "
<< c[1] << "}" << endl;
#endif
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (!par[now])
{
c[1]++;
}
}
else if (c[0] < N/4)
{
if (c[0] == c[1])
{
if (par[now])
{
c[0]++;
}
}
else
{
c[1 - (int)par[now]]++;
}
}
now++;
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
return true;
c[0] = c[1] = 0;
now = 0;
while (now < N && (c[0] < N / 4 || c[1] < N / 4))
{
if (used[now])
{
now++;
continue;
}
assert(c[0] >= c[1]);
if (c[0] == N/4)
{
if (par[now])
{
used[now] = true;
c[1]++;
}
}
else if (c[0] < N/4)
{
if (c[0] == c[1])
{
if (!par[now])
{
used[now] = true;
c[0]++;
}
}
else
{
used[now] = true;
c[(int)par[now]]++;
}
}
now++;
}
if (c[0] < N/4 || c[1] < N/4)
{
return false;
}
return true;
}
int main()
{
int Q;
cin >> Q;
for (auto i = 0; i < Q; i++)
{
cin >> S;
cout << (solve() ? "Yes" : "No") << endl;
}
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2/16/2019, 9:07:46 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, M;
int A[10];
int need[10] = {100, 2, 5, 5, 4, 5, 6, 3, 7, 6};
map<int, int> X;
vector<vector<int>> Y;
vector<vector<int>> W;
void dfs(vector<int> L, int R)
{
#if DEBUG == 1
cerr << "dfs(" << L.size() << ", " << R << ")" << endl;
cerr << "L: ";
for (auto x : L)
{
cerr << x << " ";
}
cerr << endl;
#endif
if (R == 0)
{
Y.push_back(L);
}
else
{
for (auto x : X)
{
int cost = x.first;
if ((L.empty() || cost >= L[L.size() - 1]) && cost <= R)
{
L.push_back(cost);
dfs(L, R - cost);
L.pop_back();
}
}
}
}
int max_score(vector<int> L)
{
vector<int> F;
for (auto x : L)
{
F.push_back(X[x]);
}
sort(F.begin(), F.end());
reverse(F.begin(), F.end());
string ans = "";
for (auto i = 0; i < min(9, (int)F.size()); i++)
{
ans = ans + to_string(F[i]);
}
#if DEBUG == 1
cerr << "max_score: " << ans << endl;
#endif
return stoi(ans);
}
void represent(vector<int> L)
{
vector<int> F;
for (auto x : L)
{
F.push_back(X[x]);
}
sort(F.begin(), F.end());
reverse(F.begin(), F.end());
for (auto i = 0; i < (int)F.size(); i++)
{
cerr << F[i];
}
}
int main()
{
cin >> N >> M;
for (auto i = 0; i < M; i++)
{
cin >> A[i];
int n = need[A[i]];
if (X.find(n) == X.end())
{
X[n] = A[i];
}
else
{
X[n] = max(X[n], A[i]);
}
}
int cnt = 0;
int cost = (*X.begin()).first;
string base = to_string((*X.begin()).second);
while (N > 200)
{
N -= cost;
cnt++;
}
if (cost == 2 && N % 2 == 0)
{
while (N > 0)
{
N -= cost;
cnt++;
}
}
else if (cost == 2)
{
auto it = X.begin();
while ((*it).first % 2 == 0)
{
it++;
}
cout << (*it).second;
N -= (*it).first;
while (N > 0)
{
N -= cost;
cnt++;
}
}
else
{
vector<int> V = {};
#if DEBUG == 1
cerr << "N = " << N << endl;
#endif
dfs(V, N);
int maxi = 0;
for (auto v : Y)
{
maxi = max((int)v.size(), maxi);
}
#if DEBUG == 1
cerr << "maxi = " << maxi << endl;
#endif
for (auto v : Y)
{
if ((int)v.size() == maxi)
{
W.push_back(v);
}
}
int maxi_score = 0;
vector<int> ans;
for (auto v : W)
{
if (maxi_score < max_score(v))
{
maxi_score = max_score(v);
ans = v;
}
}
represent(ans);
}
for (auto i = 0; i < cnt; i++)
{
cout << base;
}
cout << endl;
}<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1
/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2/16/2019, 9:07:46 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, M;
int A[10];
int need[10] = {100, 2, 5, 5, 4, 5, 6, 3, 7, 6};
map<int, int> X;
vector<vector<int>> Y;
vector<vector<int>> W;
void dfs(vector<int> L, int R)
{
#if DEBUG == 1
cerr << "dfs(" << L.size() << ", " << R << ")" << endl;
cerr << "L: ";
for (auto x : L)
{
cerr << x << " ";
}
cerr << endl;
#endif
if (R == 0)
{
Y.push_back(L);
}
else
{
for (auto x : X)
{
int cost = x.first;
if ((L.empty() || cost >= L[L.size() - 1]) && cost <= R)
{
L.push_back(cost);
dfs(L, R - cost);
L.pop_back();
}
}
}
}
int max_score(vector<int> L)
{
vector<int> F;
for (auto x : L)
{
F.push_back(X[x]);
}
sort(F.begin(), F.end());
reverse(F.begin(), F.end());
string ans = "";
for (auto i = 0; i < min(9, (int)F.size()); i++)
{
ans = ans + to_string(F[i]);
}
#if DEBUG == 1
cerr << "max_score: " << ans << endl;
#endif
return stoi(ans);
}
void represent(vector<int> L)
{
vector<int> F;
for (auto x : L)
{
F.push_back(X[x]);
}
sort(F.begin(), F.end());
reverse(F.begin(), F.end());
for (auto i = 0; i < (int)F.size(); i++)
{
cerr << F[i];
}
}
int main()
{
cin >> N >> M;
for (auto i = 0; i < M; i++)
{
cin >> A[i];
int n = need[A[i]];
if (X.find(n) == X.end())
{
X[n] = A[i];
}
else
{
X[n] = max(X[n], A[i]);
}
}
int cnt = 0;
int cost = (*X.begin()).first;
string base = to_string((*X.begin()).second);
while (N > 200)
{
N -= cost;
cnt++;
}
if (cost == 2 && N % 2 == 0)
{
while (N > 0)
{
N -= cost;
cnt++;
}
}
else if (cost == 2)
{
auto it = X.begin();
while ((*it).first % 2 == 0)
{
it++;
}
cout << (*it).second;
N -= (*it).first;
while (N > 0)
{
N -= cost;
cnt++;
}
}
else
{
vector<int> V = {};
#if DEBUG == 1
cerr << "N = " << N << endl;
#endif
dfs(V, N);
int maxi = 0;
for (auto v : Y)
{
maxi = max((int)v.size(), maxi);
}
#if DEBUG == 1
cerr << "maxi = " << maxi << endl;
#endif
for (auto v : Y)
{
if ((int)v.size() == maxi)
{
#if DEBUG == 1
cerr << "v: ";
for (auto x : v)
{
cerr << x << " ";
}
cerr << endl;
#endif
W.push_back(v);
}
}
int maxi_score = 0;
vector<int> ans;
for (auto v : W)
{
if (maxi_score < max_score(v))
{
maxi_score = max_score(v);
ans = v;
}
}
represent(ans);
}
for (auto i = 0; i < cnt; i++)
{
cout << base;
}
cout << endl;
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2019/8/18 21:33:53
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
ll test(ll L, ll R)
{
ll ans{0};
for (auto y = R; y >= L; y--)
{
for (auto x = y; x >= L; x--)
{
if (y % x == (y ^ x))
{
#if DEBUG == 1
cerr << "(" << y << ", " << x << ") = " << y % x << endl;
#endif
++ans;
}
}
}
return ans;
}
ll L, R;
constexpr ll C{63};
mint solve(ll X)
{
mint ans{0};
for (auto i = 0; i < C; i++)
{
if (X >> i == 0)
{
break;
}
if (X >> i & 1)
{
ans += mint{3}.power(i);
}
}
int one{0};
for (auto i = C - 1; i >= 0; i--)
{
if (X >> i > 0 && (X >> i & 1))
{
++one;
}
else if (X >> i > 0 && !(X >> i & 1))
{
ans -= mint{2}.power(one) * mint{3}.power(i);
}
}
return ans;
}
int main()
{
cin >> L >> R;
mint ans{solve(R) - solve(L - 1)};
cout << ans << endl;
}<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2019/8/18 21:33:53
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
ll test(ll L, ll R)
{
ll ans{0};
for (auto y = R; y >= L; y--)
{
for (auto x = y; x >= L; x--)
{
if (y % x == (y ^ x))
{
#if DEBUG == 1
cerr << "(" << y << ", " << x << ") = " << y % x << endl;
#endif
++ans;
}
}
}
return ans;
}
ll L, R;
constexpr ll C{63};
mint solve(ll X)
{
mint ans{0};
#if DEBUG == 1
cerr << "X = " << X << endl;
#endif
for (auto i = 0; i < C; i++)
{
if (X >> i == 0)
{
break;
}
if (X >> i & 1)
{
ans += mint{3}.power(i);
#if DEBUG == 1
cerr << "3^{" << i << "}" << endl;
#endif
}
}
int one{0};
for (auto i = C - 1; i >= 0; i--)
{
if (X >> i > 0 && (X >> i & 1))
{
++one;
}
else if (X >> i > 0 && !(X >> i & 1))
{
ans -= mint{2}.power(one) * mint{3}.power(i);
}
}
return ans;
}
int main()
{
cin >> L >> R;
mint ans{solve(R) - solve(L - 1)};
cout << ans << endl;
}<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 6/7/2020, 1:08:56 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N, M;
ll L;
cin >> N >> M >> L;
vector<vector<ll>> T(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < M; ++i)
{
int A, B;
ll C;
cin >> A >> B >> C;
--A;
--B;
T[A][B] = C;
T[B][A] = C;
}
for (auto i{0}; i < N; ++i)
{
T[i][i] = 0;
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (T[i][k] == INT64_MAX || T[k][j] == INT64_MAX)
{
continue;
}
ch_min(T[i][j], T[i][k] + T[k][j]);
}
}
}
vector<vector<ll>> H(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
H[i][j] = (T[i][j] <= L ? 1 : INT64_MAX);
}
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (H[i][k] == INT64_MAX || H[k][j] == INT64_MAX)
{
continue;
}
ch_min(H[i][j], H[i][k] + H[k][j]);
}
}
}
int Q;
cin >> Q;
for (auto q{0}; q < Q; ++q)
{
int s, t;
cin >> s >> t;
--s;
--t;
ll ans{H[s][t]};
cout << (ans == INT64_MAX ? -1 : ans + 1) << endl;
}
}
<commit_msg>submit E.cpp to 'E - Travel by Car' (abc143) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 6/7/2020, 1:08:56 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N, M;
ll L;
cin >> N >> M >> L;
vector<vector<ll>> T(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < M; ++i)
{
int A, B;
ll C;
cin >> A >> B >> C;
--A;
--B;
T[A][B] = C;
T[B][A] = C;
}
for (auto i{0}; i < N; ++i)
{
T[i][i] = 0;
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (T[i][k] == INT64_MAX || T[k][j] == INT64_MAX)
{
continue;
}
ch_min(T[i][j], T[i][k] + T[k][j]);
}
}
}
vector<vector<ll>> H(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
H[i][j] = (T[i][j] <= L ? 1 : INT64_MAX);
}
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (H[i][k] == INT64_MAX || H[k][j] == INT64_MAX)
{
continue;
}
ch_min(H[i][j], H[i][k] + H[k][j]);
}
}
}
int Q;
cin >> Q;
for (auto q{0}; q < Q; ++q)
{
int s, t;
cin >> s >> t;
--s;
--t;
ll ans{H[s][t]};
cout << (ans == INT64_MAX ? -1 : ans - 1) << endl;
}
}
<|endoftext|> |
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2/22/2020, 9:38:37 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
ll k, q;
vector<ll> d;
vector<ll> e;
vector<ll> N, X, M;
ll solve(ll n, ll x, ll m)
{
for (auto i = 0; i < k; ++i)
{
e[i] = d[i] % m;
#if DEBUG == 1
cerr << "e[" << i << "] = " << e[i] << endl;
#endif
}
ll cnt{0};
for (auto i = 0; i < k; ++i)
{
if (e[i] == 0)
{
++cnt;
}
}
ll S{accumulate(e.begin(), e.end(), 0LL)};
ll T{(n - 1) / k};
ll U{(n - 1) % k};
ll A{S * T + x};
#if DEBUG == 1
cerr << "S = " << S << endl;
cerr << "T = " << T << endl;
cerr << "U = " << U << endl;
cerr << "A = " << A << endl;
#endif
ll Y{cnt * T};
for (auto i = 0; i < U; ++i)
{
A += e[i];
if (e[i] == 0)
{
++Y;
}
}
ll Z{A / m};
#if DEBUG == 1
cerr << "Y = " << Y << endl;
cerr << "Z = " << Z << endl;
#endif
return n - 1 - Y - Z;
}
int main()
{
cin >> k >> q;
d.resize(k);
e.resize(k);
for (auto i = 0; i < k; ++i)
{
cin >> d[i];
}
N.resize(q);
X.resize(q);
M.resize(q);
for (auto i = 0; i < q; ++i)
{
cin >> N[i] >> X[i] >> M[i];
}
for (auto i = 0; i < q; ++i)
{
cout << solve(N[i], X[i], M[i]) << endl;
}
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2/22/2020, 9:38:37 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
ll k, q;
vector<ll> d;
vector<ll> e;
vector<ll> N, X, M;
ll solve(ll n, ll x, ll m)
{
for (auto i = 0; i < k; ++i)
{
e[i] = d[i] % m;
#if DEBUG == 1
cerr << "e[" << i << "] = " << e[i] << endl;
#endif
}
ll cnt{0};
for (auto i = 0; i < k; ++i)
{
if (e[i] == 0)
{
++cnt;
}
}
ll S{accumulate(e.begin(), e.end(), 0LL)};
ll T{(n - 1) / k};
ll U{(n - 1) % k};
ll A{S * T + x};
#if DEBUG == 1
cerr << "S = " << S << endl;
cerr << "T = " << T << endl;
cerr << "U = " << U << endl;
#endif
ll Y{cnt * T};
for (auto i = 0; i < U; ++i)
{
A += e[i];
if (e[i] == 0)
{
++Y;
}
}
ll Z{A / m};
#if DEBUG == 1
cerr << "A = " << A << endl;
cerr << "Y = " << Y << endl;
cerr << "Z = " << Z << endl;
#endif
return n - 1 - Y - Z;
}
int main()
{
cin >> k >> q;
d.resize(k);
e.resize(k);
for (auto i = 0; i < k; ++i)
{
cin >> d[i];
}
N.resize(q);
X.resize(q);
M.resize(q);
for (auto i = 0; i < q; ++i)
{
cin >> N[i] >> X[i] >> M[i];
}
for (auto i = 0; i < q; ++i)
{
cout << solve(N[i], X[i], M[i]) << endl;
}
}
<|endoftext|> |
<commit_before>#include "HotkeyManager.h"
#include "Logger.h"
HotkeyManager *HotkeyManager::instance = NULL;
HotkeyManager *HotkeyManager::Instance() {
return instance;
}
HotkeyManager *HotkeyManager::Instance(HWND notifyWnd) {
if (instance == NULL) {
instance = new HotkeyManager();
instance->Hook();
instance->_notifyWnd = notifyWnd;
}
return instance;
}
HotkeyManager::HotkeyManager() :
_fixWin(false) {
}
HotkeyManager::~HotkeyManager() {
while (true) {
auto i = _keyCombinations.begin();
if (_keyCombinations.size() > 0) {
Unregister(*i);
} else {
break;
}
}
Unhook();
}
void HotkeyManager::Shutdown() {
delete instance;
instance = NULL;
}
bool HotkeyManager::Hook() {
_mouseHook = SetWindowsHookEx(WH_MOUSE_LL,
LowLevelMouseProc, NULL, NULL);
_keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,
LowLevelKeyboardProc, NULL, NULL);
return _mouseHook && _keyHook;
}
bool HotkeyManager::Unhook() {
BOOL unMouse = UnhookWindowsHookEx(_mouseHook);
BOOL unKey = UnhookWindowsHookEx(_keyHook);
return unMouse && unKey;
}
void HotkeyManager::Register(int keyCombination) {
if (_keyCombinations.count(keyCombination) > 0) {
CLOG(L"Hotkey combination [%d] already registered", keyCombination);
return;
} else {
_keyCombinations.insert(keyCombination);
}
/* get VK_* value; includes unused bits */
int vk = 0xFFFF & keyCombination;
if ((keyCombination >> 20) > 0 /* uses a HKM_MOUSE_* flag */
|| vk == VK_LBUTTON
|| vk == VK_RBUTTON
|| vk == VK_MBUTTON) {
/* mouse-based hotkeys; we are done */
CLOG(L"Registered new mouse-based hotkey: %d", keyCombination);
return;
}
/* keyboard-only hotkeys; use WinAPI */
int mods = (0xF0000 & keyCombination) >> 16;
if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) {
CLOG(L"Failed to register hotkey [%d]\n"
L"Mods: %d, VK: %d", keyCombination, mods, vk);
return;
}
CLOG(L"Registered new keyboard-based hotkey: %d", keyCombination);
}
bool HotkeyManager::Unregister(int keyCombination) {
CLOG(L"Unregistering hotkey combination: %d", keyCombination);
if (_keyCombinations.count(keyCombination) <= 0) {
QCLOG(L"Hotkey combination [%d] was not previously registered",
keyCombination);
return false;
}
_keyCombinations.erase(keyCombination);
if ((keyCombination >> 20) == 0) {
/* This hotkey isn't mouse-based; unregister with Windows */
if (!UnregisterHotKey(_notifyWnd, keyCombination)) {
CLOG(L"Failed to unregister hotkey: %d", keyCombination);
return false;
}
}
return true;
}
LRESULT CALLBACK
HotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
if (wParam == WM_KEYUP) {
KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;
if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN)
&& _fixWin) {
/* WIN+Mouse combination used; we need to prevent the
* system from only seeing a WIN keypress (and usually
* popping up the start menu). We simulate WIN+VK_NONAME. */
INPUT input = { 0 };
input.type = INPUT_KEYBOARD;
input.ki.wVk = VK_NONAME;
input.ki.wScan = 0;
input.ki.dwFlags = 0;
input.ki.time = 1;
input.ki.dwExtraInfo = GetMessageExtraInfo();
/* key down: */
SendInput(1, &input, sizeof(INPUT));
/* key up: */
input.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
_fixWin = false;
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
LRESULT CALLBACK
HotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
int mouseState = 0;
MSLLHOOKSTRUCT *msInfo;
switch (wParam) {
case WM_LBUTTONDOWN:
mouseState += VK_LBUTTON;
break;
case WM_MBUTTONDOWN:
mouseState += VK_MBUTTON;
break;
case WM_RBUTTONDOWN:
mouseState += VK_RBUTTON;
break;
case WM_XBUTTONDOWN: {
msInfo = (MSLLHOOKSTRUCT *) lParam;
int button = msInfo->mouseData >> 16 & 0xFFFF;
if (button == 1)
mouseState += HKM_MOUSE_XB1;
else if (button == 2)
mouseState += HKM_MOUSE_XB2;
break;
}
case WM_MOUSEWHEEL: {
msInfo = (MSLLHOOKSTRUCT *) lParam;
if ((int) msInfo->mouseData > 0) {
mouseState += HKM_MOUSE_WHUP;
} else {
mouseState += HKM_MOUSE_WHDN;
}
break;
}
}
if (mouseState > 0) {
mouseState += Modifiers();
if (_keyCombinations.count(mouseState) > 0) {
PostMessage(_notifyWnd, WM_HOTKEY,
mouseState, mouseState & 0xF0000);
if (mouseState & HKM_MOD_WIN) {
_fixWin = true; /* enable fix right before WIN goes up */
}
return 1; /* processed the message; eat it */
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
LRESULT CALLBACK
HotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
return HotkeyManager::instance->MouseProc(nCode, wParam, lParam);
}
LRESULT CALLBACK
HotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
return HotkeyManager::instance->KeyProc(nCode, wParam, lParam);
}
int HotkeyManager::IsModifier(int vk) {
switch (vk) {
case VK_MENU:
case VK_LMENU:
case VK_RMENU:
return HKM_MOD_ALT;
case VK_CONTROL:
case VK_LCONTROL:
case VK_RCONTROL:
return HKM_MOD_CTRL;
case VK_SHIFT:
case VK_LSHIFT:
case VK_RSHIFT:
return HKM_MOD_SHF;
case VK_LWIN:
case VK_RWIN:
return HKM_MOD_WIN;
}
return 0;
}
bool HotkeyManager::IsMouseKey(int vk) {
if (vk < 0x07 && vk != VK_CANCEL) {
return true;
}
if (vk & (0xF << MOUSE_OFFSET)) {
/* Has wheel or xbutton flags */
return true;
}
return false;
}
int HotkeyManager::Modifiers() {
int mods = 0;
mods += (GetKeyState(VK_MENU) & 0x8000) << 1;
mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2;
mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3;
mods += (GetKeyState(VK_LWIN) & 0x8000) << 4;
mods += (GetKeyState(VK_RWIN) & 0x8000) << 4;
return mods;
}
int HotkeyManager::ModifiersAsync() {
int mods = 0;
mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;
mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;
mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;
mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;
mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;
return mods;
}
std::wstring HotkeyManager::HotkeysToModString(int combination,
std::wstring separator) {
std::wstring str = L"";
if (combination & HKM_MOD_ALT) {
str += VKToString(VK_MENU) + separator;
}
if (combination & HKM_MOD_CTRL) {
str += VKToString(VK_CONTROL) + separator;
}
if (combination & HKM_MOD_SHF) {
str += VKToString(VK_SHIFT) + separator;
}
if (combination & HKM_MOD_WIN) {
str += L"Win" + separator;
}
return str;
}
std::wstring HotkeyManager::HotkeysToString(int combination,
std::wstring separator) {
std::wstring mods = HotkeysToModString(combination, separator);
int vk = combination & 0xFF;
std::wstring str;
if (IsMouseKey(vk)) {
str = MouseString(combination);
} else {
bool ext = (combination & 0x100) > 0;
str = VKToString(vk, ext);
}
return mods + str;
}
std::wstring HotkeyManager::MouseString(int combination) {
int vk = combination & 0xFF;
if (vk > 0) {
switch (vk) {
case VK_LBUTTON:
return L"Mouse 1";
case VK_RBUTTON:
return L"Mouse 2";
case VK_MBUTTON:
return L"Mouse 3";
}
}
int flags = combination & (0xF << MOUSE_OFFSET);
if (flags == HKM_MOUSE_XB1) {
return L"Mouse 4";
} else if (flags == HKM_MOUSE_XB2) {
return L"Mouse 5";
} else if (flags == HKM_MOUSE_WHUP) {
return L"Mouse Wheel Up";
} else if (flags == HKM_MOUSE_WHDN) {
return L"Mouse Wheel Down";
}
return L"";
}
std::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) {
/* GetKeyNameText expects the following:
* 16-23: scan code
* 24: extended key flag
* 25: 'do not care' bit (don't distinguish between L/R keys) */
unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);
scanCode = scanCode << 16;
if (vk == VK_RSHIFT) {
/* For some reason, the right shift key ends up having its extended
* key flag set and confuses GetKeyNameText. */
extendedKey = false;
}
int extended = extendedKey ? 0x1 : 0x0;
scanCode |= extended << 24;
wchar_t buf[256] = {};
GetKeyNameText(scanCode, buf, 256);
return std::wstring(buf);
}<commit_msg>Fix VK masking bug<commit_after>#include "HotkeyManager.h"
#include "Logger.h"
HotkeyManager *HotkeyManager::instance = NULL;
HotkeyManager *HotkeyManager::Instance() {
return instance;
}
HotkeyManager *HotkeyManager::Instance(HWND notifyWnd) {
if (instance == NULL) {
instance = new HotkeyManager();
instance->Hook();
instance->_notifyWnd = notifyWnd;
}
return instance;
}
HotkeyManager::HotkeyManager() :
_fixWin(false) {
}
HotkeyManager::~HotkeyManager() {
while (true) {
auto i = _keyCombinations.begin();
if (_keyCombinations.size() > 0) {
Unregister(*i);
} else {
break;
}
}
Unhook();
}
void HotkeyManager::Shutdown() {
delete instance;
instance = NULL;
}
bool HotkeyManager::Hook() {
_mouseHook = SetWindowsHookEx(WH_MOUSE_LL,
LowLevelMouseProc, NULL, NULL);
_keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,
LowLevelKeyboardProc, NULL, NULL);
return _mouseHook && _keyHook;
}
bool HotkeyManager::Unhook() {
BOOL unMouse = UnhookWindowsHookEx(_mouseHook);
BOOL unKey = UnhookWindowsHookEx(_keyHook);
return unMouse && unKey;
}
void HotkeyManager::Register(int keyCombination) {
if (_keyCombinations.count(keyCombination) > 0) {
CLOG(L"Hotkey combination [%d] already registered", keyCombination);
return;
} else {
_keyCombinations.insert(keyCombination);
}
/* get VK_* value; */
int vk = 0xFF & keyCombination;
if ((keyCombination >> 20) > 0 /* uses a HKM_MOUSE_* flag */
|| vk == VK_LBUTTON
|| vk == VK_RBUTTON
|| vk == VK_MBUTTON) {
/* mouse-based hotkeys; we are done */
CLOG(L"Registered new mouse-based hotkey: %d", keyCombination);
return;
}
/* keyboard-only hotkeys; use WinAPI */
int mods = (0xF0000 & keyCombination) >> 16;
if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) {
CLOG(L"Failed to register hotkey [%d]\n"
L"Mods: %d, VK: %d", keyCombination, mods, vk);
return;
}
CLOG(L"Registered new keyboard-based hotkey: %d", keyCombination);
}
bool HotkeyManager::Unregister(int keyCombination) {
CLOG(L"Unregistering hotkey combination: %d", keyCombination);
if (_keyCombinations.count(keyCombination) <= 0) {
QCLOG(L"Hotkey combination [%d] was not previously registered",
keyCombination);
return false;
}
_keyCombinations.erase(keyCombination);
if ((keyCombination >> 20) == 0) {
/* This hotkey isn't mouse-based; unregister with Windows */
if (!UnregisterHotKey(_notifyWnd, keyCombination)) {
CLOG(L"Failed to unregister hotkey: %d", keyCombination);
return false;
}
}
return true;
}
LRESULT CALLBACK
HotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
if (wParam == WM_KEYUP) {
KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;
if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN)
&& _fixWin) {
/* WIN+Mouse combination used; we need to prevent the
* system from only seeing a WIN keypress (and usually
* popping up the start menu). We simulate WIN+VK_NONAME. */
INPUT input = { 0 };
input.type = INPUT_KEYBOARD;
input.ki.wVk = VK_NONAME;
input.ki.wScan = 0;
input.ki.dwFlags = 0;
input.ki.time = 1;
input.ki.dwExtraInfo = GetMessageExtraInfo();
/* key down: */
SendInput(1, &input, sizeof(INPUT));
/* key up: */
input.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
_fixWin = false;
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
LRESULT CALLBACK
HotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
int mouseState = 0;
MSLLHOOKSTRUCT *msInfo;
switch (wParam) {
case WM_LBUTTONDOWN:
mouseState += VK_LBUTTON;
break;
case WM_MBUTTONDOWN:
mouseState += VK_MBUTTON;
break;
case WM_RBUTTONDOWN:
mouseState += VK_RBUTTON;
break;
case WM_XBUTTONDOWN: {
msInfo = (MSLLHOOKSTRUCT *) lParam;
int button = msInfo->mouseData >> 16 & 0xFFFF;
if (button == 1)
mouseState += HKM_MOUSE_XB1;
else if (button == 2)
mouseState += HKM_MOUSE_XB2;
break;
}
case WM_MOUSEWHEEL: {
msInfo = (MSLLHOOKSTRUCT *) lParam;
if ((int) msInfo->mouseData > 0) {
mouseState += HKM_MOUSE_WHUP;
} else {
mouseState += HKM_MOUSE_WHDN;
}
break;
}
}
if (mouseState > 0) {
mouseState += Modifiers();
if (_keyCombinations.count(mouseState) > 0) {
PostMessage(_notifyWnd, WM_HOTKEY,
mouseState, mouseState & 0xF0000);
if (mouseState & HKM_MOD_WIN) {
_fixWin = true; /* enable fix right before WIN goes up */
}
return 1; /* processed the message; eat it */
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
LRESULT CALLBACK
HotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
return HotkeyManager::instance->MouseProc(nCode, wParam, lParam);
}
LRESULT CALLBACK
HotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
return HotkeyManager::instance->KeyProc(nCode, wParam, lParam);
}
int HotkeyManager::IsModifier(int vk) {
switch (vk) {
case VK_MENU:
case VK_LMENU:
case VK_RMENU:
return HKM_MOD_ALT;
case VK_CONTROL:
case VK_LCONTROL:
case VK_RCONTROL:
return HKM_MOD_CTRL;
case VK_SHIFT:
case VK_LSHIFT:
case VK_RSHIFT:
return HKM_MOD_SHF;
case VK_LWIN:
case VK_RWIN:
return HKM_MOD_WIN;
}
return 0;
}
bool HotkeyManager::IsMouseKey(int vk) {
if (vk < 0x07 && vk != VK_CANCEL) {
return true;
}
if (vk & (0xF << MOUSE_OFFSET)) {
/* Has wheel or xbutton flags */
return true;
}
return false;
}
int HotkeyManager::Modifiers() {
int mods = 0;
mods += (GetKeyState(VK_MENU) & 0x8000) << 1;
mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2;
mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3;
mods += (GetKeyState(VK_LWIN) & 0x8000) << 4;
mods += (GetKeyState(VK_RWIN) & 0x8000) << 4;
return mods;
}
int HotkeyManager::ModifiersAsync() {
int mods = 0;
mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;
mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;
mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;
mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;
mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;
return mods;
}
std::wstring HotkeyManager::HotkeysToModString(int combination,
std::wstring separator) {
std::wstring str = L"";
if (combination & HKM_MOD_ALT) {
str += VKToString(VK_MENU) + separator;
}
if (combination & HKM_MOD_CTRL) {
str += VKToString(VK_CONTROL) + separator;
}
if (combination & HKM_MOD_SHF) {
str += VKToString(VK_SHIFT) + separator;
}
if (combination & HKM_MOD_WIN) {
str += L"Win" + separator;
}
return str;
}
std::wstring HotkeyManager::HotkeysToString(int combination,
std::wstring separator) {
std::wstring mods = HotkeysToModString(combination, separator);
int vk = combination & 0xFF;
std::wstring str;
if (IsMouseKey(vk)) {
str = MouseString(combination);
} else {
bool ext = (combination & 0x100) > 0;
str = VKToString(vk, ext);
}
return mods + str;
}
std::wstring HotkeyManager::MouseString(int combination) {
int vk = combination & 0xFF;
if (vk > 0) {
switch (vk) {
case VK_LBUTTON:
return L"Mouse 1";
case VK_RBUTTON:
return L"Mouse 2";
case VK_MBUTTON:
return L"Mouse 3";
}
}
int flags = combination & (0xF << MOUSE_OFFSET);
if (flags == HKM_MOUSE_XB1) {
return L"Mouse 4";
} else if (flags == HKM_MOUSE_XB2) {
return L"Mouse 5";
} else if (flags == HKM_MOUSE_WHUP) {
return L"Mouse Wheel Up";
} else if (flags == HKM_MOUSE_WHDN) {
return L"Mouse Wheel Down";
}
return L"";
}
std::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) {
/* GetKeyNameText expects the following:
* 16-23: scan code
* 24: extended key flag
* 25: 'do not care' bit (don't distinguish between L/R keys) */
unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);
scanCode = scanCode << 16;
if (vk == VK_RSHIFT) {
/* For some reason, the right shift key ends up having its extended
* key flag set and confuses GetKeyNameText. */
extendedKey = false;
}
int extended = extendedKey ? 0x1 : 0x0;
scanCode |= extended << 24;
wchar_t buf[256] = {};
GetKeyNameText(scanCode, buf, 256);
return std::wstring(buf);
}<|endoftext|> |
<commit_before>#include <cassert>
#include <set>
#include <vector>
#include <map>
#include <thread>
#include <string>
#include <cstring>
#include <brynet/net/SocketLibFunction.h>
#include <brynet/net/fdset.h>
#include <brynet/net/Connector.h>
using namespace brynet;
using namespace brynet::net;
namespace brynet
{
namespace net
{
class AsyncConnectAddr
{
public:
AsyncConnectAddr(const std::string& ip,
int port,
std::chrono::nanoseconds timeout,
const AsyncConnector::COMPLETED_CALLBACK& successCB,
const AsyncConnector::FAILED_CALLBACK& failedCB) :
mIP(ip),
mPort(port),
mTimeout(timeout),
mSuccessCB(successCB),
mFailedCB(failedCB)
{
}
const std::string& getIP() const
{
return mIP;
}
int getPort() const
{
return mPort;
}
const AsyncConnector::COMPLETED_CALLBACK& getSuccessCB() const
{
return mSuccessCB;
}
const AsyncConnector::FAILED_CALLBACK& getFailedCB() const
{
return mFailedCB;
}
std::chrono::nanoseconds getTimeout() const
{
return mTimeout;
}
private:
std::string mIP;
int mPort;
std::chrono::nanoseconds mTimeout;
AsyncConnector::COMPLETED_CALLBACK mSuccessCB;
AsyncConnector::FAILED_CALLBACK mFailedCB;
};
class ConnectorWorkInfo final : public NonCopyable
{
public:
typedef std::shared_ptr<ConnectorWorkInfo> PTR;
ConnectorWorkInfo() BRYNET_NOEXCEPT;
void checkConnectStatus(int millsecond);
bool isConnectSuccess(sock clientfd) const;
void checkTimeout();
void processConnect(const AsyncConnectAddr&);
void causeAllFailed();
private:
struct ConnectingInfo
{
ConnectingInfo()
{
timeout = std::chrono::nanoseconds::zero();
}
std::chrono::steady_clock::time_point startConnectTime;
std::chrono::nanoseconds timeout;
AsyncConnector::COMPLETED_CALLBACK successCB;
AsyncConnector::FAILED_CALLBACK failedCB;
};
std::map<sock, ConnectingInfo> mConnectingInfos;
std::set<sock> mConnectingFds;
struct FDSetDeleter
{
void operator()(struct fdset_s* ptr) const
{
ox_fdset_delete(ptr);
}
};
std::unique_ptr<struct fdset_s, FDSetDeleter> mFDSet;
};
}
}
ConnectorWorkInfo::ConnectorWorkInfo() BRYNET_NOEXCEPT
{
mFDSet.reset(ox_fdset_new());
}
bool ConnectorWorkInfo::isConnectSuccess(sock clientfd) const
{
if (!ox_fdset_check(mFDSet.get(), clientfd, WriteCheck))
{
return false;
}
int error;
int len = sizeof(error);
if (getsockopt(clientfd, SOL_SOCKET, SO_ERROR, (char*)&error, (socklen_t*)&len) == -1)
{
return false;
}
return error == 0;
}
void ConnectorWorkInfo::checkConnectStatus(int millsecond)
{
if (ox_fdset_poll(mFDSet.get(), millsecond) <= 0)
{
return;
}
std::set<sock> total_fds;
std::set<sock> success_fds;
for (auto& v : mConnectingFds)
{
if (ox_fdset_check(mFDSet.get(), v, WriteCheck))
{
total_fds.insert(v);
if (isConnectSuccess(v))
{
success_fds.insert(v);
}
}
}
for (auto fd : total_fds)
{
ox_fdset_del(mFDSet.get(), fd, WriteCheck);
mConnectingFds.erase(fd);
auto it = mConnectingInfos.find(fd);
if (it == mConnectingInfos.end())
{
continue;
}
auto socket = TcpSocket::Create(fd, false);
if (success_fds.find(fd) != success_fds.end())
{
if (it->second.successCB != nullptr)
{
it->second.successCB(std::move(socket));
}
}
else
{
if (it->second.failedCB != nullptr)
{
it->second.failedCB();
}
}
mConnectingInfos.erase(it);
}
}
void ConnectorWorkInfo::checkTimeout()
{
for (auto it = mConnectingInfos.begin(); it != mConnectingInfos.end();)
{
auto now = std::chrono::steady_clock::now();
if ((now - it->second.startConnectTime) < it->second.timeout)
{
++it;
continue;
}
auto fd = it->first;
auto cb = it->second.failedCB;
ox_fdset_del(mFDSet.get(), fd, WriteCheck);
mConnectingFds.erase(fd);
mConnectingInfos.erase(it++);
brynet::net::base::SocketClose(fd);
if (cb != nullptr)
{
cb();
}
}
}
void ConnectorWorkInfo::causeAllFailed()
{
for (auto it = mConnectingInfos.begin(); it != mConnectingInfos.end();)
{
auto fd = it->first;
auto cb = it->second.failedCB;
ox_fdset_del(mFDSet.get(), fd, WriteCheck);
mConnectingFds.erase(fd);
mConnectingInfos.erase(it++);
brynet::net::base::SocketClose(fd);
if (cb != nullptr)
{
cb();
}
}
}
void ConnectorWorkInfo::processConnect(const AsyncConnectAddr& addr)
{
struct sockaddr_in server_addr;
sock clientfd = SOCKET_ERROR;
ConnectingInfo ci;
#if defined PLATFORM_WINDOWS
int check_error = WSAEWOULDBLOCK;
#else
int check_error = EINPROGRESS;
#endif
int n = 0;
brynet::net::base::InitSocket();
clientfd = brynet::net::base::SocketCreate(AF_INET, SOCK_STREAM, 0);
if (clientfd == SOCKET_ERROR)
{
goto FAILED;
}
brynet::net::base::SocketNonblock(clientfd);
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, addr.getIP().c_str(), &server_addr.sin_addr.s_addr);
server_addr.sin_port = htons(addr.getPort());
n = connect(clientfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr));
if (n == 0)
{
goto SUCCESS;
}
if (check_error != sErrno)
{
brynet::net::base::SocketClose(clientfd);
clientfd = SOCKET_ERROR;
goto FAILED;
}
ci.startConnectTime = std::chrono::steady_clock::now();
ci.successCB = addr.getSuccessCB();
ci.failedCB = addr.getFailedCB();
ci.timeout = addr.getTimeout();
mConnectingInfos[clientfd] = ci;
mConnectingFds.insert(clientfd);
ox_fdset_add(mFDSet.get(), clientfd, WriteCheck);
return;
SUCCESS:
if (addr.getSuccessCB() != nullptr)
{
addr.getSuccessCB()(TcpSocket::Create(clientfd, false));
}
return;
FAILED:
if (addr.getFailedCB() != nullptr)
{
addr.getFailedCB()();
}
}
AsyncConnector::AsyncConnector()
{
mIsRun = false;
}
AsyncConnector::~AsyncConnector()
{
stopWorkerThread();
}
static void runOnceCheckConnect(const std::shared_ptr<brynet::net::EventLoop>& eventLoop,
const std::shared_ptr<ConnectorWorkInfo>& workerInfo)
{
eventLoop->loop(std::chrono::milliseconds(10).count());
workerInfo->checkConnectStatus(0);
workerInfo->checkTimeout();
}
void AsyncConnector::startWorkerThread()
{
#ifdef HAVE_LANG_CXX17
std::lock_guard<std::shared_mutex> lck(mThreadGuard);
#else
std::lock_guard<std::mutex> lck(mThreadGuard);
#endif
if (mThread != nullptr)
{
return;
}
mIsRun = std::make_shared<bool>(true);
mWorkInfo = std::make_shared<ConnectorWorkInfo>();
mEventLoop = std::make_shared<EventLoop>();
auto eventLoop = mEventLoop;
auto workerInfo = mWorkInfo;
auto isRun = mIsRun;
mThread = std::make_shared<std::thread>([eventLoop, workerInfo, isRun](){
while (*isRun)
{
runOnceCheckConnect(eventLoop, workerInfo);
}
workerInfo->causeAllFailed();
});
}
void AsyncConnector::stopWorkerThread()
{
#ifdef HAVE_LANG_CXX17
std::lock_guard<std::shared_mutex> lck(mThreadGuard);
#else
std::lock_guard<std::mutex> lck(mThreadGuard);
#endif
if (mThread == nullptr)
{
return;
}
mEventLoop->pushAsyncProc([this]() {
*mIsRun = false;
});
try
{
if (mThread->joinable())
{
mThread->join();
}
}
catch(...)
{ }
mEventLoop = nullptr;
mWorkInfo = nullptr;
mIsRun = nullptr;
mThread = nullptr;
}
void AsyncConnector::asyncConnect(const std::string& ip,
int port,
std::chrono::nanoseconds timeout,
COMPLETED_CALLBACK successCB,
FAILED_CALLBACK failedCB)
{
#ifdef HAVE_LANG_CXX17
std::shared_lock<std::shared_mutex> lck(mThreadGuard);
#else
std::lock_guard<std::mutex> lck(mThreadGuard);
#endif
if (successCB == nullptr || failedCB == nullptr)
{
throw std::runtime_error("all callback is nullptr");
}
if (!(*mIsRun))
{
throw std::runtime_error("work thread already stop");
}
auto workInfo = mWorkInfo;
auto address = AsyncConnectAddr(ip,
port,
timeout,
successCB,
failedCB);
mEventLoop->pushAsyncProc([workInfo, address]() {
workInfo->processConnect(address);
});
}
AsyncConnector::PTR AsyncConnector::Create()
{
struct make_shared_enabler : public AsyncConnector {};
return std::make_shared<make_shared_enabler>();
}<commit_msg>fix compiling error in gcc 6.3<commit_after>#include <cassert>
#include <set>
#include <vector>
#include <map>
#include <thread>
#include <string>
#include <cstring>
#include <brynet/net/SocketLibFunction.h>
#include <brynet/net/fdset.h>
#include <brynet/net/Connector.h>
using namespace brynet;
using namespace brynet::net;
namespace brynet
{
namespace net
{
class AsyncConnectAddr
{
public:
AsyncConnectAddr(const std::string& ip,
int port,
std::chrono::nanoseconds timeout,
const AsyncConnector::COMPLETED_CALLBACK& successCB,
const AsyncConnector::FAILED_CALLBACK& failedCB) :
mIP(ip),
mPort(port),
mTimeout(timeout),
mSuccessCB(successCB),
mFailedCB(failedCB)
{
}
const std::string& getIP() const
{
return mIP;
}
int getPort() const
{
return mPort;
}
const AsyncConnector::COMPLETED_CALLBACK& getSuccessCB() const
{
return mSuccessCB;
}
const AsyncConnector::FAILED_CALLBACK& getFailedCB() const
{
return mFailedCB;
}
std::chrono::nanoseconds getTimeout() const
{
return mTimeout;
}
private:
std::string mIP;
int mPort;
std::chrono::nanoseconds mTimeout;
AsyncConnector::COMPLETED_CALLBACK mSuccessCB;
AsyncConnector::FAILED_CALLBACK mFailedCB;
};
class ConnectorWorkInfo final : public NonCopyable
{
public:
typedef std::shared_ptr<ConnectorWorkInfo> PTR;
ConnectorWorkInfo() BRYNET_NOEXCEPT;
void checkConnectStatus(int millsecond);
bool isConnectSuccess(sock clientfd) const;
void checkTimeout();
void processConnect(const AsyncConnectAddr&);
void causeAllFailed();
private:
struct ConnectingInfo
{
ConnectingInfo()
{
timeout = std::chrono::nanoseconds::zero();
}
std::chrono::steady_clock::time_point startConnectTime;
std::chrono::nanoseconds timeout;
AsyncConnector::COMPLETED_CALLBACK successCB;
AsyncConnector::FAILED_CALLBACK failedCB;
};
std::map<sock, ConnectingInfo> mConnectingInfos;
std::set<sock> mConnectingFds;
struct FDSetDeleter
{
void operator()(struct fdset_s* ptr) const
{
ox_fdset_delete(ptr);
}
};
std::unique_ptr<struct fdset_s, FDSetDeleter> mFDSet;
};
}
}
ConnectorWorkInfo::ConnectorWorkInfo() BRYNET_NOEXCEPT
{
mFDSet.reset(ox_fdset_new());
}
bool ConnectorWorkInfo::isConnectSuccess(sock clientfd) const
{
if (!ox_fdset_check(mFDSet.get(), clientfd, WriteCheck))
{
return false;
}
int error;
int len = sizeof(error);
if (getsockopt(clientfd, SOL_SOCKET, SO_ERROR, (char*)&error, (socklen_t*)&len) == -1)
{
return false;
}
return error == 0;
}
void ConnectorWorkInfo::checkConnectStatus(int millsecond)
{
if (ox_fdset_poll(mFDSet.get(), millsecond) <= 0)
{
return;
}
std::set<sock> total_fds;
std::set<sock> success_fds;
for (auto& v : mConnectingFds)
{
if (ox_fdset_check(mFDSet.get(), v, WriteCheck))
{
total_fds.insert(v);
if (isConnectSuccess(v))
{
success_fds.insert(v);
}
}
}
for (auto fd : total_fds)
{
ox_fdset_del(mFDSet.get(), fd, WriteCheck);
mConnectingFds.erase(fd);
auto it = mConnectingInfos.find(fd);
if (it == mConnectingInfos.end())
{
continue;
}
auto socket = TcpSocket::Create(fd, false);
if (success_fds.find(fd) != success_fds.end())
{
if (it->second.successCB != nullptr)
{
it->second.successCB(std::move(socket));
}
}
else
{
if (it->second.failedCB != nullptr)
{
it->second.failedCB();
}
}
mConnectingInfos.erase(it);
}
}
void ConnectorWorkInfo::checkTimeout()
{
for (auto it = mConnectingInfos.begin(); it != mConnectingInfos.end();)
{
auto now = std::chrono::steady_clock::now();
if ((now - it->second.startConnectTime) < it->second.timeout)
{
++it;
continue;
}
auto fd = it->first;
auto cb = it->second.failedCB;
ox_fdset_del(mFDSet.get(), fd, WriteCheck);
mConnectingFds.erase(fd);
mConnectingInfos.erase(it++);
brynet::net::base::SocketClose(fd);
if (cb != nullptr)
{
cb();
}
}
}
void ConnectorWorkInfo::causeAllFailed()
{
for (auto it = mConnectingInfos.begin(); it != mConnectingInfos.end();)
{
auto fd = it->first;
auto cb = it->second.failedCB;
ox_fdset_del(mFDSet.get(), fd, WriteCheck);
mConnectingFds.erase(fd);
mConnectingInfos.erase(it++);
brynet::net::base::SocketClose(fd);
if (cb != nullptr)
{
cb();
}
}
}
void ConnectorWorkInfo::processConnect(const AsyncConnectAddr& addr)
{
struct sockaddr_in server_addr;
sock clientfd = SOCKET_ERROR;
ConnectingInfo ci;
#if defined PLATFORM_WINDOWS
int check_error = WSAEWOULDBLOCK;
#else
int check_error = EINPROGRESS;
#endif
int n = 0;
brynet::net::base::InitSocket();
clientfd = brynet::net::base::SocketCreate(AF_INET, SOCK_STREAM, 0);
if (clientfd == SOCKET_ERROR)
{
goto FAILED;
}
brynet::net::base::SocketNonblock(clientfd);
server_addr.sin_family = AF_INET;
inet_pton(AF_INET, addr.getIP().c_str(), &server_addr.sin_addr.s_addr);
server_addr.sin_port = htons(addr.getPort());
n = connect(clientfd, (struct sockaddr*)&server_addr, sizeof(struct sockaddr));
if (n == 0)
{
goto SUCCESS;
}
if (check_error != sErrno)
{
brynet::net::base::SocketClose(clientfd);
clientfd = SOCKET_ERROR;
goto FAILED;
}
ci.startConnectTime = std::chrono::steady_clock::now();
ci.successCB = addr.getSuccessCB();
ci.failedCB = addr.getFailedCB();
ci.timeout = addr.getTimeout();
mConnectingInfos[clientfd] = ci;
mConnectingFds.insert(clientfd);
ox_fdset_add(mFDSet.get(), clientfd, WriteCheck);
return;
SUCCESS:
if (addr.getSuccessCB() != nullptr)
{
addr.getSuccessCB()(TcpSocket::Create(clientfd, false));
}
return;
FAILED:
if (addr.getFailedCB() != nullptr)
{
addr.getFailedCB()();
}
}
AsyncConnector::AsyncConnector()
{
*mIsRun = false;
}
AsyncConnector::~AsyncConnector()
{
stopWorkerThread();
}
static void runOnceCheckConnect(const std::shared_ptr<brynet::net::EventLoop>& eventLoop,
const std::shared_ptr<ConnectorWorkInfo>& workerInfo)
{
eventLoop->loop(std::chrono::milliseconds(10).count());
workerInfo->checkConnectStatus(0);
workerInfo->checkTimeout();
}
void AsyncConnector::startWorkerThread()
{
#ifdef HAVE_LANG_CXX17
std::lock_guard<std::shared_mutex> lck(mThreadGuard);
#else
std::lock_guard<std::mutex> lck(mThreadGuard);
#endif
if (mThread != nullptr)
{
return;
}
mIsRun = std::make_shared<bool>(true);
mWorkInfo = std::make_shared<ConnectorWorkInfo>();
mEventLoop = std::make_shared<EventLoop>();
auto eventLoop = mEventLoop;
auto workerInfo = mWorkInfo;
auto isRun = mIsRun;
mThread = std::make_shared<std::thread>([eventLoop, workerInfo, isRun](){
while (*isRun)
{
runOnceCheckConnect(eventLoop, workerInfo);
}
workerInfo->causeAllFailed();
});
}
void AsyncConnector::stopWorkerThread()
{
#ifdef HAVE_LANG_CXX17
std::lock_guard<std::shared_mutex> lck(mThreadGuard);
#else
std::lock_guard<std::mutex> lck(mThreadGuard);
#endif
if (mThread == nullptr)
{
return;
}
mEventLoop->pushAsyncProc([this]() {
*mIsRun = false;
});
try
{
if (mThread->joinable())
{
mThread->join();
}
}
catch(...)
{ }
mEventLoop = nullptr;
mWorkInfo = nullptr;
mIsRun = nullptr;
mThread = nullptr;
}
void AsyncConnector::asyncConnect(const std::string& ip,
int port,
std::chrono::nanoseconds timeout,
COMPLETED_CALLBACK successCB,
FAILED_CALLBACK failedCB)
{
#ifdef HAVE_LANG_CXX17
std::shared_lock<std::shared_mutex> lck(mThreadGuard);
#else
std::lock_guard<std::mutex> lck(mThreadGuard);
#endif
if (successCB == nullptr || failedCB == nullptr)
{
throw std::runtime_error("all callback is nullptr");
}
if (!(*mIsRun))
{
throw std::runtime_error("work thread already stop");
}
auto workInfo = mWorkInfo;
auto address = AsyncConnectAddr(ip,
port,
timeout,
successCB,
failedCB);
mEventLoop->pushAsyncProc([workInfo, address]() {
workInfo->processConnect(address);
});
}
AsyncConnector::PTR AsyncConnector::Create()
{
struct make_shared_enabler : public AsyncConnector {};
return std::make_shared<make_shared_enabler>();
}<|endoftext|> |
<commit_before>#include "include-opencv.hpp"
#include <fmo/benchmark.hpp>
#include <fmo/image.hpp>
#include <fmo/processing.hpp>
#include <fmo/stats.hpp>
#include <random>
namespace fmo {
namespace {
void log(log_t logFunc, const char* cStr) { logFunc(cStr); }
template <typename Arg1, typename... Args>
void log(log_t logFunc, const char* format, Arg1 arg1, Args... args) {
char buf[81];
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
#endif
snprintf(buf, sizeof(buf), format, arg1, args...);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
logFunc(buf);
}
}
Registry& Registry::get() {
static Registry instance;
return instance;
}
void Registry::runAll(log_t logFunc, stop_t stopFunc) const {
fmo::SectionStats stats;
try {
log(logFunc, "Benchmark started.\n");
log(logFunc, "Num threads: %d\n", cv::getNumThreads());
for (auto func : mFuncs) {
stats.reset();
bool updated = false;
while (!updated && !stopFunc()) {
stats.start();
func.second();
updated = stats.stop();
}
if (stopFunc()) { throw std::runtime_error("stopped"); }
auto q = stats.quantilesMs();
log(logFunc, "%s: %.2f / %.1f / %.0f\n", func.first, q.q50, q.q95, q.q99);
}
log(logFunc, "Benchmark finished.\n\n");
} catch (std::exception& e) { log(logFunc, "Benchmark interrupted: %s.\n\n", e.what()); }
}
Benchmark::Benchmark(const char* name, bench_t func) {
auto& reg = Registry::get();
reg.add(name, func);
}
namespace {
struct {
cv::Mat grayNoise;
cv::Mat grayCircles;
cv::Mat rect;
cv::Mat out1;
cv::Mat out2;
cv::Mat out3;
fmo::Image grayNoiseImage;
std::vector<fmo::Image> outImageVec;
std::mt19937 re{5489};
using limits = std::numeric_limits<int>;
std::uniform_int_distribution<int> uniform{limits::min(), limits::max()};
std::uniform_int_distribution<int> randomGray{2, 254};
} global;
struct Init {
static const int W = 1920;
static const int H = 1080;
static cv::Mat newGrayMat() { return {cv::Size{W, H}, CV_8UC1}; }
Init() {
{
global.grayNoise = newGrayMat();
auto* data = global.grayNoise.data;
auto* end = data + (W * H);
for (; data < end; data += sizeof(int)) {
*(int*)data = global.uniform(global.re);
}
// cv::imwrite("grayNoise.png", global.grayNoise);
global.grayNoiseImage.assign(fmo::Format::GRAY, {W, H}, global.grayNoise.data);
}
{
global.grayCircles = newGrayMat();
auto* data = global.grayCircles.data;
for (int r = 0; r < H; r++) {
int rmod = ((r + 128) % 256);
int dy = std::min(rmod, 256 - rmod);
int dy2 = dy * dy;
for (int c = 0; c < W; c++) {
int cmod = ((c + 128) % 256);
int dx = std::min(cmod, 256 - cmod);
int dx2 = dx * dx;
*data++ = (dx2 + dy2 < 10000) ? 0xFF : 0x00;
}
}
// cv::imwrite("grayCircles.png", global.grayCircles);
}
global.rect = cv::getStructuringElement(cv::MORPH_RECT, {3, 3});
}
};
void init() { static Init once; }
Benchmark FMO_UNIQUE_NAME{"cv::bitwise_or", []() {
init();
cv::bitwise_or(global.grayNoise, global.grayCircles,
global.out1);
}};
Benchmark FMO_UNIQUE_NAME{"cv::operator+", []() {
init();
global.out1 = global.grayNoise + global.grayCircles;
}};
Benchmark FMO_UNIQUE_NAME{"cv::resize/NEAREST", []() {
init();
cv::resize(global.grayNoise, global.out1,
{Init::W / 2, Init::H / 2}, 0, 0,
cv::INTER_NEAREST);
}};
Benchmark FMO_UNIQUE_NAME{"cv::resize/AREA", []() {
init();
cv::resize(global.grayNoise, global.out1,
{Init::W / 2, Init::H / 2}, 0, 0, cv::INTER_AREA);
}};
Benchmark FMO_UNIQUE_NAME{"fmo::pyramid (6 levels)", []() {
init();
fmo::pyramid(global.grayNoiseImage, global.outImageVec, 6);
}};
Benchmark FMO_UNIQUE_NAME{"cv::threshold", []() {
init();
cv::threshold(global.grayNoise, global.out1, 0x80, 0xFF,
cv::THRESH_BINARY);
}};
Benchmark FMO_UNIQUE_NAME{"cv::absdiff", []() {
init();
cv::absdiff(global.grayNoise, global.grayCircles,
global.out1);
}};
Benchmark FMO_UNIQUE_NAME{"cv::dilate", []() {
init();
cv::dilate(global.grayNoise, global.out1, global.rect);
}};
Benchmark FMO_UNIQUE_NAME{"cv::erode", []() {
init();
cv::erode(global.grayNoise, global.out1, global.rect);
}};
Benchmark FMO_UNIQUE_NAME{"cv::floodFill", []() {
init();
auto newVal = uchar(global.randomGray(global.re));
cv::floodFill(global.grayCircles, cv::Point{0, 0}, newVal);
}};
}
}
<commit_msg>Add an Explorer benchmark<commit_after>#include "include-opencv.hpp"
#include <fmo/benchmark.hpp>
#include <fmo/explorer.hpp>
#include <fmo/image.hpp>
#include <fmo/processing.hpp>
#include <fmo/stats.hpp>
#include <random>
namespace fmo {
namespace {
void log(log_t logFunc, const char* cStr) { logFunc(cStr); }
template <typename Arg1, typename... Args>
void log(log_t logFunc, const char* format, Arg1 arg1, Args... args) {
char buf[81];
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
#endif
snprintf(buf, sizeof(buf), format, arg1, args...);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
logFunc(buf);
}
}
Registry& Registry::get() {
static Registry instance;
return instance;
}
void Registry::runAll(log_t logFunc, stop_t stopFunc) const {
fmo::SectionStats stats;
try {
log(logFunc, "Benchmark started.\n");
log(logFunc, "Num threads: %d\n", cv::getNumThreads());
for (auto func : mFuncs) {
stats.reset();
bool updated = false;
while (!updated && !stopFunc()) {
stats.start();
func.second();
updated = stats.stop();
}
if (stopFunc()) { throw std::runtime_error("stopped"); }
auto q = stats.quantilesMs();
log(logFunc, "%s: %.2f / %.1f / %.0f\n", func.first, q.q50, q.q95, q.q99);
}
log(logFunc, "Benchmark finished.\n\n");
} catch (std::exception& e) { log(logFunc, "Benchmark interrupted: %s.\n\n", e.what()); }
}
Benchmark::Benchmark(const char* name, bench_t func) {
auto& reg = Registry::get();
reg.add(name, func);
}
namespace {
struct {
cv::Mat grayNoise;
cv::Mat grayCircles;
cv::Mat grayBlack;
cv::Mat rect;
cv::Mat out1;
cv::Mat out2;
cv::Mat out3;
fmo::Image grayNoiseImage;
fmo::Image grayCirclesImage;
fmo::Image grayBlackImage;
std::vector<fmo::Image> outImageVec;
std::mt19937 re{5489};
using limits = std::numeric_limits<int>;
std::uniform_int_distribution<int> uniform{limits::min(), limits::max()};
std::uniform_int_distribution<int> randomGray{2, 254};
std::unique_ptr<fmo::Explorer> explorer;
} global;
struct Init {
static const int W = 1920;
static const int H = 1080;
static cv::Mat newGrayMat() { return {cv::Size{W, H}, CV_8UC1}; }
Init() {
{
global.grayNoise = newGrayMat();
auto* data = global.grayNoise.data;
auto* end = data + (W * H);
for (; data < end; data += sizeof(int)) {
*(int*)data = global.uniform(global.re);
}
global.grayNoiseImage.assign(fmo::Format::GRAY, {W, H}, global.grayNoise.data);
}
{
global.grayCircles = newGrayMat();
auto* data = global.grayCircles.data;
for (int r = 0; r < H; r++) {
int rmod = ((r + 128) % 256);
int dy = std::min(rmod, 256 - rmod);
int dy2 = dy * dy;
for (int c = 0; c < W; c++) {
int cmod = ((c + 128) % 256);
int dx = std::min(cmod, 256 - cmod);
int dx2 = dx * dx;
*data++ = (dx2 + dy2 < 10000) ? 0xFF : 0x00;
}
}
global.grayCirclesImage.assign(fmo::Format::GRAY, {W, H},
global.grayCircles.data);
}
{
global.grayBlack = newGrayMat();
auto* data = global.grayBlack.data;
auto len = size_t(W * H);
std::memset(data, 0, len);
global.grayBlackImage.assign(fmo::Format::GRAY, {W, H}, global.grayBlack.data);
}
global.rect = cv::getStructuringElement(cv::MORPH_RECT, {3, 3});
{
fmo::Explorer::Config cfg;
cfg.dims = {W, H};
global.explorer.reset(new fmo::Explorer(cfg));
}
}
};
void init() { static Init once; }
Benchmark FMO_UNIQUE_NAME{"fmo::Explorer::setInput()", []() {
init();
static int i = 0;
const Image* im = (i++ % 2 == 0) ? &global.grayBlackImage
: &global.grayCirclesImage;
global.explorer->setInput(*im);
}};
Benchmark FMO_UNIQUE_NAME{"cv::bitwise_or", []() {
init();
cv::bitwise_or(global.grayNoise, global.grayCircles,
global.out1);
}};
Benchmark FMO_UNIQUE_NAME{"cv::operator+", []() {
init();
global.out1 = global.grayNoise + global.grayCircles;
}};
Benchmark FMO_UNIQUE_NAME{"cv::resize/NEAREST", []() {
init();
cv::resize(global.grayNoise, global.out1,
{Init::W / 2, Init::H / 2}, 0, 0,
cv::INTER_NEAREST);
}};
Benchmark FMO_UNIQUE_NAME{"cv::resize/AREA", []() {
init();
cv::resize(global.grayNoise, global.out1,
{Init::W / 2, Init::H / 2}, 0, 0, cv::INTER_AREA);
}};
Benchmark FMO_UNIQUE_NAME{"fmo::pyramid (6 levels)", []() {
init();
fmo::pyramid(global.grayNoiseImage, global.outImageVec, 6);
}};
Benchmark FMO_UNIQUE_NAME{"cv::threshold", []() {
init();
cv::threshold(global.grayNoise, global.out1, 0x80, 0xFF,
cv::THRESH_BINARY);
}};
Benchmark FMO_UNIQUE_NAME{"cv::absdiff", []() {
init();
cv::absdiff(global.grayNoise, global.grayCircles,
global.out1);
}};
Benchmark FMO_UNIQUE_NAME{"cv::dilate", []() {
init();
cv::dilate(global.grayNoise, global.out1, global.rect);
}};
Benchmark FMO_UNIQUE_NAME{"cv::erode", []() {
init();
cv::erode(global.grayNoise, global.out1, global.rect);
}};
Benchmark FMO_UNIQUE_NAME{"cv::floodFill", []() {
init();
auto newVal = uchar(global.randomGray(global.re));
cv::floodFill(global.grayCircles, cv::Point{0, 0}, newVal);
}};
}
}
<|endoftext|> |
<commit_before>#ifndef __BTREE_NODE_FUNCTIONS_HPP__
#define __BTREE_NODE_FUNCTIONS_HPP__
// We have to have this file because putting these definitions in node.hpp would require mutually recursive header files.
#include "btree/node.hpp"
#include "btree/leaf_node.hpp"
namespace node {
template <class Value>
void split(value_sizer_t<Value> *sizer, buf_t *node_buf, node_t *rnode, btree_key_t *median) {
if (is_leaf(reinterpret_cast<const node_t *>(node_buf->get_data_read()))) {
leaf::split(sizer, node_buf, reinterpret_cast<leaf_node_t *>(rnode), median);
} else {
internal_node::split(sizer->block_size(), node_buf, reinterpret_cast<internal_node_t *>(rnode), median);
}
}
template <class Value>
void merge(value_sizer_t<Value> *sizer, const node_t *node, buf_t *rnode_buf, btree_key_t *key_to_remove, const internal_node_t *parent) {
if (is_leaf(node)) {
leaf::merge(sizer, reinterpret_cast<const leaf_node_t *>(node), rnode_buf, key_to_remove);
} else {
internal_node::merge(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node), rnode_buf, key_to_remove, parent);
}
}
template <class Value>
bool level(value_sizer_t<Value> *sizer, buf_t *node_buf, buf_t *rnode_buf, btree_key_t *key_to_replace, btree_key_t *replacement_key, const internal_node_t *parent) {
if (is_leaf(reinterpret_cast<const node_t *>(node_buf->get_data_read()))) {
return leaf::level(sizer, node_buf, rnode_buf, key_to_replace, replacement_key);
} else {
return internal_node::level(sizer->block_size(), node_buf, rnode_buf, key_to_replace, replacement_key, parent);
}
}
template <class Value>
void validate(UNUSED value_sizer_t<Value> *sizer, UNUSED const node_t *node) {
#ifndef NDEBUG
if (node->magic == leaf_node_t::expected_magic) {
leaf::validate(sizer, reinterpret_cast<const leaf_node_t *>(node));
} else if (node->magic == internal_node_t::expected_magic) {
internal_node::validate(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node));
} else {
unreachable("Invalid leaf node type.");
}
#endif
}
} // namespace node
#endif // __BTREE_NODE_FUNCTIONS_HPP__
<commit_msg>node::validate now also honors other leaf node magics<commit_after>#ifndef __BTREE_NODE_FUNCTIONS_HPP__
#define __BTREE_NODE_FUNCTIONS_HPP__
// We have to have this file because putting these definitions in node.hpp would require mutually recursive header files.
#include "btree/node.hpp"
#include "btree/leaf_node.hpp"
namespace node {
template <class Value>
void split(value_sizer_t<Value> *sizer, buf_t *node_buf, node_t *rnode, btree_key_t *median) {
if (is_leaf(reinterpret_cast<const node_t *>(node_buf->get_data_read()))) {
leaf::split(sizer, node_buf, reinterpret_cast<leaf_node_t *>(rnode), median);
} else {
internal_node::split(sizer->block_size(), node_buf, reinterpret_cast<internal_node_t *>(rnode), median);
}
}
template <class Value>
void merge(value_sizer_t<Value> *sizer, const node_t *node, buf_t *rnode_buf, btree_key_t *key_to_remove, const internal_node_t *parent) {
if (is_leaf(node)) {
leaf::merge(sizer, reinterpret_cast<const leaf_node_t *>(node), rnode_buf, key_to_remove);
} else {
internal_node::merge(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node), rnode_buf, key_to_remove, parent);
}
}
template <class Value>
bool level(value_sizer_t<Value> *sizer, buf_t *node_buf, buf_t *rnode_buf, btree_key_t *key_to_replace, btree_key_t *replacement_key, const internal_node_t *parent) {
if (is_leaf(reinterpret_cast<const node_t *>(node_buf->get_data_read()))) {
return leaf::level(sizer, node_buf, rnode_buf, key_to_replace, replacement_key);
} else {
return internal_node::level(sizer->block_size(), node_buf, rnode_buf, key_to_replace, replacement_key, parent);
}
}
template <class Value>
void validate(UNUSED value_sizer_t<Value> *sizer, UNUSED const node_t *node) {
#ifndef NDEBUG
if (node->magic == sizer->btree_leaf_magic()) {
leaf::validate(sizer, reinterpret_cast<const leaf_node_t *>(node));
} else if (node->magic == internal_node_t::expected_magic) {
internal_node::validate(sizer->block_size(), reinterpret_cast<const internal_node_t *>(node));
} else {
unreachable("Invalid leaf node type.");
}
#endif
}
} // namespace node
#endif // __BTREE_NODE_FUNCTIONS_HPP__
<|endoftext|> |
<commit_before>/* Copyright 2015 Google 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.
==============================================================================*/
#include "tensorflow/stream_executor/cuda/cuda_diagnostics.h"
#include <dirent.h>
#include <limits.h>
#include <link.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
#include <vector>
#include "tensorflow/stream_executor/lib/process_state.h"
#include "tensorflow/stream_executor/lib/error.h"
#include "tensorflow/stream_executor/lib/status.h"
#include "tensorflow/stream_executor/lib/str_util.h"
#include "tensorflow/stream_executor/lib/strcat.h"
#include "tensorflow/stream_executor/lib/stringpiece.h"
#include "tensorflow/stream_executor/lib/stringprintf.h"
#include "tensorflow/stream_executor/platform/logging.h"
#include "tensorflow/stream_executor/lib/numbers.h"
#include "tensorflow/stream_executor/lib/str_util.h"
#include "tensorflow/stream_executor/lib/inlined_vector.h"
namespace perftools {
namespace gputools {
namespace cuda {
static const char *kDriverVersionPath = "/proc/driver/nvidia/version";
string DriverVersionToString(DriverVersion version) {
return port::Printf("%d.%d", std::get<0>(version), std::get<1>(version));
}
string DriverVersionStatusToString(port::StatusOr<DriverVersion> version) {
if (!version.ok()) {
return version.status().ToString();
}
return DriverVersionToString(version.ValueOrDie());
}
port::StatusOr<DriverVersion> StringToDriverVersion(const string &value) {
std::vector<string> pieces = port::Split(value, '.');
if (pieces.size() != 2) {
return port::Status{
port::error::INVALID_ARGUMENT,
port::Printf("expected %%d.%%d form for driver version; got \"%s\"",
value.c_str())};
}
int major;
int minor;
if (!port::safe_strto32(pieces[0], &major)) {
return port::Status{
port::error::INVALID_ARGUMENT,
port::Printf("could not parse major version number \"%s\" as an "
"integer from string \"%s\"",
pieces[0].c_str(), value.c_str())};
}
if (!port::safe_strto32(pieces[1], &minor)) {
return port::Status{
port::error::INVALID_ARGUMENT,
port::Printf("could not parse minor version number \"%s\" as an "
"integer from string \"%s\"",
pieces[1].c_str(), value.c_str())};
}
DriverVersion result{major, minor};
VLOG(2) << "version string \"" << value << "\" made value "
<< DriverVersionToString(result);
return result;
}
// -- class Diagnostician
string Diagnostician::GetDevNodePath(int dev_node_ordinal) {
return port::StrCat("/dev/nvidia", dev_node_ordinal);
}
void Diagnostician::LogDiagnosticInformation() {
if (access(kDriverVersionPath, F_OK) != 0) {
LOG(INFO) << "kernel driver does not appear to be running on this host "
<< "(" << port::Hostname() << "): "
<< "/proc/driver/nvidia/version does not exist";
return;
}
auto dev0_path = GetDevNodePath(0);
if (access(dev0_path.c_str(), F_OK) != 0) {
LOG(INFO) << "no NVIDIA GPU device is present: " << dev0_path
<< " does not exist";
return;
}
LOG(INFO) << "retrieving CUDA diagnostic information for host: "
<< port::Hostname();
LogDriverVersionInformation();
}
/* static */ void Diagnostician::LogDriverVersionInformation() {
LOG(INFO) << "hostname: " << port::Hostname();
if (VLOG_IS_ON(1)) {
const char *value = getenv("LD_LIBRARY_PATH");
string library_path = value == nullptr ? "" : value;
VLOG(1) << "LD_LIBRARY_PATH is: \"" << library_path << "\"";
std::vector<string> pieces = port::Split(library_path, ':');
for (auto piece : pieces) {
if (piece.empty()) {
continue;
}
DIR *dir = opendir(piece.c_str());
if (dir == nullptr) {
VLOG(1) << "could not open \"" << piece << "\"";
continue;
}
while (dirent *entity = readdir(dir)) {
VLOG(1) << piece << " :: " << entity->d_name;
}
closedir(dir);
}
}
port::StatusOr<DriverVersion> dso_version = FindDsoVersion();
LOG(INFO) << "libcuda reported version is: "
<< DriverVersionStatusToString(dso_version);
port::StatusOr<DriverVersion> kernel_version = FindKernelDriverVersion();
LOG(INFO) << "kernel reported version is: "
<< DriverVersionStatusToString(kernel_version);
if (kernel_version.ok() && dso_version.ok()) {
WarnOnDsoKernelMismatch(dso_version, kernel_version);
}
}
// Iterates through loaded DSOs with DlIteratePhdrCallback to find the
// driver-interfacing DSO version number. Returns it as a string.
port::StatusOr<DriverVersion> Diagnostician::FindDsoVersion() {
port::StatusOr<DriverVersion> result{port::Status{
port::error::NOT_FOUND,
"was unable to find libcuda.so DSO loaded into this program"}};
// Callback used when iterating through DSOs. Looks for the driver-interfacing
// DSO and yields its version number into the callback data, when found.
auto iterate_phdr =
[](struct dl_phdr_info *info, size_t size, void *data) -> int {
if (strstr(info->dlpi_name, "libcuda.so")) {
VLOG(1) << "found DLL info with name: " << info->dlpi_name;
char resolved_path[PATH_MAX] = {0};
if (realpath(info->dlpi_name, resolved_path) == nullptr) {
return 0;
}
VLOG(1) << "found DLL info with resolved path: " << resolved_path;
const char *slash = rindex(resolved_path, '/');
if (slash == nullptr) {
return 0;
}
const char *so_suffix = ".so.";
const char *dot = strstr(slash, so_suffix);
if (dot == nullptr) {
return 0;
}
string dso_version = dot + strlen(so_suffix);
// TODO(b/22689637): Eliminate the explicit namespace if possible.
auto stripped_dso_version = port::StripSuffixString(dso_version, ".ld64");
auto result = static_cast<port::StatusOr<DriverVersion> *>(data);
*result = StringToDriverVersion(stripped_dso_version);
return 1;
}
return 0;
};
dl_iterate_phdr(iterate_phdr, &result);
return result;
}
port::StatusOr<DriverVersion> Diagnostician::FindKernelModuleVersion(
const string &driver_version_file_contents) {
static const char *kDriverFilePrelude = "Kernel Module ";
size_t offset = driver_version_file_contents.find(kDriverFilePrelude);
if (offset == string::npos) {
return port::Status{
port::error::NOT_FOUND,
port::StrCat("could not find kernel module information in "
"driver version file contents: \"",
driver_version_file_contents, "\"")};
}
string version_and_rest = driver_version_file_contents.substr(
offset + strlen(kDriverFilePrelude), string::npos);
size_t space_index = version_and_rest.find(" ");
auto kernel_version = version_and_rest.substr(0, space_index);
// TODO(b/22689637): Eliminate the explicit namespace if possible.
auto stripped_kernel_version =
port::StripSuffixString(kernel_version, ".ld64");
return StringToDriverVersion(stripped_kernel_version);
}
void Diagnostician::WarnOnDsoKernelMismatch(
port::StatusOr<DriverVersion> dso_version,
port::StatusOr<DriverVersion> kernel_version) {
if (kernel_version.ok() && dso_version.ok() &&
dso_version.ValueOrDie() == kernel_version.ValueOrDie()) {
LOG(INFO) << "kernel version seems to match DSO: "
<< DriverVersionToString(kernel_version.ValueOrDie());
} else {
LOG(ERROR) << "kernel version "
<< DriverVersionStatusToString(kernel_version)
<< " does not match DSO version "
<< DriverVersionStatusToString(dso_version)
<< " -- cannot find working devices in this configuration";
}
}
port::StatusOr<DriverVersion> Diagnostician::FindKernelDriverVersion() {
FILE *driver_version_file = fopen(kDriverVersionPath, "r");
if (driver_version_file == nullptr) {
return port::Status{
port::error::PERMISSION_DENIED,
port::StrCat("could not open driver version path for reading: ",
kDriverVersionPath)};
}
static const int kContentsSize = 1024;
port::InlinedVector<char, 4> contents(kContentsSize);
size_t retcode =
fread(contents.begin(), 1, kContentsSize - 2, driver_version_file);
if (retcode < kContentsSize - 1) {
contents[retcode] = '\0';
}
contents[kContentsSize - 1] = '\0';
if (retcode != 0) {
LOG(INFO) << "driver version file contents: \"\"\"" << contents.begin()
<< "\"\"\"";
fclose(driver_version_file);
return FindKernelModuleVersion(string{contents.begin()});
}
auto status =
port::Status{port::error::INTERNAL,
port::StrCat("failed to read driver version file contents: ",
kDriverVersionPath, "; ferror: ",
ferror(driver_version_file))};
fclose(driver_version_file);
return status;
}
} // namespace cuda
} // namespace gputools
} // namespace perftools
<commit_msg>TensorFlow: change cuda-diagnostics to search for so.1 Change: 115010103<commit_after>/* Copyright 2015 Google 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.
==============================================================================*/
#include "tensorflow/stream_executor/cuda/cuda_diagnostics.h"
#include <dirent.h>
#include <limits.h>
#include <link.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
#include <vector>
#include "tensorflow/stream_executor/lib/process_state.h"
#include "tensorflow/stream_executor/lib/error.h"
#include "tensorflow/stream_executor/lib/status.h"
#include "tensorflow/stream_executor/lib/str_util.h"
#include "tensorflow/stream_executor/lib/strcat.h"
#include "tensorflow/stream_executor/lib/stringpiece.h"
#include "tensorflow/stream_executor/lib/stringprintf.h"
#include "tensorflow/stream_executor/platform/logging.h"
#include "tensorflow/stream_executor/lib/numbers.h"
#include "tensorflow/stream_executor/lib/str_util.h"
#include "tensorflow/stream_executor/lib/inlined_vector.h"
namespace perftools {
namespace gputools {
namespace cuda {
static const char *kDriverVersionPath = "/proc/driver/nvidia/version";
string DriverVersionToString(DriverVersion version) {
return port::Printf("%d.%d", std::get<0>(version), std::get<1>(version));
}
string DriverVersionStatusToString(port::StatusOr<DriverVersion> version) {
if (!version.ok()) {
return version.status().ToString();
}
return DriverVersionToString(version.ValueOrDie());
}
port::StatusOr<DriverVersion> StringToDriverVersion(const string &value) {
std::vector<string> pieces = port::Split(value, '.');
if (pieces.size() != 2) {
return port::Status{
port::error::INVALID_ARGUMENT,
port::Printf("expected %%d.%%d form for driver version; got \"%s\"",
value.c_str())};
}
int major;
int minor;
if (!port::safe_strto32(pieces[0], &major)) {
return port::Status{
port::error::INVALID_ARGUMENT,
port::Printf("could not parse major version number \"%s\" as an "
"integer from string \"%s\"",
pieces[0].c_str(), value.c_str())};
}
if (!port::safe_strto32(pieces[1], &minor)) {
return port::Status{
port::error::INVALID_ARGUMENT,
port::Printf("could not parse minor version number \"%s\" as an "
"integer from string \"%s\"",
pieces[1].c_str(), value.c_str())};
}
DriverVersion result{major, minor};
VLOG(2) << "version string \"" << value << "\" made value "
<< DriverVersionToString(result);
return result;
}
// -- class Diagnostician
string Diagnostician::GetDevNodePath(int dev_node_ordinal) {
return port::StrCat("/dev/nvidia", dev_node_ordinal);
}
void Diagnostician::LogDiagnosticInformation() {
if (access(kDriverVersionPath, F_OK) != 0) {
LOG(INFO) << "kernel driver does not appear to be running on this host "
<< "(" << port::Hostname() << "): "
<< "/proc/driver/nvidia/version does not exist";
return;
}
auto dev0_path = GetDevNodePath(0);
if (access(dev0_path.c_str(), F_OK) != 0) {
LOG(INFO) << "no NVIDIA GPU device is present: " << dev0_path
<< " does not exist";
return;
}
LOG(INFO) << "retrieving CUDA diagnostic information for host: "
<< port::Hostname();
LogDriverVersionInformation();
}
/* static */ void Diagnostician::LogDriverVersionInformation() {
LOG(INFO) << "hostname: " << port::Hostname();
if (VLOG_IS_ON(1)) {
const char *value = getenv("LD_LIBRARY_PATH");
string library_path = value == nullptr ? "" : value;
VLOG(1) << "LD_LIBRARY_PATH is: \"" << library_path << "\"";
std::vector<string> pieces = port::Split(library_path, ':');
for (auto piece : pieces) {
if (piece.empty()) {
continue;
}
DIR *dir = opendir(piece.c_str());
if (dir == nullptr) {
VLOG(1) << "could not open \"" << piece << "\"";
continue;
}
while (dirent *entity = readdir(dir)) {
VLOG(1) << piece << " :: " << entity->d_name;
}
closedir(dir);
}
}
port::StatusOr<DriverVersion> dso_version = FindDsoVersion();
LOG(INFO) << "libcuda reported version is: "
<< DriverVersionStatusToString(dso_version);
port::StatusOr<DriverVersion> kernel_version = FindKernelDriverVersion();
LOG(INFO) << "kernel reported version is: "
<< DriverVersionStatusToString(kernel_version);
if (kernel_version.ok() && dso_version.ok()) {
WarnOnDsoKernelMismatch(dso_version, kernel_version);
}
}
// Iterates through loaded DSOs with DlIteratePhdrCallback to find the
// driver-interfacing DSO version number. Returns it as a string.
port::StatusOr<DriverVersion> Diagnostician::FindDsoVersion() {
port::StatusOr<DriverVersion> result{port::Status{
port::error::NOT_FOUND,
"was unable to find libcuda.so DSO loaded into this program"}};
// Callback used when iterating through DSOs. Looks for the driver-interfacing
// DSO and yields its version number into the callback data, when found.
auto iterate_phdr =
[](struct dl_phdr_info *info, size_t size, void *data) -> int {
if (strstr(info->dlpi_name, "libcuda.so.1")) {
VLOG(1) << "found DLL info with name: " << info->dlpi_name;
char resolved_path[PATH_MAX] = {0};
if (realpath(info->dlpi_name, resolved_path) == nullptr) {
return 0;
}
VLOG(1) << "found DLL info with resolved path: " << resolved_path;
const char *slash = rindex(resolved_path, '/');
if (slash == nullptr) {
return 0;
}
const char *so_suffix = ".so.";
const char *dot = strstr(slash, so_suffix);
if (dot == nullptr) {
return 0;
}
string dso_version = dot + strlen(so_suffix);
// TODO(b/22689637): Eliminate the explicit namespace if possible.
auto stripped_dso_version = port::StripSuffixString(dso_version, ".ld64");
auto result = static_cast<port::StatusOr<DriverVersion> *>(data);
*result = StringToDriverVersion(stripped_dso_version);
return 1;
}
return 0;
};
dl_iterate_phdr(iterate_phdr, &result);
return result;
}
port::StatusOr<DriverVersion> Diagnostician::FindKernelModuleVersion(
const string &driver_version_file_contents) {
static const char *kDriverFilePrelude = "Kernel Module ";
size_t offset = driver_version_file_contents.find(kDriverFilePrelude);
if (offset == string::npos) {
return port::Status{
port::error::NOT_FOUND,
port::StrCat("could not find kernel module information in "
"driver version file contents: \"",
driver_version_file_contents, "\"")};
}
string version_and_rest = driver_version_file_contents.substr(
offset + strlen(kDriverFilePrelude), string::npos);
size_t space_index = version_and_rest.find(" ");
auto kernel_version = version_and_rest.substr(0, space_index);
// TODO(b/22689637): Eliminate the explicit namespace if possible.
auto stripped_kernel_version =
port::StripSuffixString(kernel_version, ".ld64");
return StringToDriverVersion(stripped_kernel_version);
}
void Diagnostician::WarnOnDsoKernelMismatch(
port::StatusOr<DriverVersion> dso_version,
port::StatusOr<DriverVersion> kernel_version) {
if (kernel_version.ok() && dso_version.ok() &&
dso_version.ValueOrDie() == kernel_version.ValueOrDie()) {
LOG(INFO) << "kernel version seems to match DSO: "
<< DriverVersionToString(kernel_version.ValueOrDie());
} else {
LOG(ERROR) << "kernel version "
<< DriverVersionStatusToString(kernel_version)
<< " does not match DSO version "
<< DriverVersionStatusToString(dso_version)
<< " -- cannot find working devices in this configuration";
}
}
port::StatusOr<DriverVersion> Diagnostician::FindKernelDriverVersion() {
FILE *driver_version_file = fopen(kDriverVersionPath, "r");
if (driver_version_file == nullptr) {
return port::Status{
port::error::PERMISSION_DENIED,
port::StrCat("could not open driver version path for reading: ",
kDriverVersionPath)};
}
static const int kContentsSize = 1024;
port::InlinedVector<char, 4> contents(kContentsSize);
size_t retcode =
fread(contents.begin(), 1, kContentsSize - 2, driver_version_file);
if (retcode < kContentsSize - 1) {
contents[retcode] = '\0';
}
contents[kContentsSize - 1] = '\0';
if (retcode != 0) {
LOG(INFO) << "driver version file contents: \"\"\"" << contents.begin()
<< "\"\"\"";
fclose(driver_version_file);
return FindKernelModuleVersion(string{contents.begin()});
}
auto status =
port::Status{port::error::INTERNAL,
port::StrCat("failed to read driver version file contents: ",
kDriverVersionPath, "; ferror: ",
ferror(driver_version_file))};
fclose(driver_version_file);
return status;
}
} // namespace cuda
} // namespace gputools
} // namespace perftools
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003-2006 Funambol
*
* 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 "base/Log.h"
#include "base/util/utils.h"
#include <unistd.h>
Log LOG = Log(false);
char logmsg[512];
static FILE* logFile = NULL;
static BOOL logFileStdout = FALSE;
void setLogFile(const char* configLogFile, BOOL redirectStderr) {
if (logFile) {
fclose(logFile);
logFile = NULL;
}
logFileStdout = FALSE;
if (configLogFile != NULL) {
if (!strcmp(configLogFile, "-")) {
// write to stdout
logFileStdout = TRUE;
} else {
logFile = fopen(configLogFile, "a+" );
}
}
if (redirectStderr) {
close(2);
dup2(fileno(logFile), 2);
}
}
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
wchar_t* getCurrentTime(BOOL complete) {
time_t t = time(NULL);
struct tm *sys_time = localtime(&t);
wchar_t *fmtComplete = TEXT("%04d-%02d-%02d %02d:%02d:%02d");
wchar_t *fmt = TEXT("%02d:%02d:%02d");
wchar_t* ret = new wchar_t [64];
if (complete) {
wsprintf(ret, fmtComplete, sys_time->tm_year, sys_time->tm_mon, sys_time->tm_mday,
sys_time->tm_hour, sys_time->tm_min, sys_time->tm_sec);
} else {
wsprintf(ret, fmt, sys_time->tm_hour, sys_time->tm_min, sys_time->tm_sec);
}
return ret;
}
Log::Log(BOOL resetLog) {
if (resetLog) {
reset();
}
}
Log::~Log() {
if (logFile != NULL) {
fclose(logFile);
}
}
void Log::error(const wchar_t* msg) {
printMessage(LOG_ERROR, msg);
}
void Log::info(const wchar_t* msg) {
if (logLevel >= LOG_LEVEL_INFO) {
printMessage(LOG_INFO, msg);
}
}
void Log::debug(const wchar_t* msg) {
if (logLevel >= LOG_LEVEL_DEBUG) {
printMessage(LOG_DEBUG, msg);
}
}
void Log::trace(const wchar_t* msg) {
}
void Log::setLevel(LogLevel level) {
logLevel = level;
}
LogLevel Log::getLevel() {
return logLevel;
}
BOOL Log::isLoggable(LogLevel level) {
return (level >= logLevel);
}
void Log::printMessage(const wchar_t* level, const wchar_t* msg) {
wchar_t* currentTime = NULL;
currentTime = getCurrentTime(false);
if (!logFileStdout && !logFile) {
setLogFile(LOG_NAME);
}
fwprintf(logFile ? logFile : stdout,
TEXT("%s [%s] - %s\n"), currentTime, level, msg);
fflush(logFile);
delete[] currentTime;
}
void Log::reset() {
if (!logFileStdout && !logFile) {
setLogFile(LOG_NAME);
}
if (logFile) {
ftruncate(fileno(logFile), 0);
}
}
<commit_msg>restore original stderr after redirecting it<commit_after>/*
* Copyright (C) 2003-2006 Funambol
*
* 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 "base/Log.h"
#include "base/util/utils.h"
#include <unistd.h>
Log LOG = Log(false);
char logmsg[512];
static FILE* logFile = NULL;
static BOOL logFileStdout = FALSE;
// a copy of stderr before it was redirected
static int fderr = -1;
void setLogFile(const char* configLogFile, BOOL redirectStderr) {
if (logFile) {
fclose(logFile);
logFile = NULL;
}
logFileStdout = FALSE;
if (configLogFile != NULL) {
if (!strcmp(configLogFile, "-")) {
// write to stdout
logFileStdout = TRUE;
} else {
logFile = fopen(configLogFile, "a+" );
}
}
if (redirectStderr) {
if (fderr == -1) {
// remember original stderr
fderr = dup(2);
} else {
// close redirected stderr
close(2);
}
dup2(fileno(logFile), 2);
} else {
if (fderr != -1) {
// restore original stderr
dup2(fderr, 2);
}
}
}
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
wchar_t* getCurrentTime(BOOL complete) {
time_t t = time(NULL);
struct tm *sys_time = localtime(&t);
wchar_t *fmtComplete = TEXT("%04d-%02d-%02d %02d:%02d:%02d");
wchar_t *fmt = TEXT("%02d:%02d:%02d");
wchar_t* ret = new wchar_t [64];
if (complete) {
wsprintf(ret, fmtComplete, sys_time->tm_year, sys_time->tm_mon, sys_time->tm_mday,
sys_time->tm_hour, sys_time->tm_min, sys_time->tm_sec);
} else {
wsprintf(ret, fmt, sys_time->tm_hour, sys_time->tm_min, sys_time->tm_sec);
}
return ret;
}
Log::Log(BOOL resetLog) {
if (resetLog) {
reset();
}
}
Log::~Log() {
if (logFile != NULL) {
fclose(logFile);
}
}
void Log::error(const wchar_t* msg) {
printMessage(LOG_ERROR, msg);
}
void Log::info(const wchar_t* msg) {
if (logLevel >= LOG_LEVEL_INFO) {
printMessage(LOG_INFO, msg);
}
}
void Log::debug(const wchar_t* msg) {
if (logLevel >= LOG_LEVEL_DEBUG) {
printMessage(LOG_DEBUG, msg);
}
}
void Log::trace(const wchar_t* msg) {
}
void Log::setLevel(LogLevel level) {
logLevel = level;
}
LogLevel Log::getLevel() {
return logLevel;
}
BOOL Log::isLoggable(LogLevel level) {
return (level >= logLevel);
}
void Log::printMessage(const wchar_t* level, const wchar_t* msg) {
wchar_t* currentTime = NULL;
currentTime = getCurrentTime(false);
if (!logFileStdout && !logFile) {
setLogFile(LOG_NAME);
}
fwprintf(logFile ? logFile : stdout,
TEXT("%s [%s] - %s\n"), currentTime, level, msg);
fflush(logFile);
delete[] currentTime;
}
void Log::reset() {
if (!logFileStdout && !logFile) {
setLogFile(LOG_NAME);
}
if (logFile) {
ftruncate(fileno(logFile), 0);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractGrid.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkExtractGrid.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------
vtkExtractGrid* vtkExtractGrid::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractGrid");
if(ret)
{
return (vtkExtractGrid*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkExtractGrid;
}
// Construct object to extract all of the input data.
vtkExtractGrid::vtkExtractGrid()
{
this->VOI[0] = this->VOI[2] = this->VOI[4] = 0;
this->VOI[1] = this->VOI[3] = this->VOI[5] = VTK_LARGE_INTEGER;
this->SampleRate[0] = this->SampleRate[1] = this->SampleRate[2] = 1;
this->IncludeBoundary = 0;
}
void vtkExtractGrid::ComputeInputUpdateExtents(vtkDataObject *vtkNotUsed(out))
{
vtkStructuredGrid *input = this->GetInput();
vtkStructuredGrid *output = this->GetOutput();
int i, ext[6], voi[6];
int *inWholeExt, *outWholeExt, *updateExt;
inWholeExt = input->GetWholeExtent();
outWholeExt = output->GetWholeExtent();
updateExt = output->GetUpdateExtent();
// Once again, clip the VOI with the input whole extent.
for (i = 0; i < 3; ++i)
{
voi[i*2] = this->VOI[2*i];
if (voi[2*i] < inWholeExt[2*i])
{
voi[2*i] = inWholeExt[2*i];
}
voi[i*2+1] = this->VOI[2*i+1];
if (voi[2*i+1] > inWholeExt[2*i+1])
{
voi[2*i+1] = inWholeExt[2*i+1];
}
}
ext[0] = voi[0] + (updateExt[0]-outWholeExt[0])*this->SampleRate[0];
ext[1] = voi[0] + (updateExt[1]-outWholeExt[0])*this->SampleRate[0];
if (ext[1] > voi[1])
{ // This handles the IncludeBoundary condition.
ext[1] = voi[1];
}
ext[2] = voi[2] + (updateExt[2]-outWholeExt[2])*this->SampleRate[1];
ext[3] = voi[2] + (updateExt[3]-outWholeExt[2])*this->SampleRate[1];
if (ext[3] > voi[3])
{ // This handles the IncludeBoundary condition.
ext[3] = voi[3];
}
ext[4] = voi[4] + (updateExt[4]-outWholeExt[4])*this->SampleRate[2];
ext[5] = voi[4] + (updateExt[5]-outWholeExt[4])*this->SampleRate[2];
if (ext[5] > voi[5])
{ // This handles the IncludeBoundary condition.
ext[5] = voi[5];
}
// I do not think we need this extra check, but it cannot hurt.
if (ext[0] < inWholeExt[0])
{
ext[0] = inWholeExt[0];
}
if (ext[1] > inWholeExt[1])
{
ext[1] = inWholeExt[1];
}
if (ext[2] < inWholeExt[2])
{
ext[2] = inWholeExt[2];
}
if (ext[3] > inWholeExt[3])
{
ext[3] = inWholeExt[3];
}
if (ext[4] < inWholeExt[4])
{
ext[4] = inWholeExt[4];
}
if (ext[5] > inWholeExt[5])
{
ext[5] = inWholeExt[5];
}
input->SetUpdateExtent(ext);
}
void vtkExtractGrid::ExecuteInformation()
{
vtkStructuredGrid *input= this->GetInput();
vtkStructuredGrid *output= this->GetOutput();
int i, outDims[3], voi[6], wholeExtent[6];
int mins[3];
int rate[3];
if (this->GetInput() == NULL)
{
vtkErrorMacro("Missing input");
return;
}
this->vtkStructuredGridToStructuredGridFilter::ExecuteInformation();
input->GetWholeExtent(wholeExtent);
// Copy because we need to take union of voi and whole extent.
for ( i=0; i < 6; i++ )
{
voi[i] = this->VOI[i];
}
for ( i=0; i < 3; i++ )
{
// Empty request.
if (voi[2*i+1] < voi[2*i] || voi[2*i+1] < wholeExtent[2*i] ||
voi[2*i] > wholeExtent[2*i+1])
{
output->SetWholeExtent(0,-1,0,-1,0,-1);
return;
}
// Make sure VOI is in the whole extent.
if ( voi[2*i+1] > wholeExtent[2*i+1] )
{
voi[2*i+1] = wholeExtent[2*i+1];
}
else if ( voi[2*i+1] < wholeExtent[2*i] )
{
voi[2*i+1] = wholeExtent[2*i];
}
if ( voi[2*i] > wholeExtent[2*i+1] )
{
voi[2*i] = wholeExtent[2*i+1];
}
else if ( voi[2*i] < wholeExtent[2*i] )
{
voi[2*i] = wholeExtent[2*i];
}
if ( (rate[i] = this->SampleRate[i]) < 1 )
{
rate[i] = 1;
}
outDims[i] = (voi[2*i+1] - voi[2*i]) / rate[i] + 1;
if ( outDims[i] < 1 )
{
outDims[i] = 1;
}
// We might as well make this work for negative extents.
mins[i] = (int)(floor((float)voi[2*i] / (float)rate[i]));
}
// Adjust the output dimensions if the boundaries are to be
// included and the sample rate is not 1.
if ( this->IncludeBoundary &&
(rate[0] != 1 || rate[1] != 1 || rate[2] != 1) )
{
int diff;
for (i=0; i<3; i++)
{
if ( ((diff=voi[2*i+1]-voi[2*i]) > 0) && rate[i] != 1 &&
((diff % rate[i]) != 0) )
{
outDims[i]++;
}
}
}
// Set the whole extent of the output
wholeExtent[0] = mins[0];
wholeExtent[1] = mins[0] + outDims[0] - 1;
wholeExtent[2] = mins[1];
wholeExtent[3] = mins[1] + outDims[1] - 1;
wholeExtent[4] = mins[2];
wholeExtent[5] = mins[2] + outDims[2] - 1;
output->SetWholeExtent(wholeExtent);
}
void vtkExtractGrid::Execute()
{
vtkStructuredGrid *input= this->GetInput();
vtkPointData *pd=input->GetPointData();
vtkCellData *cd=input->GetCellData();
vtkStructuredGrid *output= this->GetOutput();
vtkPointData *outPD=output->GetPointData();
vtkCellData *outCD=output->GetCellData();
int i, j, k, *uExt, voi[6];
int *inExt, *outWholeExt;
int iIn, jIn, kIn;
int outSize, jOffset, kOffset, *rate;
vtkIdType idx, newIdx, newCellId;
vtkPoints *newPts, *inPts;
int inInc1, inInc2;
vtkDebugMacro(<< "Extracting Grid");
inPts = input->GetPoints();
outWholeExt = output->GetWholeExtent();
uExt = output->GetUpdateExtent();
rate = this->SampleRate;
inExt = input->GetExtent();
inInc1 = (inExt[1]-inExt[0]+1);
inInc2 = inInc1*(inExt[3]-inExt[2]+1);
// Clip the VOI by the input extent
for (i = 0; i < 3; ++i)
{
voi[i*2] = this->VOI[2*i];
if (voi[2*i] < inExt[2*i])
{
voi[2*i] = inExt[2*i];
}
voi[i*2+1] = this->VOI[2*i+1];
if (voi[2*i+1] > inExt[2*i+1])
{
voi[2*i+1] = inExt[2*i+1];
}
}
output->SetExtent(uExt);
// If output same as input, just pass data through
if ( uExt[0] <= inExt[0] && uExt[1] >= inExt[1] &&
uExt[2] <= inExt[2] && uExt[3] >= inExt[3] &&
uExt[4] <= inExt[4] && uExt[5] >= inExt[5] &&
rate[0] == 1 && rate[1] == 1 && rate[2] == 1)
{
output->SetPoints(inPts);
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
vtkDebugMacro(<<"Passed data through bacause input and output are the same");
return;
}
// Allocate necessary objects
//
outSize = (uExt[1]-uExt[0]+1)*(uExt[3]-uExt[2]+1)*(uExt[5]-uExt[4]+1);
newPts = (vtkPoints *) inPts->MakeObject();
newPts->SetNumberOfPoints(outSize);
outPD->CopyAllocate(pd,outSize,outSize);
outCD->CopyAllocate(cd,outSize,outSize);
// Traverse input data and copy point attributes to output
// iIn,jIn,kIn are in input grid coordinates.
newIdx = 0;
for ( k=uExt[4]; k <= uExt[5]; ++k)
{ // Convert out coords to in coords.
kIn = voi[4] + ((k-outWholeExt[4])*rate[2]);
if (kIn > voi[5])
{ // This handles the IncludeBoundaryOn condition.
kIn = voi[5];
}
kOffset = (kIn-inExt[4]) * inInc2;
for ( j=uExt[2]; j <= uExt[3]; ++j)
{ // Convert out coords to in coords.
jIn = voi[2] + ((j-outWholeExt[2])*rate[1]);
if (jIn > voi[3])
{ // This handles the IncludeBoundaryOn condition.
jIn = voi[3];
}
jOffset = (jIn-inExt[2]) * inInc1;
for ( i=uExt[0]; i <= uExt[1]; ++i)
{ // Convert out coords to in coords.
iIn = voi[0] + ((i-outWholeExt[0])*rate[0]);
if (iIn > voi[1])
{ // This handles the IncludeBoundaryOn condition.
iIn = voi[1];
}
idx = (iIn-inExt[0]) + jOffset + kOffset;
newPts->SetPoint(newIdx,inPts->GetPoint(idx));
outPD->CopyData(pd, idx, newIdx++);
}
}
}
// Traverse input data and copy cell attributes to output
//
newCellId = 0;
inInc1 = (inExt[1]-inExt[0]);
inInc2 = inInc1*(inExt[3]-inExt[2]);
// No need to consider IncludeBoundary for cell data.
for ( k=uExt[4]; k < uExt[5]; ++k )
{ // Convert out coords to in coords.
kIn = voi[4] + ((k-outWholeExt[4])*rate[2]);
kOffset = (kIn-inExt[4]) * inInc2;
for ( j=uExt[2]; j < uExt[3]; ++j )
{ // Convert out coords to in coords.
jIn = voi[2] + ((j-outWholeExt[2])*rate[1]);
jOffset = (jIn-inExt[2]) * inInc1;
for ( i=uExt[0]; i < uExt[1]; ++i )
{
iIn = voi[0] + ((i-outWholeExt[0])*rate[0]);
idx = (iIn-inExt[0]) + jOffset + kOffset;
outCD->CopyData(cd, idx, newCellId++);
}
}
}
output->SetPoints(newPts);
newPts->Delete();
}
void vtkExtractGrid::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredGridToStructuredGridFilter::PrintSelf(os,indent);
os << indent << "VOI: \n";
os << indent << " Imin,Imax: (" << this->VOI[0] << ", "
<< this->VOI[1] << ")\n";
os << indent << " Jmin,Jmax: (" << this->VOI[2] << ", "
<< this->VOI[3] << ")\n";
os << indent << " Kmin,Kmax: (" << this->VOI[4] << ", "
<< this->VOI[5] << ")\n";
os << indent << "Sample Rate: (" << this->SampleRate[0] << ", "
<< this->SampleRate[1] << ", "
<< this->SampleRate[2] << ")\n";
os << indent << "Include Boundary: "
<< (this->IncludeBoundary ? "On\n" : "Off\n");
}
<commit_msg>Needed a bounds check.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractGrid.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkExtractGrid.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------
vtkExtractGrid* vtkExtractGrid::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractGrid");
if(ret)
{
return (vtkExtractGrid*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkExtractGrid;
}
// Construct object to extract all of the input data.
vtkExtractGrid::vtkExtractGrid()
{
this->VOI[0] = this->VOI[2] = this->VOI[4] = 0;
this->VOI[1] = this->VOI[3] = this->VOI[5] = VTK_LARGE_INTEGER;
this->SampleRate[0] = this->SampleRate[1] = this->SampleRate[2] = 1;
this->IncludeBoundary = 0;
}
void vtkExtractGrid::ComputeInputUpdateExtents(vtkDataObject *vtkNotUsed(out))
{
vtkStructuredGrid *input = this->GetInput();
vtkStructuredGrid *output = this->GetOutput();
int i, ext[6], voi[6];
int *inWholeExt, *outWholeExt, *updateExt;
int rate[3];
inWholeExt = input->GetWholeExtent();
outWholeExt = output->GetWholeExtent();
updateExt = output->GetUpdateExtent();
for (i = 0; i < 3; ++i)
{
rate[i] = this->SampleRate[i];
if (rate[i] < 1)
{
rate[i] = 1;
}
}
// Once again, clip the VOI with the input whole extent.
for (i = 0; i < 3; ++i)
{
voi[i*2] = this->VOI[2*i];
if (voi[2*i] < inWholeExt[2*i])
{
voi[2*i] = inWholeExt[2*i];
}
voi[i*2+1] = this->VOI[2*i+1];
if (voi[2*i+1] > inWholeExt[2*i+1])
{
voi[2*i+1] = inWholeExt[2*i+1];
}
}
ext[0] = voi[0] + (updateExt[0]-outWholeExt[0])*rate[0];
ext[1] = voi[0] + (updateExt[1]-outWholeExt[0])*rate[0];
if (ext[1] > voi[1])
{ // This handles the IncludeBoundary condition.
ext[1] = voi[1];
}
ext[2] = voi[2] + (updateExt[2]-outWholeExt[2])*rate[1];
ext[3] = voi[2] + (updateExt[3]-outWholeExt[2])*rate[1];
if (ext[3] > voi[3])
{ // This handles the IncludeBoundary condition.
ext[3] = voi[3];
}
ext[4] = voi[4] + (updateExt[4]-outWholeExt[4])*rate[2];
ext[5] = voi[4] + (updateExt[5]-outWholeExt[4])*rate[2];
if (ext[5] > voi[5])
{ // This handles the IncludeBoundary condition.
ext[5] = voi[5];
}
// I do not think we need this extra check, but it cannot hurt.
if (ext[0] < inWholeExt[0])
{
ext[0] = inWholeExt[0];
}
if (ext[1] > inWholeExt[1])
{
ext[1] = inWholeExt[1];
}
if (ext[2] < inWholeExt[2])
{
ext[2] = inWholeExt[2];
}
if (ext[3] > inWholeExt[3])
{
ext[3] = inWholeExt[3];
}
if (ext[4] < inWholeExt[4])
{
ext[4] = inWholeExt[4];
}
if (ext[5] > inWholeExt[5])
{
ext[5] = inWholeExt[5];
}
input->SetUpdateExtent(ext);
}
void vtkExtractGrid::ExecuteInformation()
{
vtkStructuredGrid *input= this->GetInput();
vtkStructuredGrid *output= this->GetOutput();
int i, outDims[3], voi[6], wholeExtent[6];
int mins[3];
int rate[3];
if (this->GetInput() == NULL)
{
vtkErrorMacro("Missing input");
return;
}
this->vtkStructuredGridToStructuredGridFilter::ExecuteInformation();
input->GetWholeExtent(wholeExtent);
// Copy because we need to take union of voi and whole extent.
for ( i=0; i < 6; i++ )
{
voi[i] = this->VOI[i];
}
for ( i=0; i < 3; i++ )
{
// Empty request.
if (voi[2*i+1] < voi[2*i] || voi[2*i+1] < wholeExtent[2*i] ||
voi[2*i] > wholeExtent[2*i+1])
{
output->SetWholeExtent(0,-1,0,-1,0,-1);
return;
}
// Make sure VOI is in the whole extent.
if ( voi[2*i+1] > wholeExtent[2*i+1] )
{
voi[2*i+1] = wholeExtent[2*i+1];
}
else if ( voi[2*i+1] < wholeExtent[2*i] )
{
voi[2*i+1] = wholeExtent[2*i];
}
if ( voi[2*i] > wholeExtent[2*i+1] )
{
voi[2*i] = wholeExtent[2*i+1];
}
else if ( voi[2*i] < wholeExtent[2*i] )
{
voi[2*i] = wholeExtent[2*i];
}
if ( (rate[i] = this->SampleRate[i]) < 1 )
{
rate[i] = 1;
}
outDims[i] = (voi[2*i+1] - voi[2*i]) / rate[i] + 1;
if ( outDims[i] < 1 )
{
outDims[i] = 1;
}
// We might as well make this work for negative extents.
mins[i] = (int)(floor((float)voi[2*i] / (float)rate[i]));
}
// Adjust the output dimensions if the boundaries are to be
// included and the sample rate is not 1.
if ( this->IncludeBoundary &&
(rate[0] != 1 || rate[1] != 1 || rate[2] != 1) )
{
int diff;
for (i=0; i<3; i++)
{
if ( ((diff=voi[2*i+1]-voi[2*i]) > 0) && rate[i] != 1 &&
((diff % rate[i]) != 0) )
{
outDims[i]++;
}
}
}
// Set the whole extent of the output
wholeExtent[0] = mins[0];
wholeExtent[1] = mins[0] + outDims[0] - 1;
wholeExtent[2] = mins[1];
wholeExtent[3] = mins[1] + outDims[1] - 1;
wholeExtent[4] = mins[2];
wholeExtent[5] = mins[2] + outDims[2] - 1;
output->SetWholeExtent(wholeExtent);
}
void vtkExtractGrid::Execute()
{
vtkStructuredGrid *input= this->GetInput();
vtkPointData *pd=input->GetPointData();
vtkCellData *cd=input->GetCellData();
vtkStructuredGrid *output= this->GetOutput();
vtkPointData *outPD=output->GetPointData();
vtkCellData *outCD=output->GetCellData();
int i, j, k, *uExt, voi[6];
int *inExt, *outWholeExt;
int iIn, jIn, kIn;
int outSize, jOffset, kOffset, rate[3];
vtkIdType idx, newIdx, newCellId;
vtkPoints *newPts, *inPts;
int inInc1, inInc2;
vtkDebugMacro(<< "Extracting Grid");
inPts = input->GetPoints();
outWholeExt = output->GetWholeExtent();
uExt = output->GetUpdateExtent();
inExt = input->GetExtent();
inInc1 = (inExt[1]-inExt[0]+1);
inInc2 = inInc1*(inExt[3]-inExt[2]+1);
for (i = 0; i < 3; ++i)
{
if ( (rate[i] = this->SampleRate[i]) < 1 )
{
rate[i] = 1;
}
}
// Clip the VOI by the input extent
for (i = 0; i < 3; ++i)
{
voi[i*2] = this->VOI[2*i];
if (voi[2*i] < inExt[2*i])
{
voi[2*i] = inExt[2*i];
}
voi[i*2+1] = this->VOI[2*i+1];
if (voi[2*i+1] > inExt[2*i+1])
{
voi[2*i+1] = inExt[2*i+1];
}
}
output->SetExtent(uExt);
// If output same as input, just pass data through
if ( uExt[0] <= inExt[0] && uExt[1] >= inExt[1] &&
uExt[2] <= inExt[2] && uExt[3] >= inExt[3] &&
uExt[4] <= inExt[4] && uExt[5] >= inExt[5] &&
rate[0] == 1 && rate[1] == 1 && rate[2] == 1)
{
output->SetPoints(inPts);
output->GetPointData()->PassData(input->GetPointData());
output->GetCellData()->PassData(input->GetCellData());
vtkDebugMacro(<<"Passed data through bacause input and output are the same");
return;
}
// Allocate necessary objects
//
outSize = (uExt[1]-uExt[0]+1)*(uExt[3]-uExt[2]+1)*(uExt[5]-uExt[4]+1);
newPts = (vtkPoints *) inPts->MakeObject();
newPts->SetNumberOfPoints(outSize);
outPD->CopyAllocate(pd,outSize,outSize);
outCD->CopyAllocate(cd,outSize,outSize);
// Traverse input data and copy point attributes to output
// iIn,jIn,kIn are in input grid coordinates.
newIdx = 0;
for ( k=uExt[4]; k <= uExt[5]; ++k)
{ // Convert out coords to in coords.
kIn = voi[4] + ((k-outWholeExt[4])*rate[2]);
if (kIn > voi[5])
{ // This handles the IncludeBoundaryOn condition.
kIn = voi[5];
}
kOffset = (kIn-inExt[4]) * inInc2;
for ( j=uExt[2]; j <= uExt[3]; ++j)
{ // Convert out coords to in coords.
jIn = voi[2] + ((j-outWholeExt[2])*rate[1]);
if (jIn > voi[3])
{ // This handles the IncludeBoundaryOn condition.
jIn = voi[3];
}
jOffset = (jIn-inExt[2]) * inInc1;
for ( i=uExt[0]; i <= uExt[1]; ++i)
{ // Convert out coords to in coords.
iIn = voi[0] + ((i-outWholeExt[0])*rate[0]);
if (iIn > voi[1])
{ // This handles the IncludeBoundaryOn condition.
iIn = voi[1];
}
idx = (iIn-inExt[0]) + jOffset + kOffset;
newPts->SetPoint(newIdx,inPts->GetPoint(idx));
outPD->CopyData(pd, idx, newIdx++);
}
}
}
// Traverse input data and copy cell attributes to output
//
newCellId = 0;
inInc1 = (inExt[1]-inExt[0]);
inInc2 = inInc1*(inExt[3]-inExt[2]);
// No need to consider IncludeBoundary for cell data.
for ( k=uExt[4]; k < uExt[5]; ++k )
{ // Convert out coords to in coords.
kIn = voi[4] + ((k-outWholeExt[4])*rate[2]);
kOffset = (kIn-inExt[4]) * inInc2;
for ( j=uExt[2]; j < uExt[3]; ++j )
{ // Convert out coords to in coords.
jIn = voi[2] + ((j-outWholeExt[2])*rate[1]);
jOffset = (jIn-inExt[2]) * inInc1;
for ( i=uExt[0]; i < uExt[1]; ++i )
{
iIn = voi[0] + ((i-outWholeExt[0])*rate[0]);
idx = (iIn-inExt[0]) + jOffset + kOffset;
outCD->CopyData(cd, idx, newCellId++);
}
}
}
output->SetPoints(newPts);
newPts->Delete();
}
void vtkExtractGrid::PrintSelf(ostream& os, vtkIndent indent)
{
vtkStructuredGridToStructuredGridFilter::PrintSelf(os,indent);
os << indent << "VOI: \n";
os << indent << " Imin,Imax: (" << this->VOI[0] << ", "
<< this->VOI[1] << ")\n";
os << indent << " Jmin,Jmax: (" << this->VOI[2] << ", "
<< this->VOI[3] << ")\n";
os << indent << " Kmin,Kmax: (" << this->VOI[4] << ", "
<< this->VOI[5] << ")\n";
os << indent << "Sample Rate: (" << this->SampleRate[0] << ", "
<< this->SampleRate[1] << ", "
<< this->SampleRate[2] << ")\n";
os << indent << "Include Boundary: "
<< (this->IncludeBoundary ? "On\n" : "Off\n");
}
<|endoftext|> |
<commit_before>#include "osg_tools.h"
#include <osg/Geometry>
#include "osg/Material"
#include "xo/container/prop_node.h"
#include "xo/system/log.h"
#include "xo/time/timer.h"
#include "xo/serialization/prop_node_tools.h"
#include "xo/serialization/serialize.h"
using namespace xo;
namespace vis
{
osg::Geode* create_tile_floor( int x_tiles, int z_tiles, float tile_width /*= 1.0f */ )
{
// fill in vertices for grid, note numTilesX+1 * numTilesY+1...
osg::Vec3Array* coords = new osg::Vec3Array;
for ( int z = 0; z <= z_tiles; ++z )
{
for ( int x = 0; x <= x_tiles; ++x )
coords->push_back( -osg::Vec3( ( x - x_tiles / 2 ) * tile_width, 0, -( z - z_tiles / 2 ) * tile_width ) );
}
//Just two colors - gray and grey
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back( osg::Vec4( 0.6f, 0.6f, 0.6f, 1.0f ) ); // white
colors->push_back( osg::Vec4( 0.5f, 0.5f, 0.5f, 1.0f ) ); // black
osg::ref_ptr<osg::DrawElementsUShort> whitePrimitives = new osg::DrawElementsUShort( GL_QUADS );
osg::ref_ptr<osg::DrawElementsUShort> blackPrimitives = new osg::DrawElementsUShort( GL_QUADS );
int numIndicesPerRow = x_tiles + 1;
for ( int iz = 0; iz < z_tiles; ++iz )
{
for ( int ix = 0; ix < x_tiles; ++ix )
{
osg::DrawElementsUShort* primitives = ( ( iz + ix ) % 2 == 0 ) ? whitePrimitives.get() : blackPrimitives.get();
primitives->push_back( ix + ( iz + 1 )*numIndicesPerRow );
primitives->push_back( ix + iz*numIndicesPerRow );
primitives->push_back( ( ix + 1 ) + iz*numIndicesPerRow );
primitives->push_back( ( ix + 1 ) + ( iz + 1 )*numIndicesPerRow );
}
}
// set up a single normal
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back( osg::Vec3( 0.0f, 1.0f, 0.0f ) );
osg::Geometry* geom = new osg::Geometry;
geom->setVertexArray( coords );
geom->setColorArray( colors, osg::Array::BIND_PER_PRIMITIVE_SET );
geom->setNormalArray( normals, osg::Array::BIND_OVERALL );
geom->setCullingActive( true );
geom->addPrimitiveSet( whitePrimitives.get() );
geom->addPrimitiveSet( blackPrimitives.get() );
osg::Geode* geode = new osg::Geode;
geode->addDrawable( geom );
geode->getOrCreateStateSet()->setMode( GL_CULL_FACE, osg::StateAttribute::ON );
osg::Material* mat = new osg::Material;
mat->setColorMode( osg::Material::EMISSION );
mat->setSpecular( osg::Material::FRONT_AND_BACK, osg::Vec4( 0, 0, 0, 0 ) );
mat->setDiffuse( osg::Material::FRONT_AND_BACK, osg::Vec4( 0, 0, 0, 0 ) );
mat->setAmbient( osg::Material::FRONT_AND_BACK, osg::Vec4( 0, 0, 0, 0 ) );
geode->getOrCreateStateSet()->setAttribute( mat );
return geode;
}
SIMVIS_API osg::ref_ptr< osg::Geode > read_vtp( const path& filename )
{
prop_node root_pn = load_xml( filename );
prop_node& poly_pn = root_pn[ "VTKFile" ][ "PolyData" ][ "Piece" ];
auto point_count = poly_pn.get< int >( "NumberOfPoints");
auto poly_count = poly_pn.get< int >( "NumberOfPolys" );
// create normal and vertex array
osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array( point_count );
osg::Vec3Array* vertices = new osg::Vec3Array( point_count );
auto normal_vec = str_to_vec< float >( poly_pn[ "PointData" ][ "DataArray" ].get_value(), point_count * 3 );
auto point_vec = str_to_vec< float >( poly_pn[ "Points" ][ "DataArray" ].get_value(), point_count * 3 );
xo_assert( normal_vec.size() == point_count * 3 && point_vec.size() == point_count * 3 );
size_t vec_idx = 0;
for ( int idx = 0; idx < point_count; ++idx )
{
normals->at( idx ).set( normal_vec[ vec_idx ], normal_vec[ vec_idx + 1 ], normal_vec[ vec_idx + 2] );
vertices->at( idx ).set( point_vec[ vec_idx ], point_vec[ vec_idx + 1 ], point_vec[ vec_idx + 2] );
vec_idx += 3;
}
osg::ref_ptr< osg::DrawElementsUShort > trianglePrimitives = new osg::DrawElementsUShort( GL_TRIANGLES );
osg::ref_ptr< osg::DrawElementsUShort > quadPrimitives = new osg::DrawElementsUShort( GL_QUADS );
{
auto con_vec = str_to_vec< int >( poly_pn[ "Polys" ][ 0 ].get_value(), no_index );
auto ofs_vec = str_to_vec< int >( poly_pn[ "Polys" ][ 1 ].get_value(), no_index );
for ( size_t idx = 0; idx < ofs_vec.size(); ++idx )
{
auto end_ofs = ofs_vec[ idx ];
auto begin_ofs = idx == 0 ? unsigned short( 0 ) : ofs_vec[ idx - 1 ];
auto num_ver = end_ofs - begin_ofs;
if ( num_ver == 3 )
{
trianglePrimitives->push_back( (unsigned short) con_vec[begin_ofs] );
trianglePrimitives->push_back( (unsigned short) con_vec[begin_ofs + 1] );
trianglePrimitives->push_back( (unsigned short) con_vec[begin_ofs + 2] );
}
else if ( num_ver == 4 )
{
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs] );
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs + 1] );
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs + 2] );
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs + 3] );
}
else
{
// silently ignore...
//xo::log::warning( "Unknown primitive type, number of vertices = ", num_ver );
}
}
}
// add primitives
osg::Geometry* polyGeom = new osg::Geometry;
if ( trianglePrimitives->size() > 0 )
polyGeom->addPrimitiveSet( trianglePrimitives );
if ( quadPrimitives->size() > 0 )
polyGeom->addPrimitiveSet( quadPrimitives );
// create color array (shared)
//osg::ref_ptr<osg::Vec4Array> shared_colors = new osg::Vec4Array;
//shared_colors->push_back(osg::Vec4(1.0f,0.0f,0.0f,1.0f));
//polyGeom->setColorArray( shared_colors.get(), osg::Array::BIND_OVERALL );
// pass the created vertex array to the points geometry object
polyGeom->setVertexArray( vertices );
polyGeom->setNormalArray( normals, osg::Array::BIND_PER_VERTEX );
polyGeom->setCullingActive( true );
// add the points geometry to the geode.
osg::ref_ptr< osg::Geode > geode = new osg::Geode;
geode->addDrawable(polyGeom);
geode->getOrCreateStateSet()->setMode( GL_CULL_FACE, osg::StateAttribute::ON );
return geode;
}
void set_shadow_mask( osg::Node* n, bool receive, bool cast )
{
n->setNodeMask( receive ? n->getNodeMask() | OsgReceiveShadowMask : n->getNodeMask() & ~OsgReceiveShadowMask );
n->setNodeMask( cast ? n->getNodeMask() | OsgCastShadowMask : n->getNodeMask() & ~OsgCastShadowMask );
}
}
<commit_msg>include fixes<commit_after>#include "osg_tools.h"
#include <osg/Geometry>
#include "osg/Material"
#include "xo/container/prop_node.h"
#include "xo/system/log.h"
#include "xo/time/timer.h"
#include "xo/container/prop_node_tools.h"
#include "xo/serialization/serialize.h"
using namespace xo;
namespace vis
{
osg::Geode* create_tile_floor( int x_tiles, int z_tiles, float tile_width /*= 1.0f */ )
{
// fill in vertices for grid, note numTilesX+1 * numTilesY+1...
osg::Vec3Array* coords = new osg::Vec3Array;
for ( int z = 0; z <= z_tiles; ++z )
{
for ( int x = 0; x <= x_tiles; ++x )
coords->push_back( -osg::Vec3( ( x - x_tiles / 2 ) * tile_width, 0, -( z - z_tiles / 2 ) * tile_width ) );
}
//Just two colors - gray and grey
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back( osg::Vec4( 0.6f, 0.6f, 0.6f, 1.0f ) ); // white
colors->push_back( osg::Vec4( 0.5f, 0.5f, 0.5f, 1.0f ) ); // black
osg::ref_ptr<osg::DrawElementsUShort> whitePrimitives = new osg::DrawElementsUShort( GL_QUADS );
osg::ref_ptr<osg::DrawElementsUShort> blackPrimitives = new osg::DrawElementsUShort( GL_QUADS );
int numIndicesPerRow = x_tiles + 1;
for ( int iz = 0; iz < z_tiles; ++iz )
{
for ( int ix = 0; ix < x_tiles; ++ix )
{
osg::DrawElementsUShort* primitives = ( ( iz + ix ) % 2 == 0 ) ? whitePrimitives.get() : blackPrimitives.get();
primitives->push_back( ix + ( iz + 1 )*numIndicesPerRow );
primitives->push_back( ix + iz*numIndicesPerRow );
primitives->push_back( ( ix + 1 ) + iz*numIndicesPerRow );
primitives->push_back( ( ix + 1 ) + ( iz + 1 )*numIndicesPerRow );
}
}
// set up a single normal
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back( osg::Vec3( 0.0f, 1.0f, 0.0f ) );
osg::Geometry* geom = new osg::Geometry;
geom->setVertexArray( coords );
geom->setColorArray( colors, osg::Array::BIND_PER_PRIMITIVE_SET );
geom->setNormalArray( normals, osg::Array::BIND_OVERALL );
geom->setCullingActive( true );
geom->addPrimitiveSet( whitePrimitives.get() );
geom->addPrimitiveSet( blackPrimitives.get() );
osg::Geode* geode = new osg::Geode;
geode->addDrawable( geom );
geode->getOrCreateStateSet()->setMode( GL_CULL_FACE, osg::StateAttribute::ON );
osg::Material* mat = new osg::Material;
mat->setColorMode( osg::Material::EMISSION );
mat->setSpecular( osg::Material::FRONT_AND_BACK, osg::Vec4( 0, 0, 0, 0 ) );
mat->setDiffuse( osg::Material::FRONT_AND_BACK, osg::Vec4( 0, 0, 0, 0 ) );
mat->setAmbient( osg::Material::FRONT_AND_BACK, osg::Vec4( 0, 0, 0, 0 ) );
geode->getOrCreateStateSet()->setAttribute( mat );
return geode;
}
SIMVIS_API osg::ref_ptr< osg::Geode > read_vtp( const path& filename )
{
prop_node root_pn = load_xml( filename );
prop_node& poly_pn = root_pn[ "VTKFile" ][ "PolyData" ][ "Piece" ];
auto point_count = poly_pn.get< int >( "NumberOfPoints");
auto poly_count = poly_pn.get< int >( "NumberOfPolys" );
// create normal and vertex array
osg::ref_ptr<osg::Vec3Array> normals = new osg::Vec3Array( point_count );
osg::Vec3Array* vertices = new osg::Vec3Array( point_count );
auto normal_vec = str_to_vec< float >( poly_pn[ "PointData" ][ "DataArray" ].get_value(), point_count * 3 );
auto point_vec = str_to_vec< float >( poly_pn[ "Points" ][ "DataArray" ].get_value(), point_count * 3 );
xo_assert( normal_vec.size() == point_count * 3 && point_vec.size() == point_count * 3 );
size_t vec_idx = 0;
for ( int idx = 0; idx < point_count; ++idx )
{
normals->at( idx ).set( normal_vec[ vec_idx ], normal_vec[ vec_idx + 1 ], normal_vec[ vec_idx + 2] );
vertices->at( idx ).set( point_vec[ vec_idx ], point_vec[ vec_idx + 1 ], point_vec[ vec_idx + 2] );
vec_idx += 3;
}
osg::ref_ptr< osg::DrawElementsUShort > trianglePrimitives = new osg::DrawElementsUShort( GL_TRIANGLES );
osg::ref_ptr< osg::DrawElementsUShort > quadPrimitives = new osg::DrawElementsUShort( GL_QUADS );
{
auto con_vec = str_to_vec< int >( poly_pn[ "Polys" ][ 0 ].get_value(), no_index );
auto ofs_vec = str_to_vec< int >( poly_pn[ "Polys" ][ 1 ].get_value(), no_index );
for ( size_t idx = 0; idx < ofs_vec.size(); ++idx )
{
auto end_ofs = ofs_vec[ idx ];
auto begin_ofs = idx == 0 ? unsigned short( 0 ) : ofs_vec[ idx - 1 ];
auto num_ver = end_ofs - begin_ofs;
if ( num_ver == 3 )
{
trianglePrimitives->push_back( (unsigned short) con_vec[begin_ofs] );
trianglePrimitives->push_back( (unsigned short) con_vec[begin_ofs + 1] );
trianglePrimitives->push_back( (unsigned short) con_vec[begin_ofs + 2] );
}
else if ( num_ver == 4 )
{
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs] );
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs + 1] );
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs + 2] );
quadPrimitives->push_back( (unsigned short) con_vec[begin_ofs + 3] );
}
else
{
// silently ignore...
//xo::log::warning( "Unknown primitive type, number of vertices = ", num_ver );
}
}
}
// add primitives
osg::Geometry* polyGeom = new osg::Geometry;
if ( trianglePrimitives->size() > 0 )
polyGeom->addPrimitiveSet( trianglePrimitives );
if ( quadPrimitives->size() > 0 )
polyGeom->addPrimitiveSet( quadPrimitives );
// create color array (shared)
//osg::ref_ptr<osg::Vec4Array> shared_colors = new osg::Vec4Array;
//shared_colors->push_back(osg::Vec4(1.0f,0.0f,0.0f,1.0f));
//polyGeom->setColorArray( shared_colors.get(), osg::Array::BIND_OVERALL );
// pass the created vertex array to the points geometry object
polyGeom->setVertexArray( vertices );
polyGeom->setNormalArray( normals, osg::Array::BIND_PER_VERTEX );
polyGeom->setCullingActive( true );
// add the points geometry to the geode.
osg::ref_ptr< osg::Geode > geode = new osg::Geode;
geode->addDrawable(polyGeom);
geode->getOrCreateStateSet()->setMode( GL_CULL_FACE, osg::StateAttribute::ON );
return geode;
}
void set_shadow_mask( osg::Node* n, bool receive, bool cast )
{
n->setNodeMask( receive ? n->getNodeMask() | OsgReceiveShadowMask : n->getNodeMask() & ~OsgReceiveShadowMask );
n->setNodeMask( cast ? n->getNodeMask() | OsgCastShadowMask : n->getNodeMask() & ~OsgCastShadowMask );
}
}
<|endoftext|> |
<commit_before>#include <cstring>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/test/test_caffe_main.hpp"
namespace caffe {
template <typename Dtype>
class BlobSimpleTest : public ::testing::Test {
protected:
BlobSimpleTest()
: blob_(new Blob<Dtype>()),
blob_preshaped_(new Blob<Dtype>(2, 3, 4, 5)) {}
virtual ~BlobSimpleTest() { delete blob_; delete blob_preshaped_; }
Blob<Dtype>* const blob_;
Blob<Dtype>* const blob_preshaped_;
};
TYPED_TEST_CASE(BlobSimpleTest, TestDtypes);
TYPED_TEST(BlobSimpleTest, TestInitialization) {
EXPECT_TRUE(this->blob_);
EXPECT_TRUE(this->blob_preshaped_);
EXPECT_EQ(this->blob_preshaped_->num(), 2);
EXPECT_EQ(this->blob_preshaped_->channels(), 3);
EXPECT_EQ(this->blob_preshaped_->height(), 4);
EXPECT_EQ(this->blob_preshaped_->width(), 5);
EXPECT_EQ(this->blob_preshaped_->count(), 120);
EXPECT_EQ(this->blob_->num(), 0);
EXPECT_EQ(this->blob_->channels(), 0);
EXPECT_EQ(this->blob_->height(), 0);
EXPECT_EQ(this->blob_->width(), 0);
EXPECT_EQ(this->blob_->count(), 0);
}
TYPED_TEST(BlobSimpleTest, TestPointersCPUGPU) {
EXPECT_TRUE(this->blob_preshaped_->gpu_data());
EXPECT_TRUE(this->blob_preshaped_->cpu_data());
EXPECT_TRUE(this->blob_preshaped_->mutable_gpu_data());
EXPECT_TRUE(this->blob_preshaped_->mutable_cpu_data());
}
TYPED_TEST(BlobSimpleTest, TestReshape) {
this->blob_->Reshape(2, 3, 4, 5);
EXPECT_EQ(this->blob_->num(), 2);
EXPECT_EQ(this->blob_->channels(), 3);
EXPECT_EQ(this->blob_->height(), 4);
EXPECT_EQ(this->blob_->width(), 5);
EXPECT_EQ(this->blob_->count(), 120);
}
} // namespace caffe
<commit_msg>Add BlobMathTest with unit tests for sumsq and asum<commit_after>#include <cstring>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/test/test_caffe_main.hpp"
namespace caffe {
template <typename Dtype>
class BlobSimpleTest : public ::testing::Test {
protected:
BlobSimpleTest()
: blob_(new Blob<Dtype>()),
blob_preshaped_(new Blob<Dtype>(2, 3, 4, 5)) {}
virtual ~BlobSimpleTest() { delete blob_; delete blob_preshaped_; }
Blob<Dtype>* const blob_;
Blob<Dtype>* const blob_preshaped_;
};
TYPED_TEST_CASE(BlobSimpleTest, TestDtypes);
TYPED_TEST(BlobSimpleTest, TestInitialization) {
EXPECT_TRUE(this->blob_);
EXPECT_TRUE(this->blob_preshaped_);
EXPECT_EQ(this->blob_preshaped_->num(), 2);
EXPECT_EQ(this->blob_preshaped_->channels(), 3);
EXPECT_EQ(this->blob_preshaped_->height(), 4);
EXPECT_EQ(this->blob_preshaped_->width(), 5);
EXPECT_EQ(this->blob_preshaped_->count(), 120);
EXPECT_EQ(this->blob_->num(), 0);
EXPECT_EQ(this->blob_->channels(), 0);
EXPECT_EQ(this->blob_->height(), 0);
EXPECT_EQ(this->blob_->width(), 0);
EXPECT_EQ(this->blob_->count(), 0);
}
TYPED_TEST(BlobSimpleTest, TestPointersCPUGPU) {
EXPECT_TRUE(this->blob_preshaped_->gpu_data());
EXPECT_TRUE(this->blob_preshaped_->cpu_data());
EXPECT_TRUE(this->blob_preshaped_->mutable_gpu_data());
EXPECT_TRUE(this->blob_preshaped_->mutable_cpu_data());
}
TYPED_TEST(BlobSimpleTest, TestReshape) {
this->blob_->Reshape(2, 3, 4, 5);
EXPECT_EQ(this->blob_->num(), 2);
EXPECT_EQ(this->blob_->channels(), 3);
EXPECT_EQ(this->blob_->height(), 4);
EXPECT_EQ(this->blob_->width(), 5);
EXPECT_EQ(this->blob_->count(), 120);
}
template <typename TypeParam>
class BlobMathTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
BlobMathTest()
: blob_(new Blob<Dtype>(2, 3, 4, 5)) {}
virtual ~BlobMathTest() { delete blob_; }
Blob<Dtype>* const blob_;
};
TYPED_TEST_CASE(BlobMathTest, TestDtypesAndDevices);
TYPED_TEST(BlobMathTest, TestSumOfSquares) {
typedef typename TypeParam::Dtype Dtype;
// Uninitialized Blob should have sum of squares == 0.
EXPECT_EQ(0, this->blob_->sumsq_data());
EXPECT_EQ(0, this->blob_->sumsq_diff());
FillerParameter filler_param;
filler_param.set_min(-3);
filler_param.set_max(3);
UniformFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_);
Dtype expected_sumsq = 0;
const Dtype* data = this->blob_->cpu_data();
for (int i = 0; i < this->blob_->count(); ++i) {
expected_sumsq += data[i] * data[i];
}
// Do a mutable access on the current device,
// so that the sumsq computation is done on that device.
// (Otherwise, this would only check the CPU sumsq implementation.)
switch (TypeParam::device) {
case Caffe::CPU:
this->blob_->mutable_cpu_data();
break;
case Caffe::GPU:
this->blob_->mutable_gpu_data();
break;
default:
LOG(FATAL) << "Unknown device: " << TypeParam::device;
}
EXPECT_FLOAT_EQ(expected_sumsq, this->blob_->sumsq_data());
EXPECT_EQ(0, this->blob_->sumsq_diff());
// Check sumsq_diff too.
const Dtype kDiffScaleFactor = 7;
caffe_cpu_scale(this->blob_->count(), kDiffScaleFactor, data,
this->blob_->mutable_cpu_diff());
switch (TypeParam::device) {
case Caffe::CPU:
this->blob_->mutable_cpu_diff();
break;
case Caffe::GPU:
this->blob_->mutable_gpu_diff();
break;
default:
LOG(FATAL) << "Unknown device: " << TypeParam::device;
}
EXPECT_FLOAT_EQ(expected_sumsq, this->blob_->sumsq_data());
EXPECT_FLOAT_EQ(expected_sumsq * kDiffScaleFactor * kDiffScaleFactor,
this->blob_->sumsq_diff());
}
TYPED_TEST(BlobMathTest, TestAsum) {
typedef typename TypeParam::Dtype Dtype;
// Uninitialized Blob should have sum of squares == 0.
EXPECT_EQ(0, this->blob_->asum_data());
EXPECT_EQ(0, this->blob_->asum_diff());
FillerParameter filler_param;
filler_param.set_min(-3);
filler_param.set_max(3);
UniformFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_);
Dtype expected_asum = 0;
const Dtype* data = this->blob_->cpu_data();
for (int i = 0; i < this->blob_->count(); ++i) {
expected_asum += std::fabs(data[i]);
}
// Do a mutable access on the current device,
// so that the asum computation is done on that device.
// (Otherwise, this would only check the CPU asum implementation.)
switch (TypeParam::device) {
case Caffe::CPU:
this->blob_->mutable_cpu_data();
break;
case Caffe::GPU:
this->blob_->mutable_gpu_data();
break;
default:
LOG(FATAL) << "Unknown device: " << TypeParam::device;
}
EXPECT_FLOAT_EQ(expected_asum, this->blob_->asum_data());
EXPECT_EQ(0, this->blob_->asum_diff());
// Check asum_diff too.
const Dtype kDiffScaleFactor = 7;
caffe_cpu_scale(this->blob_->count(), kDiffScaleFactor, data,
this->blob_->mutable_cpu_diff());
switch (TypeParam::device) {
case Caffe::CPU:
this->blob_->mutable_cpu_diff();
break;
case Caffe::GPU:
this->blob_->mutable_gpu_diff();
break;
default:
LOG(FATAL) << "Unknown device: " << TypeParam::device;
}
EXPECT_FLOAT_EQ(expected_asum, this->blob_->asum_data());
EXPECT_FLOAT_EQ(expected_asum * kDiffScaleFactor, this->blob_->asum_diff());
}
} // namespace caffe
<|endoftext|> |
<commit_before>//===----- lib/Support/Error.cpp - Error and associated utilities ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Error.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include <system_error>
using namespace llvm;
namespace {
enum class ErrorErrorCode : int {
MultipleErrors = 1,
InconvertibleError
};
// FIXME: This class is only here to support the transition to llvm::Error. It
// will be removed once this transition is complete. Clients should prefer to
// deal with the Error value directly, rather than converting to error_code.
class ErrorErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "Error"; }
std::string message(int condition) const override {
switch (static_cast<ErrorErrorCode>(condition)) {
case ErrorErrorCode::MultipleErrors:
return "Multiple errors";
case ErrorErrorCode::InconvertibleError:
return "Inconvertible error value. An error has occurred that could "
"not be converted to a known std::error_code. Please file a "
"bug.";
}
llvm_unreachable("Unhandled error code");
}
};
}
static ManagedStatic<ErrorErrorCategory> ErrorErrorCat;
namespace llvm {
void ErrorInfoBase::anchor() {}
char ErrorInfoBase::ID = 0;
char ErrorList::ID = 0;
char ECError::ID = 0;
char StringError::ID = 0;
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) {
if (!E)
return;
OS << ErrorBanner;
handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
EI.log(OS);
OS << "\n";
});
}
std::error_code ErrorList::convertToErrorCode() const {
return std::error_code(static_cast<int>(ErrorErrorCode::MultipleErrors),
*ErrorErrorCat);
}
std::error_code inconvertibleErrorCode() {
return std::error_code(static_cast<int>(ErrorErrorCode::InconvertibleError),
*ErrorErrorCat);
}
Error errorCodeToError(std::error_code EC) {
if (!EC)
return Error::success();
return Error(llvm::make_unique<ECError>(ECError(EC)));
}
std::error_code errorToErrorCode(Error Err) {
std::error_code EC;
handleAllErrors(std::move(Err), [&](const ErrorInfoBase &EI) {
EC = EI.convertToErrorCode();
});
if (EC == inconvertibleErrorCode())
report_fatal_error(EC.message());
return EC;
}
StringError::StringError(const Twine &S, std::error_code EC)
: Msg(S.str()), EC(EC) {}
void StringError::log(raw_ostream &OS) const { OS << Msg; }
std::error_code StringError::convertToErrorCode() const {
return EC;
}
void report_fatal_error(Error Err, bool GenCrashDiag) {
assert(Err && "report_fatal_error called with success value");
std::string ErrMsg;
{
raw_string_ostream ErrStream(ErrMsg);
logAllUnhandledErrors(std::move(Err), ErrStream, "");
}
report_fatal_error(ErrMsg);
}
}
#ifndef _MSC_VER
namespace llvm {
// One of these two variables will be referenced by a symbol defined in
// llvm-config.h. We provide a link-time (or load time for DSO) failure when
// there is a mismatch in the build configuration of the API client and LLVM.
#if LLVM_ENABLE_ABI_BREAKING_CHECKS
int EnableABIBreakingChecks;
#else
int DisableABIBreakingChecks;
#endif
} // end namespace llvm
#endif<commit_msg>Fix a linefeed at eof.<commit_after>//===----- lib/Support/Error.cpp - Error and associated utilities ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Error.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include <system_error>
using namespace llvm;
namespace {
enum class ErrorErrorCode : int {
MultipleErrors = 1,
InconvertibleError
};
// FIXME: This class is only here to support the transition to llvm::Error. It
// will be removed once this transition is complete. Clients should prefer to
// deal with the Error value directly, rather than converting to error_code.
class ErrorErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "Error"; }
std::string message(int condition) const override {
switch (static_cast<ErrorErrorCode>(condition)) {
case ErrorErrorCode::MultipleErrors:
return "Multiple errors";
case ErrorErrorCode::InconvertibleError:
return "Inconvertible error value. An error has occurred that could "
"not be converted to a known std::error_code. Please file a "
"bug.";
}
llvm_unreachable("Unhandled error code");
}
};
}
static ManagedStatic<ErrorErrorCategory> ErrorErrorCat;
namespace llvm {
void ErrorInfoBase::anchor() {}
char ErrorInfoBase::ID = 0;
char ErrorList::ID = 0;
char ECError::ID = 0;
char StringError::ID = 0;
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) {
if (!E)
return;
OS << ErrorBanner;
handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
EI.log(OS);
OS << "\n";
});
}
std::error_code ErrorList::convertToErrorCode() const {
return std::error_code(static_cast<int>(ErrorErrorCode::MultipleErrors),
*ErrorErrorCat);
}
std::error_code inconvertibleErrorCode() {
return std::error_code(static_cast<int>(ErrorErrorCode::InconvertibleError),
*ErrorErrorCat);
}
Error errorCodeToError(std::error_code EC) {
if (!EC)
return Error::success();
return Error(llvm::make_unique<ECError>(ECError(EC)));
}
std::error_code errorToErrorCode(Error Err) {
std::error_code EC;
handleAllErrors(std::move(Err), [&](const ErrorInfoBase &EI) {
EC = EI.convertToErrorCode();
});
if (EC == inconvertibleErrorCode())
report_fatal_error(EC.message());
return EC;
}
StringError::StringError(const Twine &S, std::error_code EC)
: Msg(S.str()), EC(EC) {}
void StringError::log(raw_ostream &OS) const { OS << Msg; }
std::error_code StringError::convertToErrorCode() const {
return EC;
}
void report_fatal_error(Error Err, bool GenCrashDiag) {
assert(Err && "report_fatal_error called with success value");
std::string ErrMsg;
{
raw_string_ostream ErrStream(ErrMsg);
logAllUnhandledErrors(std::move(Err), ErrStream, "");
}
report_fatal_error(ErrMsg);
}
}
#ifndef _MSC_VER
namespace llvm {
// One of these two variables will be referenced by a symbol defined in
// llvm-config.h. We provide a link-time (or load time for DSO) failure when
// there is a mismatch in the build configuration of the API client and LLVM.
#if LLVM_ENABLE_ABI_BREAKING_CHECKS
int EnableABIBreakingChecks;
#else
int DisableABIBreakingChecks;
#endif
} // end namespace llvm
#endif
<|endoftext|> |
<commit_before>//===-- Module.cpp - Implement the Module class ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Module class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/InstrTypes.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/TypeSymbolTable.h"
#include <algorithm>
#include <cstdarg>
#include <cstdlib>
#include <map>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Methods to implement the globals and functions lists.
//
Function *ilist_traits<Function>::createSentinel() {
FunctionType *FTy =
FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
GlobalAlias *Ret = new GlobalAlias(Type::Int32Ty,
GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
iplist<Function> &ilist_traits<Function>::getList(Module *M) {
return M->getFunctionList();
}
iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
return M->getGlobalList();
}
iplist<GlobalAlias> &ilist_traits<GlobalAlias>::getList(Module *M) {
return M->getAliasList();
}
// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file.
template class SymbolTableListTraits<GlobalVariable, Module>;
template class SymbolTableListTraits<Function, Module>;
template class SymbolTableListTraits<GlobalAlias, Module>;
//===----------------------------------------------------------------------===//
// Primitive Module methods.
//
Module::Module(const std::string &MID)
: ModuleID(MID), DataLayout("") {
ValSymTab = new ValueSymbolTable();
TypeSymTab = new TypeSymbolTable();
}
Module::~Module() {
dropAllReferences();
GlobalList.clear();
FunctionList.clear();
AliasList.clear();
LibraryList.clear();
delete ValSymTab;
delete TypeSymTab;
}
// Module::dump() - Allow printing from debugger
void Module::dump() const {
print(*cerr.stream());
}
/// Target endian information...
Module::Endianness Module::getEndianness() const {
std::string temp = DataLayout;
Module::Endianness ret = AnyEndianness;
while (!temp.empty()) {
std::string token = getToken(temp, "-");
if (token[0] == 'e') {
ret = LittleEndian;
} else if (token[0] == 'E') {
ret = BigEndian;
}
}
return ret;
}
/// Target Pointer Size information...
Module::PointerSize Module::getPointerSize() const {
std::string temp = DataLayout;
Module::PointerSize ret = AnyPointerSize;
while (!temp.empty()) {
std::string token = getToken(temp, "-");
char signal = getToken(token, ":")[0];
if (signal == 'p') {
int size = atoi(getToken(token, ":").c_str());
if (size == 32)
ret = Pointer32;
else if (size == 64)
ret = Pointer64;
}
}
return ret;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the functions in the module.
//
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return
// it. This is nice because it allows most passes to get away with not handling
// the symbol table directly for this common task.
//
Constant *Module::getOrInsertFunction(const std::string &Name,
const FunctionType *Ty) {
ValueSymbolTable &SymTab = getValueSymbolTable();
// See if we have a definition for the specified function already.
GlobalValue *F = dyn_cast_or_null<GlobalValue>(SymTab.lookup(Name));
if (F == 0) {
// Nope, add it
Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
FunctionList.push_back(New);
return New; // Return the new prototype.
}
// Okay, the function exists. Does it have externally visible linkage?
if (F->hasInternalLinkage()) {
// Rename the function.
F->setName(SymTab.getUniqueName(F->getName()));
// Retry, now there won't be a conflict.
return getOrInsertFunction(Name, Ty);
}
// If the function exists but has the wrong type, return a bitcast to the
// right type.
if (F->getType() != PointerType::getUnqual(Ty))
return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
// Otherwise, we just found the existing function or a prototype.
return F;
}
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return it.
// This version of the method takes a null terminated list of function
// arguments, which makes it easier for clients to use.
//
Constant *Module::getOrInsertFunction(const std::string &Name,
const Type *RetTy, ...) {
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<const Type*> ArgTys;
while (const Type *ArgTy = va_arg(Args, const Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
}
// getFunction - Look up the specified function in the module symbol table.
// If it does not exist, return null.
//
Function *Module::getFunction(const std::string &Name) const {
const ValueSymbolTable &SymTab = getValueSymbolTable();
return dyn_cast_or_null<Function>(SymTab.lookup(Name));
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
/// getGlobalVariable - Look up the specified global variable in the module
/// symbol table. If it does not exist, return null. The type argument
/// should be the underlying type of the global, i.e., it should not have
/// the top-level PointerType, which represents the address of the global.
/// If AllowInternal is set to true, this function will return types that
/// have InternalLinkage. By default, these types are not returned.
///
GlobalVariable *Module::getGlobalVariable(const std::string &Name,
bool AllowInternal) const {
if (Value *V = ValSymTab->lookup(Name)) {
GlobalVariable *Result = dyn_cast<GlobalVariable>(V);
if (Result && (AllowInternal || !Result->hasInternalLinkage()))
return Result;
}
return 0;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
// getNamedAlias - Look up the specified global in the module symbol table.
// If it does not exist, return null.
//
GlobalAlias *Module::getNamedAlias(const std::string &Name) const {
const ValueSymbolTable &SymTab = getValueSymbolTable();
return dyn_cast_or_null<GlobalAlias>(SymTab.lookup(Name));
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the types in the module.
//
// addTypeName - Insert an entry in the symbol table mapping Str to Type. If
// there is already an entry for this name, true is returned and the symbol
// table is not modified.
//
bool Module::addTypeName(const std::string &Name, const Type *Ty) {
TypeSymbolTable &ST = getTypeSymbolTable();
if (ST.lookup(Name)) return true; // Already in symtab...
// Not in symbol table? Set the name with the Symtab as an argument so the
// type knows what to update...
ST.insert(Name, Ty);
return false;
}
/// getTypeByName - Return the type with the specified name in this module, or
/// null if there is none by that name.
const Type *Module::getTypeByName(const std::string &Name) const {
const TypeSymbolTable &ST = getTypeSymbolTable();
return cast_or_null<Type>(ST.lookup(Name));
}
// getTypeName - If there is at least one entry in the symbol table for the
// specified type, return it.
//
std::string Module::getTypeName(const Type *Ty) const {
const TypeSymbolTable &ST = getTypeSymbolTable();
TypeSymbolTable::const_iterator TI = ST.begin();
TypeSymbolTable::const_iterator TE = ST.end();
if ( TI == TE ) return ""; // No names for types
while (TI != TE && TI->second != Ty)
++TI;
if (TI != TE) // Must have found an entry!
return TI->first;
return ""; // Must not have found anything...
}
//===----------------------------------------------------------------------===//
// Other module related stuff.
//
// dropAllReferences() - This function causes all the subelementss to "let go"
// of all references that they are maintaining. This allows one to 'delete' a
// whole module at a time, even though there may be circular references... first
// all references are dropped, and all use counts go to zero. Then everything
// is deleted for real. Note that no operations are valid on an object that
// has "dropped all references", except operator delete.
//
void Module::dropAllReferences() {
for(Module::iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
I->dropAllReferences();
for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
I->dropAllReferences();
}
void Module::addLibrary(const std::string& Lib) {
for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
if (*I == Lib)
return;
LibraryList.push_back(Lib);
}
void Module::removeLibrary(const std::string& Lib) {
LibraryListType::iterator I = LibraryList.begin();
LibraryListType::iterator E = LibraryList.end();
for (;I != E; ++I)
if (*I == Lib) {
LibraryList.erase(I);
return;
}
}
<commit_msg>Remove an unnecessary #include<commit_after>//===-- Module.cpp - Implement the Module class ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Module class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/InstrTypes.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/TypeSymbolTable.h"
#include <algorithm>
#include <cstdarg>
#include <cstdlib>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Methods to implement the globals and functions lists.
//
Function *ilist_traits<Function>::createSentinel() {
FunctionType *FTy =
FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
GlobalVariable *Ret = new GlobalVariable(Type::Int32Ty, false,
GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
GlobalAlias *Ret = new GlobalAlias(Type::Int32Ty,
GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
iplist<Function> &ilist_traits<Function>::getList(Module *M) {
return M->getFunctionList();
}
iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
return M->getGlobalList();
}
iplist<GlobalAlias> &ilist_traits<GlobalAlias>::getList(Module *M) {
return M->getAliasList();
}
// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file.
template class SymbolTableListTraits<GlobalVariable, Module>;
template class SymbolTableListTraits<Function, Module>;
template class SymbolTableListTraits<GlobalAlias, Module>;
//===----------------------------------------------------------------------===//
// Primitive Module methods.
//
Module::Module(const std::string &MID)
: ModuleID(MID), DataLayout("") {
ValSymTab = new ValueSymbolTable();
TypeSymTab = new TypeSymbolTable();
}
Module::~Module() {
dropAllReferences();
GlobalList.clear();
FunctionList.clear();
AliasList.clear();
LibraryList.clear();
delete ValSymTab;
delete TypeSymTab;
}
// Module::dump() - Allow printing from debugger
void Module::dump() const {
print(*cerr.stream());
}
/// Target endian information...
Module::Endianness Module::getEndianness() const {
std::string temp = DataLayout;
Module::Endianness ret = AnyEndianness;
while (!temp.empty()) {
std::string token = getToken(temp, "-");
if (token[0] == 'e') {
ret = LittleEndian;
} else if (token[0] == 'E') {
ret = BigEndian;
}
}
return ret;
}
/// Target Pointer Size information...
Module::PointerSize Module::getPointerSize() const {
std::string temp = DataLayout;
Module::PointerSize ret = AnyPointerSize;
while (!temp.empty()) {
std::string token = getToken(temp, "-");
char signal = getToken(token, ":")[0];
if (signal == 'p') {
int size = atoi(getToken(token, ":").c_str());
if (size == 32)
ret = Pointer32;
else if (size == 64)
ret = Pointer64;
}
}
return ret;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the functions in the module.
//
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return
// it. This is nice because it allows most passes to get away with not handling
// the symbol table directly for this common task.
//
Constant *Module::getOrInsertFunction(const std::string &Name,
const FunctionType *Ty) {
ValueSymbolTable &SymTab = getValueSymbolTable();
// See if we have a definition for the specified function already.
GlobalValue *F = dyn_cast_or_null<GlobalValue>(SymTab.lookup(Name));
if (F == 0) {
// Nope, add it
Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
FunctionList.push_back(New);
return New; // Return the new prototype.
}
// Okay, the function exists. Does it have externally visible linkage?
if (F->hasInternalLinkage()) {
// Rename the function.
F->setName(SymTab.getUniqueName(F->getName()));
// Retry, now there won't be a conflict.
return getOrInsertFunction(Name, Ty);
}
// If the function exists but has the wrong type, return a bitcast to the
// right type.
if (F->getType() != PointerType::getUnqual(Ty))
return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
// Otherwise, we just found the existing function or a prototype.
return F;
}
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return it.
// This version of the method takes a null terminated list of function
// arguments, which makes it easier for clients to use.
//
Constant *Module::getOrInsertFunction(const std::string &Name,
const Type *RetTy, ...) {
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<const Type*> ArgTys;
while (const Type *ArgTy = va_arg(Args, const Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
}
// getFunction - Look up the specified function in the module symbol table.
// If it does not exist, return null.
//
Function *Module::getFunction(const std::string &Name) const {
const ValueSymbolTable &SymTab = getValueSymbolTable();
return dyn_cast_or_null<Function>(SymTab.lookup(Name));
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
/// getGlobalVariable - Look up the specified global variable in the module
/// symbol table. If it does not exist, return null. The type argument
/// should be the underlying type of the global, i.e., it should not have
/// the top-level PointerType, which represents the address of the global.
/// If AllowInternal is set to true, this function will return types that
/// have InternalLinkage. By default, these types are not returned.
///
GlobalVariable *Module::getGlobalVariable(const std::string &Name,
bool AllowInternal) const {
if (Value *V = ValSymTab->lookup(Name)) {
GlobalVariable *Result = dyn_cast<GlobalVariable>(V);
if (Result && (AllowInternal || !Result->hasInternalLinkage()))
return Result;
}
return 0;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
// getNamedAlias - Look up the specified global in the module symbol table.
// If it does not exist, return null.
//
GlobalAlias *Module::getNamedAlias(const std::string &Name) const {
const ValueSymbolTable &SymTab = getValueSymbolTable();
return dyn_cast_or_null<GlobalAlias>(SymTab.lookup(Name));
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the types in the module.
//
// addTypeName - Insert an entry in the symbol table mapping Str to Type. If
// there is already an entry for this name, true is returned and the symbol
// table is not modified.
//
bool Module::addTypeName(const std::string &Name, const Type *Ty) {
TypeSymbolTable &ST = getTypeSymbolTable();
if (ST.lookup(Name)) return true; // Already in symtab...
// Not in symbol table? Set the name with the Symtab as an argument so the
// type knows what to update...
ST.insert(Name, Ty);
return false;
}
/// getTypeByName - Return the type with the specified name in this module, or
/// null if there is none by that name.
const Type *Module::getTypeByName(const std::string &Name) const {
const TypeSymbolTable &ST = getTypeSymbolTable();
return cast_or_null<Type>(ST.lookup(Name));
}
// getTypeName - If there is at least one entry in the symbol table for the
// specified type, return it.
//
std::string Module::getTypeName(const Type *Ty) const {
const TypeSymbolTable &ST = getTypeSymbolTable();
TypeSymbolTable::const_iterator TI = ST.begin();
TypeSymbolTable::const_iterator TE = ST.end();
if ( TI == TE ) return ""; // No names for types
while (TI != TE && TI->second != Ty)
++TI;
if (TI != TE) // Must have found an entry!
return TI->first;
return ""; // Must not have found anything...
}
//===----------------------------------------------------------------------===//
// Other module related stuff.
//
// dropAllReferences() - This function causes all the subelementss to "let go"
// of all references that they are maintaining. This allows one to 'delete' a
// whole module at a time, even though there may be circular references... first
// all references are dropped, and all use counts go to zero. Then everything
// is deleted for real. Note that no operations are valid on an object that
// has "dropped all references", except operator delete.
//
void Module::dropAllReferences() {
for(Module::iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
I->dropAllReferences();
for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
I->dropAllReferences();
}
void Module::addLibrary(const std::string& Lib) {
for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
if (*I == Lib)
return;
LibraryList.push_back(Lib);
}
void Module::removeLibrary(const std::string& Lib) {
LibraryListType::iterator I = LibraryList.begin();
LibraryListType::iterator E = LibraryList.end();
for (;I != E; ++I)
if (*I == Lib) {
LibraryList.erase(I);
return;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediator.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 19:54:22 $
*
* 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 _MEDIATOR_HXX
#define _MEDIATOR_HXX
#include <string.h>
#include <stdarg.h>
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _VOS_PIPE_HXX_
#include <vos/pipe.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _VOS_CONDITN_HXX_
#include <vos/conditn.hxx>
#endif
#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif
struct MediatorMessage
{
ULONG m_nID;
ULONG m_nBytes;
char* m_pBytes;
char* m_pRun;
MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ),
m_pBytes( NULL ), m_pRun( NULL ) {}
MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) :
m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL )
{
m_pBytes = new char[ m_nBytes ];
memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
}
~MediatorMessage()
{
if( m_pBytes )
delete [] m_pBytes;
}
void Set( ULONG nBytes, char* pBytes )
{
if( m_pBytes )
delete [] m_pBytes;
m_nBytes = nBytes;
m_pBytes = new char[ m_nBytes ];
memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
}
ULONG ExtractULONG();
char* GetString();
UINT32 GetUINT32();
void* GetBytes( ULONG& );
void* GetBytes() { ULONG nBytes; return GetBytes( nBytes ); }
void Rewind() { m_pRun = NULL; }
};
DECLARE_LIST( MediatorMessageList, MediatorMessage* );
class MediatorListener;
class Mediator
{
friend class MediatorListener;
protected:
int m_nSocket;
MediatorMessageList m_aMessageQueue;
NAMESPACE_VOS(OMutex) m_aQueueMutex;
NAMESPACE_VOS(OMutex) m_aSendMutex;
// only one thread can send a message at any given time
NAMESPACE_VOS(OCondition) m_aNewMessageCdtn;
MediatorListener* m_pListener;
// thread to fill the queue
ULONG m_nCurrentID;
// will be constantly increased with each message sent
bool m_bValid;
Link m_aConnectionLostHdl;
Link m_aNewMessageHdl;
public:
Mediator( int nSocket );
~Mediator();
// mark mediator as invalid. No more messages will be processed,
// SendMessage, WaitForMessage, TransactMessage will return immediatly
// with error
void invalidate() { m_bValid = false; }
ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 );
ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 )
{
return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID );
}
BOOL WaitForMessage( ULONG nTimeOut = 5000 );
// timeout in ms
// TRUE: Message came in
// FALSE: timed out
// if timeout is set, WaitForMessage will wait even if there are messages
// in the queue
virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
// wait for an answer message ( ID >= 1 << 24 )
// the message will be removed from the queue and returned
MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes );
// sends a message and waits for an answer
MediatorMessage* GetNextMessage( BOOL bWait = FALSE );
Link SetConnectionLostHdl( const Link& rLink )
{
Link aRet = m_aConnectionLostHdl;
m_aConnectionLostHdl = rLink;
return aRet;
}
Link SetNewMessageHdl( const Link& rLink )
{
Link aRet = m_aNewMessageHdl;
m_aNewMessageHdl = rLink;
return aRet;
}
};
class MediatorListener : public NAMESPACE_VOS( OThread )
{
friend class Mediator;
private:
Mediator* m_pMediator;
::vos::OMutex m_aMutex;
MediatorListener( Mediator* );
~MediatorListener();
virtual void run();
virtual void onTerminated();
};
inline void medDebug( int condition, const char* pFormat, ... )
{
#if OSL_DEBUG_LEVEL > 1
if( condition )
{
va_list ap;
va_start( ap, pFormat );
vfprintf( stderr, pFormat, ap );
va_end( ap );
}
#endif
}
#endif // _MEDIATOR_HXX
<commit_msg>INTEGRATION: CWS wae4extensions (1.6.386); FILE MERGED 2007/10/01 11:10:45 fs 1.6.386.2: #i81612# warning-free code (unxsoli4) 2007/09/27 12:18:49 fs 1.6.386.1: #i81612# warning-free on unxlngi6/.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mediator.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2008-01-14 14:52:33 $
*
* 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 _MEDIATOR_HXX
#define _MEDIATOR_HXX
#include <string.h>
#include <stdarg.h>
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _VOS_PIPE_HXX_
#include <vos/pipe.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _VOS_CONDITN_HXX_
#include <vos/conditn.hxx>
#endif
#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif
struct MediatorMessage
{
ULONG m_nID;
ULONG m_nBytes;
char* m_pBytes;
char* m_pRun;
MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ),
m_pBytes( NULL ), m_pRun( NULL ) {}
MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) :
m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL )
{
m_pBytes = new char[ m_nBytes ];
memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
}
~MediatorMessage()
{
if( m_pBytes )
delete [] m_pBytes;
}
void Set( ULONG nBytes, char* pBytes )
{
if( m_pBytes )
delete [] m_pBytes;
m_nBytes = nBytes;
m_pBytes = new char[ m_nBytes ];
memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
}
ULONG ExtractULONG();
char* GetString();
UINT32 GetUINT32();
void* GetBytes( ULONG& );
void* GetBytes() { ULONG nBytes; return GetBytes( nBytes ); }
void Rewind() { m_pRun = NULL; }
};
DECLARE_LIST( MediatorMessageList, MediatorMessage* )
class MediatorListener;
class Mediator
{
friend class MediatorListener;
protected:
int m_nSocket;
MediatorMessageList m_aMessageQueue;
NAMESPACE_VOS(OMutex) m_aQueueMutex;
NAMESPACE_VOS(OMutex) m_aSendMutex;
// only one thread can send a message at any given time
NAMESPACE_VOS(OCondition) m_aNewMessageCdtn;
MediatorListener* m_pListener;
// thread to fill the queue
ULONG m_nCurrentID;
// will be constantly increased with each message sent
bool m_bValid;
Link m_aConnectionLostHdl;
Link m_aNewMessageHdl;
public:
Mediator( int nSocket );
~Mediator();
// mark mediator as invalid. No more messages will be processed,
// SendMessage, WaitForMessage, TransactMessage will return immediatly
// with error
void invalidate() { m_bValid = false; }
ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 );
ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 )
{
return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID );
}
BOOL WaitForMessage( ULONG nTimeOut = 5000 );
// timeout in ms
// TRUE: Message came in
// FALSE: timed out
// if timeout is set, WaitForMessage will wait even if there are messages
// in the queue
virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
// wait for an answer message ( ID >= 1 << 24 )
// the message will be removed from the queue and returned
MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes );
// sends a message and waits for an answer
MediatorMessage* GetNextMessage( BOOL bWait = FALSE );
Link SetConnectionLostHdl( const Link& rLink )
{
Link aRet = m_aConnectionLostHdl;
m_aConnectionLostHdl = rLink;
return aRet;
}
Link SetNewMessageHdl( const Link& rLink )
{
Link aRet = m_aNewMessageHdl;
m_aNewMessageHdl = rLink;
return aRet;
}
};
class MediatorListener : public NAMESPACE_VOS( OThread )
{
friend class Mediator;
private:
Mediator* m_pMediator;
::vos::OMutex m_aMutex;
MediatorListener( Mediator* );
~MediatorListener();
virtual void run();
virtual void onTerminated();
};
inline void medDebug( int condition, const char* pFormat, ... )
{
#if OSL_DEBUG_LEVEL > 1
if( condition )
{
va_list ap;
va_start( ap, pFormat );
vfprintf( stderr, pFormat, ap );
va_end( ap );
}
#else
(void)condition;
(void)pFormat;
#endif
}
#endif // _MEDIATOR_HXX
<|endoftext|> |
<commit_before><commit_msg>Review the BLIS inner kernel<commit_after><|endoftext|> |
<commit_before>/* Copyright 2019-2021 Benjamin Worpitz, Erik Zenker, Sergei Bastrakov
*
* This file exemplifies usage of alpaka.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED “AS IS” AND ISC DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <alpaka/alpaka.hpp>
#include <alpaka/example/ExampleDefaultAcc.hpp>
#include <cstdint>
#include <iostream>
// This example only makes sense with alpaka AccCpuOmp2Blocks backend enabled
// and OpenMP runtime supporting at least 3.0. Disable it for other cases.
#if defined _OPENMP && _OPENMP >= 200805 && ALPAKA_ACC_CPU_B_OMP2_T_SEQ_ENABLED
//! OpenMP schedule demonstration kernel
//!
//! Prints distribution of alpaka thread indices between OpenMP threads.
//! Its operator() is reused in other kernels of this example.
//! Sets no schedule explicitly, so the default is used, controlled by the OMP_SCHEDULE environment variable.
struct OpenMPScheduleDefaultKernel
{
template<typename TAcc>
ALPAKA_FN_ACC auto operator()(TAcc const& acc) const -> void
{
// For simplicity assume 1d index space throughout this example
using Idx = alpaka::Idx<TAcc>;
Idx const globalThreadIdx = alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0];
// Print work distribution between threads for illustration
printf(
"alpaka global thread index %u is processed by OpenMP thread %d\n",
static_cast<std::uint32_t>(globalThreadIdx),
omp_get_thread_num());
}
};
//! Kernel that sets the schedule via a static member.
//! We inherit OpenMPScheduleDefaultKernel just to reuse its operator().
struct OpenMPScheduleMemberKernel : public OpenMPScheduleDefaultKernel
{
//! These two members are only checked for when the OmpSchedule trait is not specialized for this kernel type.
//! OpenMP schedule kind to be used by the AccCpuOmp2Blocks accelerator,
//! has to be static and constexpr.
static constexpr auto ompScheduleKind = alpaka::omp::Schedule::Static;
//! Member to set OpenMP chunk size, can be non-static and non-constexpr.
static constexpr int ompScheduleChunkSize = 1;
};
//! Kernel that sets the schedule via trait specialization.
//! We inherit OpenMPScheduleDefaultKernel just to reuse its operator().
//! The schedule trait specialization is given underneath this struct.
//! It has a higher priority than the internal static member.
struct OpenMPScheduleTraitKernel : public OpenMPScheduleDefaultKernel
{
};
namespace alpaka
{
namespace traits
{
//! Schedule trait specialization for OpenMPScheduleTraitKernel.
//! This is the most general way to define a schedule.
//! In case neither the trait nor the member are provided, alpaka does not set any runtime schedule and the
//! schedule used is defined by omp_set_schedule() called on the user side, or otherwise by the OMP_SCHEDULE
//! environment variable.
template<typename TAcc>
struct OmpSchedule<OpenMPScheduleTraitKernel, TAcc>
{
template<typename TDim, typename... TArgs>
ALPAKA_FN_HOST static auto getOmpSchedule(
OpenMPScheduleTraitKernel const& kernelFnObj,
Vec<TDim, Idx<TAcc>> const& blockThreadExtent,
Vec<TDim, Idx<TAcc>> const& threadElemExtent,
TArgs const&... args) -> alpaka::omp::Schedule
{
// Determine schedule at runtime for the given kernel and run parameters.
// For this particular example kernel, TArgs is an empty pack and can be removed.
alpaka::ignore_unused(kernelFnObj);
alpaka::ignore_unused(blockThreadExtent);
alpaka::ignore_unused(threadElemExtent);
alpaka::ignore_unused(args...);
return alpaka::omp::Schedule{alpaka::omp::Schedule::Dynamic, 2};
}
};
} // namespace traits
} // namespace alpaka
auto main() -> int
{
// Fallback for the CI with disabled sequential backend
# if defined(ALPAKA_CI) && !defined(ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED)
return EXIT_SUCCESS;
# else
using Idx = std::size_t;
// OpenMP schedule illustrated by this example only has effect with
// with the AccCpuOmp2Blocks accelerator.
// This example also assumes 1d for simplicity.
using Acc = alpaka::AccCpuOmp2Blocks<alpaka::DimInt<1>, Idx>;
std::cout << "Using alpaka accelerator: " << alpaka::getAccName<Acc>() << std::endl;
// Defines the synchronization behavior of a queue
using QueueProperty = alpaka::Blocking;
using Queue = alpaka::Queue<Acc, QueueProperty>;
// Select a device
auto const devAcc = alpaka::getDevByIdx<Acc>(0u);
// Create a queue on the device
Queue queue(devAcc);
// Define the work division
Idx const threadsPerGrid = 16u;
Idx const elementsPerThread = 1u;
auto const workDiv = alpaka::getValidWorkDiv<Acc>(
devAcc,
threadsPerGrid,
elementsPerThread,
false,
alpaka::GridBlockExtentSubDivRestrictions::Unrestricted);
// Run the kernel setting no schedule explicitly.
// In this case the schedule is controlled by the OMP_SCHEDULE environment variable.
std::cout << "OpenMPScheduleDefaultKernel setting no schedule explicitly:\n";
alpaka::exec<Acc>(queue, workDiv, OpenMPScheduleDefaultKernel{});
alpaka::wait(queue);
// Run the kernel setting the schedule via a trait
std::cout << "\n\nOpenMPScheduleMemberKernel setting the schedule via a static member:\n";
alpaka::exec<Acc>(queue, workDiv, OpenMPScheduleMemberKernel{});
alpaka::wait(queue);
// Run the kernel setting the schedule via a trait
std::cout << "\n\nOpenMPScheduleTraitKernel setting the schedule via trait:\n";
alpaka::exec<Acc>(queue, workDiv, OpenMPScheduleTraitKernel{});
alpaka::wait(queue);
return EXIT_SUCCESS;
# endif
}
#else
auto main() -> int
{
std::cout << "This example is disabled, as it requires OpenMP runtime version >= 3.0 and alpaka accelerator"
<< " AccCpuOmp2Blocks\n";
return EXIT_SUCCESS;
}
#endif
<commit_msg>example: fix warning (NVCC+OpenMP)<commit_after>/* Copyright 2019-2021 Benjamin Worpitz, Erik Zenker, Sergei Bastrakov
*
* This file exemplifies usage of alpaka.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED “AS IS” AND ISC DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <alpaka/alpaka.hpp>
#include <alpaka/example/ExampleDefaultAcc.hpp>
#include <cstdint>
#include <iostream>
// This example only makes sense with alpaka AccCpuOmp2Blocks backend enabled
// and OpenMP runtime supporting at least 3.0. Disable it for other cases.
#if defined _OPENMP && _OPENMP >= 200805 && ALPAKA_ACC_CPU_B_OMP2_T_SEQ_ENABLED
//! OpenMP schedule demonstration kernel
//!
//! Prints distribution of alpaka thread indices between OpenMP threads.
//! Its operator() is reused in other kernels of this example.
//! Sets no schedule explicitly, so the default is used, controlled by the OMP_SCHEDULE environment variable.
struct OpenMPScheduleDefaultKernel
{
template<typename TAcc>
ALPAKA_FN_HOST auto operator()(TAcc const& acc) const -> void
{
// For simplicity assume 1d index space throughout this example
using Idx = alpaka::Idx<TAcc>;
Idx const globalThreadIdx = alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0];
// Print work distribution between threads for illustration
printf(
"alpaka global thread index %u is processed by OpenMP thread %d\n",
static_cast<std::uint32_t>(globalThreadIdx),
omp_get_thread_num());
}
};
//! Kernel that sets the schedule via a static member.
//! We inherit OpenMPScheduleDefaultKernel just to reuse its operator().
struct OpenMPScheduleMemberKernel : public OpenMPScheduleDefaultKernel
{
//! These two members are only checked for when the OmpSchedule trait is not specialized for this kernel type.
//! OpenMP schedule kind to be used by the AccCpuOmp2Blocks accelerator,
//! has to be static and constexpr.
static constexpr auto ompScheduleKind = alpaka::omp::Schedule::Static;
//! Member to set OpenMP chunk size, can be non-static and non-constexpr.
static constexpr int ompScheduleChunkSize = 1;
};
//! Kernel that sets the schedule via trait specialization.
//! We inherit OpenMPScheduleDefaultKernel just to reuse its operator().
//! The schedule trait specialization is given underneath this struct.
//! It has a higher priority than the internal static member.
struct OpenMPScheduleTraitKernel : public OpenMPScheduleDefaultKernel
{
};
namespace alpaka
{
namespace traits
{
//! Schedule trait specialization for OpenMPScheduleTraitKernel.
//! This is the most general way to define a schedule.
//! In case neither the trait nor the member are provided, alpaka does not set any runtime schedule and the
//! schedule used is defined by omp_set_schedule() called on the user side, or otherwise by the OMP_SCHEDULE
//! environment variable.
template<typename TAcc>
struct OmpSchedule<OpenMPScheduleTraitKernel, TAcc>
{
template<typename TDim, typename... TArgs>
ALPAKA_FN_HOST static auto getOmpSchedule(
OpenMPScheduleTraitKernel const& kernelFnObj,
Vec<TDim, Idx<TAcc>> const& blockThreadExtent,
Vec<TDim, Idx<TAcc>> const& threadElemExtent,
TArgs const&... args) -> alpaka::omp::Schedule
{
// Determine schedule at runtime for the given kernel and run parameters.
// For this particular example kernel, TArgs is an empty pack and can be removed.
alpaka::ignore_unused(kernelFnObj);
alpaka::ignore_unused(blockThreadExtent);
alpaka::ignore_unused(threadElemExtent);
alpaka::ignore_unused(args...);
return alpaka::omp::Schedule{alpaka::omp::Schedule::Dynamic, 2};
}
};
} // namespace traits
} // namespace alpaka
auto main() -> int
{
// Fallback for the CI with disabled sequential backend
# if defined(ALPAKA_CI) && !defined(ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED)
return EXIT_SUCCESS;
# else
using Idx = std::size_t;
// OpenMP schedule illustrated by this example only has effect with
// with the AccCpuOmp2Blocks accelerator.
// This example also assumes 1d for simplicity.
using Acc = alpaka::AccCpuOmp2Blocks<alpaka::DimInt<1>, Idx>;
std::cout << "Using alpaka accelerator: " << alpaka::getAccName<Acc>() << std::endl;
// Defines the synchronization behavior of a queue
using QueueProperty = alpaka::Blocking;
using Queue = alpaka::Queue<Acc, QueueProperty>;
// Select a device
auto const devAcc = alpaka::getDevByIdx<Acc>(0u);
// Create a queue on the device
Queue queue(devAcc);
// Define the work division
Idx const threadsPerGrid = 16u;
Idx const elementsPerThread = 1u;
auto const workDiv = alpaka::getValidWorkDiv<Acc>(
devAcc,
threadsPerGrid,
elementsPerThread,
false,
alpaka::GridBlockExtentSubDivRestrictions::Unrestricted);
// Run the kernel setting no schedule explicitly.
// In this case the schedule is controlled by the OMP_SCHEDULE environment variable.
std::cout << "OpenMPScheduleDefaultKernel setting no schedule explicitly:\n";
alpaka::exec<Acc>(queue, workDiv, OpenMPScheduleDefaultKernel{});
alpaka::wait(queue);
// Run the kernel setting the schedule via a trait
std::cout << "\n\nOpenMPScheduleMemberKernel setting the schedule via a static member:\n";
alpaka::exec<Acc>(queue, workDiv, OpenMPScheduleMemberKernel{});
alpaka::wait(queue);
// Run the kernel setting the schedule via a trait
std::cout << "\n\nOpenMPScheduleTraitKernel setting the schedule via trait:\n";
alpaka::exec<Acc>(queue, workDiv, OpenMPScheduleTraitKernel{});
alpaka::wait(queue);
return EXIT_SUCCESS;
# endif
}
#else
auto main() -> int
{
std::cout << "This example is disabled, as it requires OpenMP runtime version >= 3.0 and alpaka accelerator"
<< " AccCpuOmp2Blocks\n";
return EXIT_SUCCESS;
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Use ADL instead of directly putting property map's get/set into boost namespace.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2015 Facebook, 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 <map>
#include <thrift/lib/cpp/transport/TSocket.h>
#include <thrift/lib/cpp/transport/TServerSocket.h>
#include <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h>
#include <thrift/tutorial/cpp/async/fetcher/gen-cpp2/Fetcher.h>
#include <thrift/tutorial/cpp/async/fetcher/FetcherHandler.h>
#include <gtest/gtest.h>
using namespace std;
using namespace folly;
using namespace apache::thrift;
using namespace apache::thrift::tutorial::fetcher;
class FetcherHandlerTest : public testing::Test {
protected:
EventBase eb;
template <typename T>
T sync(Future<T> f) { return f.waitVia(&eb).get(); }
FetchHttpRequest makeRequest(SocketAddress addr, string path) {
FetchHttpRequest request;
request.addr = addr.getAddressStr();
request.port = addr.getPort();
request.path = path;
return request;
}
};
TEST_F(FetcherHandlerTest, example_pass) {
const auto data = map<string, string>{
{"/foo", "<html></html>"},
{"/bar", "<html><head></head><body></body></html>"},
};
auto sock = make_shared<transport::TServerSocket>(0);
sock->setAcceptTimeout(10);
sock->listen();
auto listen = thread([=] {
while (true) {
shared_ptr<transport::TRpcTransport> conn;
try {
conn = sock->accept();
} catch (transport::TTransportException&) {
break; // closed
}
string raw;
uint8_t buf[4096];
while (auto k = conn->read(buf, sizeof(buf))) {
raw.append(reinterpret_cast<const char*>(buf), k);
if (StringPiece(raw).endsWith("\r\n\r\n")) {
break;
}
}
vector<StringPiece> lines;
split("\r\n", raw, lines);
auto line = lines.at(0);
vector<StringPiece> parts;
split(" ", line, parts);
EXPECT_EQ("GET", parts.at(0));
EXPECT_EQ("HTTP/1.0", parts.at(2));
auto path = parts.at(1);
auto i = data.find(path.str());
if (i != data.end()) {
const auto& content = i->second;
conn->write(
reinterpret_cast<const uint8_t*>(content.data()), content.size());
}
}
});
SCOPE_EXIT {
sock->close();
listen.join();
};
auto handler = make_shared<FetcherHandler>();
ScopedServerInterfaceThread runner(handler);
auto client = runner.newClient<FetcherAsyncClient>(eb);
SocketAddress http;
sock->getAddress(&http);
EXPECT_EQ(
data.at("/foo"),
sync(client->future_fetchHttp(makeRequest(http, "/foo"))));
}
<commit_msg>Increase poll timeout in FetcherHandlerTest<commit_after>/*
* Copyright 2015 Facebook, 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 <map>
#include <thrift/lib/cpp/transport/TSocket.h>
#include <thrift/lib/cpp/transport/TServerSocket.h>
#include <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h>
#include <thrift/tutorial/cpp/async/fetcher/gen-cpp2/Fetcher.h>
#include <thrift/tutorial/cpp/async/fetcher/FetcherHandler.h>
#include <gtest/gtest.h>
using namespace std;
using namespace folly;
using namespace apache::thrift;
using namespace apache::thrift::tutorial::fetcher;
class FetcherHandlerTest : public testing::Test {
protected:
EventBase eb;
template <typename T>
T sync(Future<T> f) { return f.waitVia(&eb).get(); }
FetchHttpRequest makeRequest(SocketAddress addr, string path) {
FetchHttpRequest request;
request.addr = addr.getAddressStr();
request.port = addr.getPort();
request.path = path;
return request;
}
};
TEST_F(FetcherHandlerTest, example_pass) {
const auto data = map<string, string>{
{"/foo", "<html></html>"},
{"/bar", "<html><head></head><body></body></html>"},
};
auto sock = make_shared<transport::TServerSocket>(0);
sock->setAcceptTimeout(1000);
sock->listen();
auto listen = thread([=] {
while (true) {
shared_ptr<transport::TRpcTransport> conn;
try {
conn = sock->accept();
} catch (transport::TTransportException&) {
break; // closed
}
string raw;
uint8_t buf[4096];
while (auto k = conn->read(buf, sizeof(buf))) {
raw.append(reinterpret_cast<const char*>(buf), k);
if (StringPiece(raw).endsWith("\r\n\r\n")) {
break;
}
}
vector<StringPiece> lines;
split("\r\n", raw, lines);
auto line = lines.at(0);
vector<StringPiece> parts;
split(" ", line, parts);
EXPECT_EQ("GET", parts.at(0));
EXPECT_EQ("HTTP/1.0", parts.at(2));
auto path = parts.at(1);
auto i = data.find(path.str());
if (i != data.end()) {
const auto& content = i->second;
conn->write(
reinterpret_cast<const uint8_t*>(content.data()), content.size());
}
}
});
SCOPE_EXIT {
sock->close();
listen.join();
};
auto handler = make_shared<FetcherHandler>();
ScopedServerInterfaceThread runner(handler);
auto client = runner.newClient<FetcherAsyncClient>(eb);
SocketAddress http;
sock->getAddress(&http);
EXPECT_EQ(
data.at("/foo"),
sync(client->future_fetchHttp(makeRequest(http, "/foo"))));
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2017 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofApp.h"
void ofApp::setup()
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
// Load the network data.
dlib::deserialize(ofToDataPath("mmod_human_face_detector.dat", true)) >> net;
if (ofLoadImage(pixels, "Crowd.jpg"))
{
texture.loadData(pixels);
}
dlib::matrix<rgb_pixel> img;
dlib::load_image(img, ofToDataPath("Crowd.jpg", true));
// Upsampling the image will allow us to detect smaller faces but will cause
// the program to use more RAM and run longer.
float initialSize = img.size();
// while (img.size() < 800 * 800)
// {
// dlib::pyramid_up(img);
// }
// Note that you can process a bunch of images in a std::vector at once and
// it runs much faster, since this will form mini-batches of images and
// therefore get better parallelism out of your GPU hardware. However, all
// the images must be the same size. To avoid this requirement on images
// being the same size we process them individually in this example.
auto dets = net(img);
for (auto&& d: dets)
{
rectangles.push_back(d);
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time);
std::cout << "elapsed time: " << elapsed_seconds.count() << "s";
std::cout << std::endl;
// 16 seconds on MacBook Pro (15-inch, Mid 2012), no CUDA support.
}
void ofApp::draw()
{
ofBackground(0);
ofNoFill();
ofSetColor(ofColor::white);
texture.draw(0, 0);
for (auto& r: rectangles)
{
std::stringstream ss;
ss << "Confidence: " << r.detection_confidence << std::endl;
ss << "Ignore: " << r.ignore;
ofRectangle rect = toOf(r);
ofDrawRectangle(rect);
ofPopMatrix();
ofDrawBitmapString(ss.str(), rect.getCenter());
}
}
<commit_msg>Additions.<commit_after>//
// Copyright (c) 2017 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofApp.h"
void ofApp::setup()
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
// Load the network data.
dlib::deserialize(ofToDataPath("mmod_human_face_detector.dat", true)) >> net;
if (ofLoadImage(pixels, "Crowd.jpg"))
{
texture.loadData(pixels);
}
dlib::matrix<rgb_pixel> img;
dlib::load_image(img, ofToDataPath("Crowd.jpg", true));
// Upsampling the image will allow us to detect smaller faces but will cause
// the program to use more RAM and run longer.
float initialSize = img.size();
// while (img.size() < 800 * 800)
// {
// dlib::pyramid_up(img);
// }
// Note that you can process a bunch of images in a std::vector at once and
// it runs much faster, since this will form mini-batches of images and
// therefore get better parallelism out of your GPU hardware. However, all
// the images must be the same size. To avoid this requirement on images
// being the same size we process them individually in this example.
auto dets = net(img);
for (auto&& d: dets)
{
rectangles.push_back(d);
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "finished computation at " << std::ctime(&end_time);
std::cout << "elapsed time: " << elapsed_seconds.count() << "s";
std::cout << std::endl;
// 16 seconds on MacBook Pro (15-inch, Mid 2012), no CUDA support.
// 1.2 seconds on i7 7700 + Nvidia 1080, CUDA support + MKL libs.
}
void ofApp::draw()
{
ofBackground(0);
ofNoFill();
ofSetColor(ofColor::white);
texture.draw(0, 0);
for (auto& r: rectangles)
{
std::stringstream ss;
ss << "Confidence: " << r.detection_confidence << std::endl;
ss << "Ignore: " << r.ignore;
ofRectangle rect = toOf(r);
ofDrawRectangle(rect);
ofPopMatrix();
ofDrawBitmapString(ss.str(), rect.getCenter());
}
}
<|endoftext|> |
<commit_before><commit_msg>Fix error with std::integral_constant aggregate initialization<commit_after><|endoftext|> |
<commit_before>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan 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.
*/
#ifndef _MAIKEN_DEFS_LANG_HPP_
#define _MAIKEN_DEFS_LANG_HPP_
#define MKN_DEFS_CMD "Commands:"
#define MKN_DEFS_BUILD " build | Compile and link"
#define MKN_DEFS_CLEAN " clean | Delete files from ./bin/$profile"
#define MKN_DEFS_COMP " compile | Compile sources to ./bin/$profile"
#define MKN_DEFS_DBG " dbg | Executes project profile binary with debugger"
#define MKN_DEFS_INIT " init | Create minimal mkn.xml in ./"
#define MKN_DEFS_LINK " link | Link object files to exe/lib"
#define MKN_DEFS_PACK " pack | Copy binary files & library files into bin/$profile/pack"
#define MKN_DEFS_PROFS " profiles | Display profiles contained within ./mkn.xml"
#define MKN_DEFS_RUN " run | Executes project profile binary linking dynamic libraries automatically"
#define MKN_DEFS_INC " inc | Print include directories to std out"
#define MKN_DEFS_SRC " src | Print found source files to std out [allows -d]."
#define MKN_DEFS_TRIM " trim | Removes trailing whitespace from inc/src files under project directory"
#define MKN_DEFS_ARG "Arguments:"
#define MKN_DEFS_ARGS " -a/--args $a | Add $arg to compilation on build, passes to process on run"
#define MKN_DEFS_DEPS " -d/--dependencies $d | Number of children to include or project/profile CSV, missing assumed infinite"
#define MKN_DEFS_DIRC " -C/--directory $d | Execute on directory $d rather than current"
#define MKN_DEFS_EVSA " -E/--env $a | CSV key=value environment variables override, format \"k1=v1,k2=v2\""
#define MKN_DEFS_HELP " -h/--help | Print help to console"
#define MKN_DEFS_JARG " -j/--jargs | File type specifc args as json like '{\"c\": \"-DC_ARG1\", \"cpp\": \"-DCXX_ARG1\"}'"
#define MKN_DEFS_LINKER " -l/--linker $t | Adds $t to linking of root project profile"
#define MKN_DEFS_LINKER " -L/--all-linker $t | Adds $t to linking of all projects with link operations"
#define MKN_DEFS_PROF " -p/--profile $p | Activates profile $p"
#define MKN_DEFS_PROP " -P/--property $p | CSV key=value project properties override, format \"k1=v1,k2=v2\""
#define MKN_DEFS_DRYR " -R/--dry-run | Do not compile but print out process commands, do not run etc"
#define MKN_DEFS_STAT " -s/--scm-status | Display SCM status of project directory, allows -d"
#define MKN_DEFS_THREDS " -t/--threads $n | Consume $n threads while compiling source files where $n > 0, missing optimal resolution attempted."
#define MKN_DEFS_UPDATE " -u/--scm-update | Check for updates per project and ask if to, allows -d"
#define MKN_DEFS_FUPDATE " -U/--scm-force-update | Force update project from SCM, allows -d"
#define MKN_DEFS_VERSON " -v/--version | Displays the current maiken version number then exits, first checked command/argument"
#define MKN_DEFS_SETTNGS " -x/--settings $f | Sets settings.xml in use to file $f, directory of $f missing $(HOME)/maiken/$f attempted"
#define MKN_DEFS_STATIC " -K/--static | Links projects without mode as static"
#define MKN_DEFS_SHARED " -S/--shared | Links projects without mode as shared"
#define MKN_DEFS_EXMPL "Examples:"
#define MKN_DEFS_EXMPL1 " mkn build -dtKUa | Force update everything / Compile everything with optimal threads and, link everything statically"
#define MKN_DEFS_EXMPL2 " mkn clean build -dtu | Optionally update everything, clean everything, build everything with optimal threads"
#define MKN_DEFS_EXMPL3 " mkn clean build -d 1 -t 2 -u | Update/Clean/Build project and immediate dependencies with two threads"
#define MKN_DEFS_EXMPL4 " mkn -ds | Display '${scm} status' for everything"
#define MKN_PARENT "Parent"
#define MKN_PROFILE "Profile"
#define MKN_PROJECT "Project"
#define MKN_PROJECT_NOT_FOUND "Project not found, attempting automatic resolution: "
#endif /* _MAIKEN_DEFS_LANG_HPP_ */
<commit_msg>Update defs.en.hpp<commit_after>/**
Copyright (c) 2013, Philip Deegan.
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 Philip Deegan 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.
*/
#ifndef _MAIKEN_DEFS_LANG_HPP_
#define _MAIKEN_DEFS_LANG_HPP_
#define MKN_DEFS_CMD "Commands:"
#define MKN_DEFS_BUILD " build | Compile and link"
#define MKN_DEFS_CLEAN " clean | Delete files from ./bin/$profile"
#define MKN_DEFS_COMP " compile | Compile sources to ./bin/$profile"
#define MKN_DEFS_DBG " dbg | Executes project profile binary with debugger"
#define MKN_DEFS_INIT " init | Create minimal mkn.xml in ./"
#define MKN_DEFS_LINK " link | Link object files to exe/lib"
#define MKN_DEFS_PACK " pack | Copy binary files & library files into bin/$profile/pack"
#define MKN_DEFS_PROFS " profiles | Display profiles contained within ./mkn.xml"
#define MKN_DEFS_RUN " run | Executes project profile binary linking dynamic libraries automatically"
#define MKN_DEFS_INC " inc | Print include directories to std out"
#define MKN_DEFS_SRC " src | Print found source files to std out [allows -d]."
#define MKN_DEFS_TRIM " trim | Removes trailing whitespace from inc/src files under project directory"
#define MKN_DEFS_ARG "Arguments:"
#define MKN_DEFS_ARGS " -a/--args $a | Add $arg to compilation on build, passes to process on run"
#define MKN_DEFS_DEPS " -d/--dependencies $d | Number of children to include or project/profile CSV, missing assumed infinite"
#define MKN_DEFS_DIRC " -C/--directory $d | Execute on directory $d rather than current"
#define MKN_DEFS_EVSA " -E/--env $a | CSV key=value environment variables override, format \"k1=v1,k2=v2\""
#define MKN_DEFS_HELP " -h/--help | Print help to console"
#define MKN_DEFS_JARG " -j/--jargs | File type specifc args as json like '{\"c\": \"-DC_ARG1\", \"cpp\": \"-DCXX_ARG1\"}'"
#define MKN_DEFS_LINKER " -l/--linker $t | Adds $t to linking of root project profile"
#define MKN_DEFS_ALINKR " -L/--all-linker $t | Adds $t to linking of all projects with link operations"
#define MKN_DEFS_PROF " -p/--profile $p | Activates profile $p"
#define MKN_DEFS_PROP " -P/--property $p | CSV key=value project properties override, format \"k1=v1,k2=v2\""
#define MKN_DEFS_DRYR " -R/--dry-run | Do not compile but print out process commands, do not run etc"
#define MKN_DEFS_STAT " -s/--scm-status | Display SCM status of project directory, allows -d"
#define MKN_DEFS_THREDS " -t/--threads $n | Consume $n threads while compiling source files where $n > 0, missing optimal resolution attempted."
#define MKN_DEFS_UPDATE " -u/--scm-update | Check for updates per project and ask if to, allows -d"
#define MKN_DEFS_FUPDATE " -U/--scm-force-update | Force update project from SCM, allows -d"
#define MKN_DEFS_VERSON " -v/--version | Displays the current maiken version number then exits, first checked command/argument"
#define MKN_DEFS_SETTNGS " -x/--settings $f | Sets settings.xml in use to file $f, directory of $f missing $(HOME)/maiken/$f attempted"
#define MKN_DEFS_STATIC " -K/--static | Links projects without mode as static"
#define MKN_DEFS_SHARED " -S/--shared | Links projects without mode as shared"
#define MKN_DEFS_EXMPL "Examples:"
#define MKN_DEFS_EXMPL1 " mkn build -dtKUa | Force update everything / Compile everything with optimal threads and, link everything statically"
#define MKN_DEFS_EXMPL2 " mkn clean build -dtu | Optionally update everything, clean everything, build everything with optimal threads"
#define MKN_DEFS_EXMPL3 " mkn clean build -d 1 -t 2 -u | Update/Clean/Build project and immediate dependencies with two threads"
#define MKN_DEFS_EXMPL4 " mkn -ds | Display '${scm} status' for everything"
#define MKN_PARENT "Parent"
#define MKN_PROFILE "Profile"
#define MKN_PROJECT "Project"
#define MKN_PROJECT_NOT_FOUND "Project not found, attempting automatic resolution: "
#endif /* _MAIKEN_DEFS_LANG_HPP_ */
<|endoftext|> |
<commit_before>#define __STDC_FORMAT_MACROS
#include <errno.h>
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <algorithm>
#include <phosg/Time.hh>
#include <phosg/UnitTest.hh>
#include <string>
#include "Pool.hh"
#include "LogarithmicAllocator.hh"
#include "SimpleAllocator.hh"
using namespace std;
using namespace sharedstructures;
shared_ptr<Allocator> create_allocator(shared_ptr<Pool> pool,
const string& allocator_type) {
if (allocator_type == "simple") {
return shared_ptr<Allocator>(new SimpleAllocator(pool));
}
if (allocator_type == "logarithmic") {
return shared_ptr<Allocator>(new LogarithmicAllocator(pool));
}
throw invalid_argument("unknown allocator type: " + allocator_type);
}
template <typename T>
struct Stats {
size_t count;
T sum;
T mean;
T min;
T max;
T p01;
T p10;
T p50;
T p90;
T p99;
};
template <typename T>
struct Stats<T> get_stats(const vector<T>& x) {
Stats<T> ret;
ret.count = x.size();
ret.min = x.front();
ret.max = x.back();
ret.p01 = x[(1 * ret.count) / 100];
ret.p10 = x[(10 * ret.count) / 100];
ret.p50 = x[(50 * ret.count) / 100];
ret.p90 = x[(90 * ret.count) / 100];
ret.p99 = x[(99 * ret.count) / 100];
ret.sum = 0;
for (const auto& y : x) {
ret.sum += y;
}
ret.mean = ret.sum / ret.count;
return ret;
}
int main(int argc, char** argv) {
size_t max_size = 32 * 1024 * 1024;
size_t min_alloc_size = 1, max_alloc_size = 1024;
uint64_t report_interval = 100;
string allocator_type;
string pool_name = "benchmark-pool";
for (int x = 1; x < argc; x++) {
if (argv[x][0] == '-') {
if (argv[x][1] == 'l') {
max_size = strtoull(&argv[x][2], NULL, 0);
} else if (argv[x][1] == 's') {
min_alloc_size = strtoull(&argv[x][2], NULL, 0);
} else if (argv[x][1] == 'S') {
max_alloc_size = strtoull(&argv[x][2], NULL, 0);
} else if (argv[x][1] == 'X') {
allocator_type = &argv[x][2];
} else if (argv[x][1] == 'P') {
pool_name = &argv[x][2];
} else {
fprintf(stderr, "unknown argument: %s\n", argv[x]);
return 1;
}
} else {
fprintf(stderr, "unknown argument: %s\n", argv[x]);
return 1;
}
}
srand(time(NULL));
Pool::delete_pool(pool_name);
shared_ptr<Pool> pool(new Pool(pool_name));
shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
vector<double> efficiencies;
vector<uint64_t> alloc_times;
unordered_set<uint64_t> allocated_regions;
size_t allocated_size = 0;
while (pool->size() <= max_size) {
if (allocated_regions.size() % report_interval == 0) {
double efficiency = (float)alloc->bytes_allocated() /
(pool->size() - alloc->bytes_free());
efficiencies.emplace_back(efficiency);
fprintf(stderr, "allocation #%zu: %zu allocated, %zu free, %zu total, "
"%g efficiency\n", allocated_regions.size(), allocated_size,
alloc->bytes_free(), pool->size(), efficiency);
}
size_t size = min_alloc_size + (rand() % (max_alloc_size - min_alloc_size));
uint64_t start = now();
uint64_t offset = alloc->allocate(size);
uint64_t end = now();
alloc_times.emplace_back(end - start);
allocated_regions.emplace(offset);
allocated_size += size;
expect_eq(allocated_size, alloc->bytes_allocated());
}
vector<uint64_t> free_times;
while (!allocated_regions.empty()) {
auto it = allocated_regions.begin();
uint64_t offset = *it;
uint64_t size = alloc->block_size(offset);
uint64_t start = now();
alloc->free(offset);
uint64_t end = now();
free_times.emplace_back(end - start);
allocated_regions.erase(it);
allocated_size -= size;
expect_eq(allocated_size, alloc->bytes_allocated());
if (allocated_regions.size() % report_interval == 0) {
double efficiency = (float)alloc->bytes_allocated() /
(pool->size() - alloc->bytes_free());
efficiencies.emplace_back(efficiency);
fprintf(stderr, "free #%zu: %zu allocated, %zu free, %zu total, "
"%g efficiency\n", allocated_regions.size(), allocated_size,
alloc->bytes_free(), pool->size(), efficiency);
}
}
sort(efficiencies.begin(), efficiencies.end());
auto efficiency_stats = get_stats(efficiencies);
fprintf(stdout, "efficiency: avg=%lg min=%lg p01=%lg p10=%lg p50=%lg p90=%lg "
"p99=%lg max=%lg\n", efficiency_stats.mean, efficiency_stats.min,
efficiency_stats.p01, efficiency_stats.p10, efficiency_stats.p50,
efficiency_stats.p90, efficiency_stats.p99, efficiency_stats.max);
sort(alloc_times.begin(), alloc_times.end());
auto alloc_time_stats = get_stats(alloc_times);
fprintf(stdout, "alloc usecs: avg=%" PRIu64 " min=%" PRIu64 " p01=%" PRIu64
" p10=%" PRIu64 " p50=%" PRIu64 " p90=%" PRIu64 " p99=%" PRIu64
" max=%" PRIu64 "\n", alloc_time_stats.mean, alloc_time_stats.min,
alloc_time_stats.p01, alloc_time_stats.p10, alloc_time_stats.p50,
alloc_time_stats.p90, alloc_time_stats.p99, alloc_time_stats.max);
sort(free_times.begin(), free_times.end());
auto free_time_stats = get_stats(free_times);
fprintf(stdout, "free usecs: avg=%" PRIu64 " min=%" PRIu64 " p01=%" PRIu64
" p10=%" PRIu64 " p50=%" PRIu64 " p90=%" PRIu64 " p99=%" PRIu64
" max=%" PRIu64 "\n", free_time_stats.mean, free_time_stats.min,
free_time_stats.p01, free_time_stats.p10, free_time_stats.p50,
free_time_stats.p90, free_time_stats.p99, free_time_stats.max);
return 0;
}
<commit_msg>add an option in allocator benchmark to preallocate the pool<commit_after>#define __STDC_FORMAT_MACROS
#include <errno.h>
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <algorithm>
#include <phosg/Time.hh>
#include <phosg/UnitTest.hh>
#include <string>
#include "Pool.hh"
#include "LogarithmicAllocator.hh"
#include "SimpleAllocator.hh"
using namespace std;
using namespace sharedstructures;
shared_ptr<Allocator> create_allocator(shared_ptr<Pool> pool,
const string& allocator_type) {
if (allocator_type == "simple") {
return shared_ptr<Allocator>(new SimpleAllocator(pool));
}
if (allocator_type == "logarithmic") {
return shared_ptr<Allocator>(new LogarithmicAllocator(pool));
}
throw invalid_argument("unknown allocator type: " + allocator_type);
}
template <typename T>
struct Stats {
size_t count;
T sum;
T mean;
T min;
T max;
T p01;
T p10;
T p50;
T p90;
T p99;
};
template <typename T>
struct Stats<T> get_stats(const vector<T>& x) {
Stats<T> ret;
ret.count = x.size();
ret.min = x.front();
ret.max = x.back();
ret.p01 = x[(1 * ret.count) / 100];
ret.p10 = x[(10 * ret.count) / 100];
ret.p50 = x[(50 * ret.count) / 100];
ret.p90 = x[(90 * ret.count) / 100];
ret.p99 = x[(99 * ret.count) / 100];
ret.sum = 0;
for (const auto& y : x) {
ret.sum += y;
}
ret.mean = ret.sum / ret.count;
return ret;
}
void print_usage(const char* argv0) {
fprintf(stderr,
"usage: %s -X<allocator-type> [options]\n"
" options:\n"
" -l<max-pool-size> : pool will grow up to this size (bytes)\n"
" -s<min-alloc-size> : allocations will be at least this many bytes each\n"
" -S<max-alloc-size> : allocations will be at most this many bytes each\n"
" -P<pool-name> : filename for the pool\n"
" -A : preallocate the entire pool up to max-pool-size\n", argv0);
}
int main(int argc, char** argv) {
size_t max_size = 32 * 1024 * 1024;
size_t min_alloc_size = 1, max_alloc_size = 1024;
uint64_t report_interval = 100;
bool preallocate = false;
string allocator_type;
string pool_name = "benchmark-pool";
for (int x = 1; x < argc; x++) {
if (argv[x][0] == '-') {
if (argv[x][1] == 'l') {
max_size = strtoull(&argv[x][2], NULL, 0);
} else if (argv[x][1] == 's') {
min_alloc_size = strtoull(&argv[x][2], NULL, 0);
} else if (argv[x][1] == 'S') {
max_alloc_size = strtoull(&argv[x][2], NULL, 0);
} else if (argv[x][1] == 'X') {
allocator_type = &argv[x][2];
} else if (argv[x][1] == 'P') {
pool_name = &argv[x][2];
} else if (argv[x][1] == 'A') {
preallocate = true;
} else {
fprintf(stderr, "unknown argument: %s\n", argv[x]);
print_usage(argv[0]);
return 1;
}
} else {
fprintf(stderr, "unknown argument: %s\n", argv[x]);
print_usage(argv[0]);
return 1;
}
}
if (allocator_type.empty()) {
print_usage(argv[0]);
return 1;
}
srand(time(NULL));
Pool::delete_pool(pool_name);
shared_ptr<Pool> pool(new Pool(pool_name));
if (preallocate) {
pool->expand(max_size);
}
shared_ptr<Allocator> alloc = create_allocator(pool, allocator_type);
vector<double> efficiencies;
vector<uint64_t> alloc_times;
unordered_set<uint64_t> allocated_regions;
size_t allocated_size = 0;
while (pool->size() <= max_size) {
if (allocated_regions.size() % report_interval == 0) {
double efficiency = (float)alloc->bytes_allocated() /
(pool->size() - alloc->bytes_free());
efficiencies.emplace_back(efficiency);
fprintf(stderr, "allocation #%zu: %zu allocated, %zu free, %zu total, "
"%g efficiency\n", allocated_regions.size(), allocated_size,
alloc->bytes_free(), pool->size(), efficiency);
}
size_t size = min_alloc_size + (rand() % (max_alloc_size - min_alloc_size));
uint64_t start = now();
uint64_t offset = alloc->allocate(size);
uint64_t end = now();
alloc_times.emplace_back(end - start);
allocated_regions.emplace(offset);
allocated_size += size;
expect_eq(allocated_size, alloc->bytes_allocated());
}
vector<uint64_t> free_times;
while (!allocated_regions.empty()) {
auto it = allocated_regions.begin();
uint64_t offset = *it;
uint64_t size = alloc->block_size(offset);
uint64_t start = now();
alloc->free(offset);
uint64_t end = now();
free_times.emplace_back(end - start);
allocated_regions.erase(it);
allocated_size -= size;
expect_eq(allocated_size, alloc->bytes_allocated());
if (allocated_regions.size() % report_interval == 0) {
double efficiency = (float)alloc->bytes_allocated() /
(pool->size() - alloc->bytes_free());
efficiencies.emplace_back(efficiency);
fprintf(stderr, "free #%zu: %zu allocated, %zu free, %zu total, "
"%g efficiency\n", allocated_regions.size(), allocated_size,
alloc->bytes_free(), pool->size(), efficiency);
}
}
sort(efficiencies.begin(), efficiencies.end());
auto efficiency_stats = get_stats(efficiencies);
fprintf(stdout, "efficiency: avg=%lg min=%lg p01=%lg p10=%lg p50=%lg p90=%lg "
"p99=%lg max=%lg\n", efficiency_stats.mean, efficiency_stats.min,
efficiency_stats.p01, efficiency_stats.p10, efficiency_stats.p50,
efficiency_stats.p90, efficiency_stats.p99, efficiency_stats.max);
sort(alloc_times.begin(), alloc_times.end());
auto alloc_time_stats = get_stats(alloc_times);
fprintf(stdout, "alloc usecs: avg=%" PRIu64 " min=%" PRIu64 " p01=%" PRIu64
" p10=%" PRIu64 " p50=%" PRIu64 " p90=%" PRIu64 " p99=%" PRIu64
" max=%" PRIu64 "\n", alloc_time_stats.mean, alloc_time_stats.min,
alloc_time_stats.p01, alloc_time_stats.p10, alloc_time_stats.p50,
alloc_time_stats.p90, alloc_time_stats.p99, alloc_time_stats.max);
sort(free_times.begin(), free_times.end());
auto free_time_stats = get_stats(free_times);
fprintf(stdout, "free usecs: avg=%" PRIu64 " min=%" PRIu64 " p01=%" PRIu64
" p10=%" PRIu64 " p50=%" PRIu64 " p90=%" PRIu64 " p99=%" PRIu64
" max=%" PRIu64 "\n", free_time_stats.mean, free_time_stats.min,
free_time_stats.p01, free_time_stats.p10, free_time_stats.p50,
free_time_stats.p90, free_time_stats.p99, free_time_stats.max);
return 0;
}
<|endoftext|> |
<commit_before>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_RING_POOL_HPP
#define GHULBUS_LIBRARY_INCLUDE_GUARD_RING_POOL_HPP
/** @file
*
* @brief Ring pool allocator.
* @author Andreas Weis ([email protected])
*/
#include <gbBase/config.hpp>
#include <gbBase/Assert.hpp>
#include <atomic>
#include <cstring>
#include <memory>
#include <vector>
namespace GHULBUS_BASE_NAMESPACE
{
namespace Memory
{
namespace RingPoolPolicies
{
namespace FallbackPolicies
{
struct ReturnNullptr
{
static void* allocate_failed()
{
return nullptr;
}
};
struct Assert
{
static void* allocate_failed()
{
GHULBUS_ASSERT_MESSAGE(false, "Allocator capacity exceeded.");
return nullptr;
}
};
}
template<typename FallbackPolicy_T>
struct Policies {
typedef FallbackPolicy_T FallbackPolicy;
};
using DefaultPolicies = Policies<FallbackPolicies::ReturnNullptr>;
}
template<class Policies_T>
class RingPool_T
{
private:
std::atomic<std::size_t> m_rightPtr; // offset to the beginning of the unallocated memory
std::atomic<std::size_t> m_leftPtr; // offset to the beginning of the allocated memory
std::size_t const m_poolCapacity;
std::unique_ptr<char[]> m_storage;
public:
inline RingPool_T(std::size_t poolCapacity);
RingPool_T(RingPool_T const&) = delete;
RingPool_T& operator=(RingPool_T const&) = delete;
inline void* allocate(std::size_t requested_size);
inline void free(void* ptr);
};
template<class Policies_T>
RingPool_T<Policies_T>::RingPool_T(std::size_t poolCapacity)
:m_rightPtr(0), m_leftPtr(0), m_poolCapacity(poolCapacity),
m_storage(std::make_unique<char[]>(poolCapacity))
{
}
template<class Policies_T>
void* RingPool_T<Policies_T>::allocate(std::size_t requested_size)
{
requested_size += sizeof(size_t);
for(;;) {
auto expected_right = m_rightPtr.load();
auto const left = m_leftPtr.load();
if(left <= expected_right) {
// rightPtr is right of leftPtr; allocated section does not span ring boundaries
if(expected_right + requested_size >= m_poolCapacity) {
// no room to the right, attempt wrap-around and allocate at the beginning
if(requested_size >= left) {
// requested data too big; does not fit empty space
return Policies_T::FallbackPolicy::allocate_failed();
} else {
// allocate from the beginning
if(m_rightPtr.compare_exchange_weak(expected_right, requested_size)) {
auto const basePtr = m_storage.get();
std::memcpy(basePtr, &requested_size, sizeof(std::size_t));
return basePtr + sizeof(size_t);
}
}
} else {
// allocate at rightPtr
if(m_rightPtr.compare_exchange_weak(expected_right, expected_right + requested_size)) {
auto const basePtr = m_storage.get() + expected_right;
std::memcpy(basePtr, &requested_size, sizeof(std::size_t));
return basePtr + sizeof(size_t);
}
}
} else {
// rightPtr is left of leftPtr; allocated section does span ring boundaries
if(expected_right + requested_size >= left) {
// requested data too big; does not fit empty space
return Policies_T::FallbackPolicy::allocate_failed();
} else {
// allocate at rightPtr
if(m_rightPtr.compare_exchange_weak(expected_right, expected_right + requested_size)) {
auto const basePtr = m_storage.get() + expected_right;
std::memcpy(basePtr, &requested_size, sizeof(std::size_t));
return basePtr + sizeof(size_t);
}
}
}
}
}
template<class Policies_T>
void RingPool_T<Policies_T>::free(void* ptr)
{
char* baseptr = static_cast<char*>(ptr) - sizeof(std::size_t);
std::size_t elementSize;
std::memcpy(&elementSize, baseptr, sizeof(std::size_t));
GHULBUS_ASSERT_MESSAGE(baseptr == m_storage.get() + m_leftPtr,
"RingPool elements must be freed in the order in which they were allocated.");
m_leftPtr.fetch_add(elementSize);
// todo: what if we free the last element at the end of the ring buffer?
}
using RingPool = RingPool_T<RingPoolPolicies::DefaultPolicies>;
}
}
#endif
<commit_msg>ring pool allocator wip<commit_after>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_RING_POOL_HPP
#define GHULBUS_LIBRARY_INCLUDE_GUARD_RING_POOL_HPP
/** @file
*
* @brief Ring pool allocator.
* @author Andreas Weis ([email protected])
*/
#include <gbBase/config.hpp>
#include <gbBase/Assert.hpp>
#include <atomic>
#include <cstring>
#include <memory>
#include <mutex>
#include <new>
#include <vector>
namespace GHULBUS_BASE_NAMESPACE
{
namespace Memory
{
namespace RingPoolPolicies
{
namespace FallbackPolicies
{
struct ReturnNullptr
{
static void* allocate_failed()
{
return nullptr;
}
};
struct Assert
{
static void* allocate_failed()
{
GHULBUS_ASSERT_MESSAGE(false, "Allocator capacity exceeded.");
return nullptr;
}
};
template<typename Exception_T = std::bad_alloc>
struct Throw
{
static void* allocate_failed()
{
throw Exception_T();
}
};
// @todo: fallback allocator
}
template<typename FallbackPolicy_T>
struct Policies {
typedef FallbackPolicy_T FallbackPolicy;
};
using DefaultPolicies = Policies<FallbackPolicies::ReturnNullptr>;
}
/**
* - freeing never blocks allocations
* - allocations never block each other
* - freeing blocks if order is different from allocation order
*/
template<class Policies_T>
class RingPool_T
{
private:
std::atomic<std::size_t> m_rightPtr; // offset to the beginning of the unallocated memory region
std::atomic<std::size_t> m_leftPtr; // offset to the beginning of the allocated memory region
std::size_t const m_poolCapacity;
std::unique_ptr<char[]> m_storage;
std::atomic<std::size_t> m_paddingPtr; // in case the last allocation in the buffer does not exactly hit
// the ring boundary, we have to leave some empty space at the end.
// if this happens, this offset points to the start of the empty area,
// that extends until m_poolCapacity. will be 0 if the end of the buffer
// is currently in the unallocated region (between rightPtr and leftPtr).
std::mutex m_freeListMutex;
std::vector<char*> m_freeList;
public:
inline RingPool_T(std::size_t poolCapacity);
RingPool_T(RingPool_T const&) = delete;
RingPool_T& operator=(RingPool_T const&) = delete;
void* allocate(std::size_t requested_size);
void free(void* ptr);
private:
inline void* allocate_block_at(std::size_t offset, std::size_t size);
};
template<class Policies_T>
RingPool_T<Policies_T>::RingPool_T(std::size_t poolCapacity)
:m_rightPtr(0), m_leftPtr(0), m_poolCapacity(poolCapacity),
m_storage(std::make_unique<char[]>(poolCapacity)), m_paddingPtr(0)
{
}
template<class Policies_T>
void* RingPool_T<Policies_T>::allocate(std::size_t requested_size)
{
requested_size += sizeof(size_t);
for(;;) {
auto expected_right = m_rightPtr.load();
auto const left = m_leftPtr.load();
if(left <= expected_right) {
// rightPtr is right of leftPtr; allocated section does not span ring boundaries
if(expected_right + requested_size >= m_poolCapacity) {
// no room to the right, attempt wrap-around and allocate at the beginning
if(requested_size >= left) {
// requested data too big; does not fit empty space
return Policies_T::FallbackPolicy::allocate_failed();
} else {
// allocate from the beginning
if(m_rightPtr.compare_exchange_weak(expected_right, requested_size)) {
// we wrapped around the ring; set the padding pointer so that we can skip the padding
// area when this block is freed again
std::size_t expected_padding = 0;
auto const res = m_paddingPtr.compare_exchange_strong(expected_padding, expected_right);
GHULBUS_ASSERT(res);
return allocate_block_at(0u, requested_size);
}
}
} else {
// allocate at rightPtr
if(m_rightPtr.compare_exchange_weak(expected_right, expected_right + requested_size)) {
return allocate_block_at(expected_right, requested_size);
}
}
} else {
// rightPtr is left of leftPtr; allocated section does span ring boundaries
if(expected_right + requested_size >= left) {
// requested data too big; does not fit empty space
return Policies_T::FallbackPolicy::allocate_failed();
} else {
// allocate at rightPtr
if(m_rightPtr.compare_exchange_weak(expected_right, expected_right + requested_size)) {
return allocate_block_at(expected_right, requested_size);
}
}
}
}
}
template<class Policies_T>
void* RingPool_T<Policies_T>::allocate_block_at(std::size_t offset, std::size_t size)
{
auto const basePtr = m_storage.get() + offset;
std::memcpy(basePtr, &size, sizeof(std::size_t));
return basePtr + sizeof(size_t);
}
template<class Policies_T>
void RingPool_T<Policies_T>::free(void* ptr)
{
char* baseptr = static_cast<char*>(ptr) - sizeof(std::size_t);
std::size_t elementSize;
std::memcpy(&elementSize, baseptr, sizeof(std::size_t));
GHULBUS_ASSERT_MESSAGE(baseptr == m_storage.get() + m_leftPtr,
"RingPool elements must be freed in the order in which they were allocated.");
m_leftPtr.fetch_add(elementSize);
if (m_leftPtr == m_paddingPtr)
{
// we freed the last element at the end of the ring buffer
m_leftPtr.store(0);
m_paddingPtr.store(0);
}
// @todo: maintain free list
// - frees that occur out of order go to free list
// - when to check free list? can we avoid locking on every free?
}
using RingPool = RingPool_T<RingPoolPolicies::DefaultPolicies>;
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_GENERIC_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_GENERIC_HPP
#include "container.hpp"
#include "detail/injected.hpp"
#include "detail/traits.hpp"
namespace kgr {
namespace detail {
template<typename Generic, typename Type, typename = void>
struct GenericServiceDestruction {
~GenericServiceDestruction() {
static_cast<Generic&>(*this).instance().~Type();
}
};
template<typename Generic, typename Type>
struct GenericServiceDestruction<Generic, Type, enable_if_t<std::is_trivially_destructible<Type>::value>> {};
} // namespace detail
template<typename CRTP, typename Type>
struct GenericService {
friend struct Container;
using Self = CRTP;
GenericService() = default;
GenericService(GenericService&& other) {
emplace(std::move(other.instance()));
}
GenericService& operator=(GenericService&& other) {
emplace(std::move(other.instance()));
return *this;
}
GenericService(const GenericService& other) {
emplace(other.instance());
}
GenericService& operator=(const GenericService& other) {
emplace(other.instance());
return *this;
}
template<typename... Args, detail::enable_if_t<detail::is_someway_constructible<Type, Args...>::value, int> = 0>
GenericService(in_place_t, Args&&... args) {
emplace(std::forward<Args>(args)...);
}
protected:
Type& instance() {
return *reinterpret_cast<Type*>(&_instance);
}
const Type& instance() const {
return *reinterpret_cast<const Type*>(&_instance);
}
private:
template<typename, typename...> friend struct detail::has_emplace_helper;
template<typename... Args, detail::enable_if_t<std::is_constructible<Type, Args...>::value, int> = 0>
void emplace(Args&&... args) {
new (&_instance) Type(std::forward<Args>(args)...);
}
template<typename... Args, detail::enable_if_t<detail::is_only_brace_constructible<Type, Args...>::value, int> = 0>
void emplace(Args&&... args) {
new (&_instance) Type{std::forward<Args>(args)...};
}
template<typename F, typename... Ts>
void autocall(Inject<Ts>... others) {
CRTP::call(instance(), F::value, std::forward<Inject<Ts>>(others).forward()...);
}
template<typename F, template<typename> class Map>
void autocall(Inject<ContainerService> cs) {
autocall<Map, F>(detail::tuple_seq<detail::function_arguments_t<typename F::value_type>>{}, std::move(cs));
}
template<template<typename> class Map, typename F, std::size_t... S>
void autocall(detail::seq<S...>, Inject<ContainerService> cs) {
cs.forward().invoke<Map>([this](detail::function_argument_t<S, typename F::value_type>... args){
CRTP::call(instance(), F::value, std::forward<detail::function_argument_t<S, typename F::value_type>>(args)...);
});
}
typename std::aligned_storage<sizeof(Type), alignof(Type)>::type _instance;
};
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_GENERIC_HPP
<commit_msg>autocall_function need access to generic service<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_GENERIC_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_GENERIC_HPP
#include "container.hpp"
#include "detail/injected.hpp"
#include "detail/traits.hpp"
namespace kgr {
namespace detail {
template<typename Generic, typename Type, typename = void>
struct GenericServiceDestruction {
~GenericServiceDestruction() {
static_cast<Generic&>(*this).instance().~Type();
}
};
template<typename Generic, typename Type>
struct GenericServiceDestruction<Generic, Type, enable_if_t<std::is_trivially_destructible<Type>::value>> {};
template<typename, typename> struct autocall_function;
} // namespace detail
template<typename CRTP, typename Type>
struct GenericService {
friend struct Container;
using Self = CRTP;
GenericService() = default;
GenericService(GenericService&& other) {
emplace(std::move(other.instance()));
}
GenericService& operator=(GenericService&& other) {
emplace(std::move(other.instance()));
return *this;
}
GenericService(const GenericService& other) {
emplace(other.instance());
}
GenericService& operator=(const GenericService& other) {
emplace(other.instance());
return *this;
}
template<typename... Args, detail::enable_if_t<detail::is_someway_constructible<Type, Args...>::value, int> = 0>
GenericService(in_place_t, Args&&... args) {
emplace(std::forward<Args>(args)...);
}
protected:
Type& instance() {
return *reinterpret_cast<Type*>(&_instance);
}
const Type& instance() const {
return *reinterpret_cast<const Type*>(&_instance);
}
private:
template<typename, typename...> friend struct detail::has_emplace_helper;
template<typename, typename> friend struct detail::autocall_function;
template<typename... Args, detail::enable_if_t<std::is_constructible<Type, Args...>::value, int> = 0>
void emplace(Args&&... args) {
new (&_instance) Type(std::forward<Args>(args)...);
}
template<typename... Args, detail::enable_if_t<detail::is_only_brace_constructible<Type, Args...>::value, int> = 0>
void emplace(Args&&... args) {
new (&_instance) Type{std::forward<Args>(args)...};
}
template<typename F, typename... Ts>
void autocall(Inject<Ts>... others) {
CRTP::call(instance(), F::value, std::forward<Inject<Ts>>(others).forward()...);
}
template<typename F, template<typename> class Map>
void autocall(Inject<ContainerService> cs) {
autocall<Map, F>(detail::tuple_seq<detail::function_arguments_t<typename F::value_type>>{}, std::move(cs));
}
template<template<typename> class Map, typename F, std::size_t... S>
void autocall(detail::seq<S...>, Inject<ContainerService> cs) {
cs.forward().invoke<Map>([this](detail::function_argument_t<S, typename F::value_type>... args){
CRTP::call(instance(), F::value, std::forward<detail::function_argument_t<S, typename F::value_type>>(args)...);
});
}
typename std::aligned_storage<sizeof(Type), alignof(Type)>::type _instance;
};
} // namespace kgr
#endif // KGR_KANGARU_INCLUDE_KANGARU_GENERIC_HPP
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_UTF8_HPP_INCLUDED
#define TORRENT_UTF8_HPP_INCLUDED
#include "libtorrent/config.hpp"
// on windows we need these functions for
// convert_to_native and convert_from_native
#if TORRENT_USE_WSTRING || defined TORRENT_WINDOWS
#include <string>
#include <cwchar>
#include "libtorrent/ConvertUTF.h"
namespace libtorrent
{
inline int utf8_wchar(const std::string &utf8, std::wstring &wide)
{
// allocate space for worst-case
wide.resize(utf8.size());
wchar_t const* dst_start = &wide[0];
char const* src_start = &utf8[0];
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF8toUTF32((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF32**)&dst_start, (UTF32*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - &wide[0]);
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF8toUTF16((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF16**)&dst_start, (UTF16*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - &wide[0]);
return ret;
}
else
{
return sourceIllegal;
}
}
inline int wchar_utf8(const std::wstring &wide, std::string &utf8)
{
// allocate space for worst-case
utf8.resize(wide.size() * 6);
char* dst_start = &utf8[0];
wchar_t const* src_start = &wide[0];
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF32toUTF8((const UTF32**)&src_start, (const UTF32*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF16toUTF8((const UTF16**)&src_start, (const UTF16*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else
{
return sourceIllegal;
}
}
}
#endif // !BOOST_NO_STD_WSTRING
#endif
<commit_msg>don't dereference empty strings<commit_after>/*
Copyright (c) 2006, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_UTF8_HPP_INCLUDED
#define TORRENT_UTF8_HPP_INCLUDED
#include "libtorrent/config.hpp"
// on windows we need these functions for
// convert_to_native and convert_from_native
#if TORRENT_USE_WSTRING || defined TORRENT_WINDOWS
#include <string>
#include <cwchar>
#include "libtorrent/ConvertUTF.h"
namespace libtorrent
{
inline int utf8_wchar(const std::string &utf8, std::wstring &wide)
{
// allocate space for worst-case
wide.resize(utf8.size());
wchar_t const* dst_start = wide.c_str();
char const* src_start = utf8.c_str();
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF8toUTF32((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF32**)&dst_start, (UTF32*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - wide.c_str());
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF8toUTF16((const UTF8**)&src_start, (const UTF8*)src_start
+ utf8.size(), (UTF16**)&dst_start, (UTF16*)dst_start + wide.size()
, lenientConversion);
wide.resize(dst_start - wide.c_str());
return ret;
}
else
{
return sourceIllegal;
}
}
inline int wchar_utf8(const std::wstring &wide, std::string &utf8)
{
// allocate space for worst-case
utf8.resize(wide.size() * 6);
if (wide.empty()) return 0;
char* dst_start = &utf8[0];
wchar_t const* src_start = wide.c_str();
ConversionResult ret;
if (sizeof(wchar_t) == sizeof(UTF32))
{
ret = ConvertUTF32toUTF8((const UTF32**)&src_start, (const UTF32*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else if (sizeof(wchar_t) == sizeof(UTF16))
{
ret = ConvertUTF16toUTF8((const UTF16**)&src_start, (const UTF16*)src_start
+ wide.size(), (UTF8**)&dst_start, (UTF8*)dst_start + utf8.size()
, lenientConversion);
utf8.resize(dst_start - &utf8[0]);
return ret;
}
else
{
return sourceIllegal;
}
}
}
#endif // !BOOST_NO_STD_WSTRING
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2011 Tor Lillqvist <[email protected]> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "oox/mathml/importutils.hxx"
#include <assert.h>
#include <stdio.h>
#include <oox/token/namespacemap.hxx>
#include <oox/token/tokenmap.hxx>
#include <oox/token/tokens.hxx>
#include <oox/token/namespaces.hxx>
#include <rtl/ustring.hxx>
#define OPENING( token ) XML_STREAM_OPENING( token )
#define CLOSING( token ) XML_STREAM_CLOSING( token )
using namespace com::sun::star;
using rtl::OUString;
namespace oox
{
namespace formulaimport
{
namespace
{
// a class that inherits from AttributeList, builds the internal data and then will be sliced off
// during conversion to the base class
class AttributeListBuilder
: public XmlStream::AttributeList
{
public:
AttributeListBuilder( const uno::Reference< xml::sax::XFastAttributeList >& a );
};
AttributeListBuilder::AttributeListBuilder( const uno::Reference< xml::sax::XFastAttributeList >& a )
{
if( a.get() == NULL )
return;
uno::Sequence< xml::FastAttribute > aFastAttrSeq = a->getFastAttributes();
const xml::FastAttribute* pFastAttr = aFastAttrSeq.getConstArray();
sal_Int32 nFastAttrLength = aFastAttrSeq.getLength();
for( int i = 0;
i < nFastAttrLength;
++i )
{
attrs[ pFastAttr[ i ].Token ] = pFastAttr[ i ].Value;
}
}
static OUString tokenToString( int token )
{
OUString tokenname = StaticTokenMap::get().getUnicodeTokenName( token & TOKEN_MASK );
if( tokenname.isEmpty())
tokenname = "???";
int nmsp = ( token & NMSP_MASK & ~( TAG_OPENING | TAG_CLOSING ));
#if 0 // this is awfully long
OUString namespacename = StaticNamespaceMap::get().count( nmsp ) != 0
? StaticNamespaceMap::get()[ nmsp ] : OUString( "???" );
#else
OUString namespacename;
// only few are needed actually
switch( nmsp )
{
case NMSP_officeMath:
namespacename = "m";
break;
case NMSP_doc:
namespacename = "w";
break;
default:
namespacename = "?";
break;
}
#endif
if( token == OPENING( token ))
return "<" + namespacename + ":" + tokenname + ">";
if( token == CLOSING( token ))
return "</" + namespacename + ":" + tokenname + ">";
// just the name itself, not specified whether opening or closing
return namespacename + ":" + tokenname;
}
} // namespace
OUString& XmlStream::AttributeList::operator[] (int token)
{
return attrs[token];
}
rtl::OUString XmlStream::AttributeList::attribute( int token, const rtl::OUString& def ) const
{
std::map< int, rtl::OUString >::const_iterator find = attrs.find( token );
if( find != attrs.end())
return find->second;
return def;
}
bool XmlStream::AttributeList::attribute( int token, bool def ) const
{
std::map< int, rtl::OUString >::const_iterator find = attrs.find( token );
if( find != attrs.end())
{
const rtl::OUString sValue = find->second;
if( sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("true")) ||
sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("on")) ||
sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("t")) ||
sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("1")) )
return true;
if( sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("false")) ||
sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("off")) ||
sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("f")) ||
sValue.equalsIgnoreAsciiCaseAsciiL(RTL_CONSTASCII_STRINGPARAM("0")) )
return false;
SAL_WARN( "oox.xmlstream", "Cannot convert \'" << sValue << "\' to bool." );
}
return def;
}
sal_Unicode XmlStream::AttributeList::attribute( int token, sal_Unicode def ) const
{
std::map< int, rtl::OUString >::const_iterator find = attrs.find( token );
if( find != attrs.end())
{
if( !find->second.isEmpty() )
{
if( find->second.getLength() != 1 )
SAL_WARN( "oox.xmlstream", "Cannot convert \'" << find->second << "\' to sal_Unicode, stripping." );
return find->second[ 0 ];
}
}
return def;
}
XmlStream::Tag::Tag( int t, const uno::Reference< xml::sax::XFastAttributeList >& a, const rtl::OUString& txt )
: token( t )
, attributes( AttributeListBuilder( a ))
, text( txt )
{
}
XmlStream::Tag::Tag( int t, const AttributeList& a )
: token( t )
, attributes( a )
{
}
XmlStream::Tag::operator bool() const
{
return token != XML_TOKEN_INVALID;
}
XmlStream::XmlStream()
: pos( 0 )
{
// make sure our extra bit does not conflict with values used by oox
assert( TAG_OPENING > ( 1024 << NMSP_SHIFT ));
}
bool XmlStream::atEnd() const
{
return pos >= tags.size();
}
XmlStream::Tag XmlStream::currentTag() const
{
if( pos >= tags.size())
return Tag();
return tags[ pos ];
}
int XmlStream::currentToken() const
{
if( pos >= tags.size())
return XML_TOKEN_INVALID;
return tags[ pos ].token;
}
void XmlStream::moveToNextTag()
{
if( pos < tags.size())
++pos;
}
XmlStream::Tag XmlStream::ensureOpeningTag( int token )
{
return checkTag( OPENING( token ), false );
}
XmlStream::Tag XmlStream::checkOpeningTag( int token )
{
return checkTag( OPENING( token ), true );
}
void XmlStream::ensureClosingTag( int token )
{
checkTag( CLOSING( token ), false );
}
XmlStream::Tag XmlStream::checkTag( int token, bool optional )
{
// either it's the following tag, or find it
int savedPos = pos;
if( optional )
{ // avoid printing debug messages about skipping tags if the optional one
// will not be found and the position will be reset back
if( currentToken() != token && !findTagInternal( token, true ))
{
pos = savedPos;
return Tag();
}
}
if( currentToken() == token || findTag( token ))
{
Tag ret = currentTag();
moveToNextTag();
return ret; // ok
}
if( optional )
{ // not a problem, just rewind
pos = savedPos;
return Tag();
}
SAL_WARN( "oox.xmlstream", "Expected tag " << tokenToString( token ) << " not found." );
return Tag();
}
bool XmlStream::findTag( int token )
{
return findTagInternal( token, false );
}
bool XmlStream::findTagInternal( int token, bool silent )
{
int depth = 0;
for(;
!atEnd();
moveToNextTag())
{
if( depth > 0 ) // we're inside a nested element, skip those
{
if( currentToken() == OPENING( currentToken()))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping tag " << tokenToString( currentToken()));
++depth;
}
else if( currentToken() == CLOSING( currentToken()))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping tag " << tokenToString( currentToken()));
--depth;
}
else
{
if( !silent )
SAL_WARN( "oox.xmlstream", "Malformed token " << currentToken() << " ("
<< tokenToString( currentToken()) << ")" );
abort();
}
continue;
}
if( currentToken() == token )
return true; // ok, found
if( currentToken() == CLOSING( currentToken()))
return false; // that would be leaving current element, so not found
if( currentToken() == OPENING( currentToken()))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping tag " << tokenToString( currentToken()));
++depth;
}
else
abort();
}
if( !silent )
SAL_WARN( "oox.xmlstream", "Unexpected end of stream reached." );
return false;
}
void XmlStream::skipElementInternal( int token, bool silent )
{
int closing = ( token & ~TAG_OPENING ) | TAG_CLOSING; // make it a closing tag
assert( currentToken() == OPENING( token ));
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping unexpected element " << tokenToString( currentToken()));
moveToNextTag();
// and just find the matching closing tag
if( findTag( closing ))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipped unexpected element " << tokenToString( token ));
moveToNextTag(); // and skip it too
return;
}
// this one is an unexpected problem, do not silent it
SAL_WARN( "oox.xmlstream", "Expected end of element " << tokenToString( token ) << " not found." );
}
void XmlStream::handleUnexpectedTag()
{
if( atEnd())
return;
if( currentToken() == CLOSING( currentToken()))
{
SAL_INFO( "oox.xmlstream", "Skipping unexpected tag " << tokenToString( currentToken()));
moveToNextTag(); // just skip it
return;
}
skipElementInternal( currentToken(), false ); // otherwise skip the entire element
}
void XmlStreamBuilder::appendOpeningTag( int token, const uno::Reference< xml::sax::XFastAttributeList >& attrs )
{
tags.push_back( Tag( OPENING( token ), attrs ));
}
void XmlStreamBuilder::appendOpeningTag( int token, const AttributeList& attrs )
{
tags.push_back( Tag( OPENING( token ), attrs ));
}
void XmlStreamBuilder::appendClosingTag( int token )
{
tags.push_back( Tag( CLOSING( token )));
}
void XmlStreamBuilder::appendCharacters( const rtl::OUString& chars )
{
assert( !tags.empty());
tags.back().text += chars;
}
} // namespace
} // namespace
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>String cleanup in oox<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2011 Tor Lillqvist <[email protected]> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "oox/mathml/importutils.hxx"
#include <assert.h>
#include <stdio.h>
#include <oox/token/namespacemap.hxx>
#include <oox/token/tokenmap.hxx>
#include <oox/token/tokens.hxx>
#include <oox/token/namespaces.hxx>
#include <rtl/ustring.hxx>
#define OPENING( token ) XML_STREAM_OPENING( token )
#define CLOSING( token ) XML_STREAM_CLOSING( token )
using namespace com::sun::star;
namespace oox
{
namespace formulaimport
{
namespace
{
// a class that inherits from AttributeList, builds the internal data and then will be sliced off
// during conversion to the base class
class AttributeListBuilder
: public XmlStream::AttributeList
{
public:
AttributeListBuilder( const uno::Reference< xml::sax::XFastAttributeList >& a );
};
AttributeListBuilder::AttributeListBuilder( const uno::Reference< xml::sax::XFastAttributeList >& a )
{
if( a.get() == NULL )
return;
uno::Sequence< xml::FastAttribute > aFastAttrSeq = a->getFastAttributes();
const xml::FastAttribute* pFastAttr = aFastAttrSeq.getConstArray();
sal_Int32 nFastAttrLength = aFastAttrSeq.getLength();
for( int i = 0;
i < nFastAttrLength;
++i )
{
attrs[ pFastAttr[ i ].Token ] = pFastAttr[ i ].Value;
}
}
static OUString tokenToString( int token )
{
OUString tokenname = StaticTokenMap::get().getUnicodeTokenName( token & TOKEN_MASK );
if( tokenname.isEmpty())
tokenname = "???";
int nmsp = ( token & NMSP_MASK & ~( TAG_OPENING | TAG_CLOSING ));
#if 0 // this is awfully long
OUString namespacename = StaticNamespaceMap::get().count( nmsp ) != 0
? StaticNamespaceMap::get()[ nmsp ] : OUString( "???" );
#else
OUString namespacename;
// only few are needed actually
switch( nmsp )
{
case NMSP_officeMath:
namespacename = "m";
break;
case NMSP_doc:
namespacename = "w";
break;
default:
namespacename = "?";
break;
}
#endif
if( token == OPENING( token ))
return "<" + namespacename + ":" + tokenname + ">";
if( token == CLOSING( token ))
return "</" + namespacename + ":" + tokenname + ">";
// just the name itself, not specified whether opening or closing
return namespacename + ":" + tokenname;
}
} // namespace
OUString& XmlStream::AttributeList::operator[] (int token)
{
return attrs[token];
}
rtl::OUString XmlStream::AttributeList::attribute( int token, const rtl::OUString& def ) const
{
std::map< int, OUString >::const_iterator find = attrs.find( token );
if( find != attrs.end())
return find->second;
return def;
}
bool XmlStream::AttributeList::attribute( int token, bool def ) const
{
std::map< int, OUString >::const_iterator find = attrs.find( token );
if( find != attrs.end())
{
const OUString sValue = find->second;
if( sValue.equalsIgnoreAsciiCaseAscii("true") ||
sValue.equalsIgnoreAsciiCaseAscii("on") ||
sValue.equalsIgnoreAsciiCaseAscii("t") ||
sValue.equalsIgnoreAsciiCaseAscii("1") )
return true;
if( sValue.equalsIgnoreAsciiCaseAscii("false") ||
sValue.equalsIgnoreAsciiCaseAscii("off") ||
sValue.equalsIgnoreAsciiCaseAscii("f") ||
sValue.equalsIgnoreAsciiCaseAscii("0") )
return false;
SAL_WARN( "oox.xmlstream", "Cannot convert \'" << sValue << "\' to bool." );
}
return def;
}
sal_Unicode XmlStream::AttributeList::attribute( int token, sal_Unicode def ) const
{
std::map< int, OUString >::const_iterator find = attrs.find( token );
if( find != attrs.end())
{
if( !find->second.isEmpty() )
{
if( find->second.getLength() != 1 )
SAL_WARN( "oox.xmlstream", "Cannot convert \'" << find->second << "\' to sal_Unicode, stripping." );
return find->second[ 0 ];
}
}
return def;
}
XmlStream::Tag::Tag( int t, const uno::Reference< xml::sax::XFastAttributeList >& a, const rtl::OUString& txt )
: token( t )
, attributes( AttributeListBuilder( a ))
, text( txt )
{
}
XmlStream::Tag::Tag( int t, const AttributeList& a )
: token( t )
, attributes( a )
{
}
XmlStream::Tag::operator bool() const
{
return token != XML_TOKEN_INVALID;
}
XmlStream::XmlStream()
: pos( 0 )
{
// make sure our extra bit does not conflict with values used by oox
assert( TAG_OPENING > ( 1024 << NMSP_SHIFT ));
}
bool XmlStream::atEnd() const
{
return pos >= tags.size();
}
XmlStream::Tag XmlStream::currentTag() const
{
if( pos >= tags.size())
return Tag();
return tags[ pos ];
}
int XmlStream::currentToken() const
{
if( pos >= tags.size())
return XML_TOKEN_INVALID;
return tags[ pos ].token;
}
void XmlStream::moveToNextTag()
{
if( pos < tags.size())
++pos;
}
XmlStream::Tag XmlStream::ensureOpeningTag( int token )
{
return checkTag( OPENING( token ), false );
}
XmlStream::Tag XmlStream::checkOpeningTag( int token )
{
return checkTag( OPENING( token ), true );
}
void XmlStream::ensureClosingTag( int token )
{
checkTag( CLOSING( token ), false );
}
XmlStream::Tag XmlStream::checkTag( int token, bool optional )
{
// either it's the following tag, or find it
int savedPos = pos;
if( optional )
{ // avoid printing debug messages about skipping tags if the optional one
// will not be found and the position will be reset back
if( currentToken() != token && !findTagInternal( token, true ))
{
pos = savedPos;
return Tag();
}
}
if( currentToken() == token || findTag( token ))
{
Tag ret = currentTag();
moveToNextTag();
return ret; // ok
}
if( optional )
{ // not a problem, just rewind
pos = savedPos;
return Tag();
}
SAL_WARN( "oox.xmlstream", "Expected tag " << tokenToString( token ) << " not found." );
return Tag();
}
bool XmlStream::findTag( int token )
{
return findTagInternal( token, false );
}
bool XmlStream::findTagInternal( int token, bool silent )
{
int depth = 0;
for(;
!atEnd();
moveToNextTag())
{
if( depth > 0 ) // we're inside a nested element, skip those
{
if( currentToken() == OPENING( currentToken()))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping tag " << tokenToString( currentToken()));
++depth;
}
else if( currentToken() == CLOSING( currentToken()))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping tag " << tokenToString( currentToken()));
--depth;
}
else
{
if( !silent )
SAL_WARN( "oox.xmlstream", "Malformed token " << currentToken() << " ("
<< tokenToString( currentToken()) << ")" );
abort();
}
continue;
}
if( currentToken() == token )
return true; // ok, found
if( currentToken() == CLOSING( currentToken()))
return false; // that would be leaving current element, so not found
if( currentToken() == OPENING( currentToken()))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping tag " << tokenToString( currentToken()));
++depth;
}
else
abort();
}
if( !silent )
SAL_WARN( "oox.xmlstream", "Unexpected end of stream reached." );
return false;
}
void XmlStream::skipElementInternal( int token, bool silent )
{
int closing = ( token & ~TAG_OPENING ) | TAG_CLOSING; // make it a closing tag
assert( currentToken() == OPENING( token ));
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipping unexpected element " << tokenToString( currentToken()));
moveToNextTag();
// and just find the matching closing tag
if( findTag( closing ))
{
if( !silent )
SAL_INFO( "oox.xmlstream", "Skipped unexpected element " << tokenToString( token ));
moveToNextTag(); // and skip it too
return;
}
// this one is an unexpected problem, do not silent it
SAL_WARN( "oox.xmlstream", "Expected end of element " << tokenToString( token ) << " not found." );
}
void XmlStream::handleUnexpectedTag()
{
if( atEnd())
return;
if( currentToken() == CLOSING( currentToken()))
{
SAL_INFO( "oox.xmlstream", "Skipping unexpected tag " << tokenToString( currentToken()));
moveToNextTag(); // just skip it
return;
}
skipElementInternal( currentToken(), false ); // otherwise skip the entire element
}
void XmlStreamBuilder::appendOpeningTag( int token, const uno::Reference< xml::sax::XFastAttributeList >& attrs )
{
tags.push_back( Tag( OPENING( token ), attrs ));
}
void XmlStreamBuilder::appendOpeningTag( int token, const AttributeList& attrs )
{
tags.push_back( Tag( OPENING( token ), attrs ));
}
void XmlStreamBuilder::appendClosingTag( int token )
{
tags.push_back( Tag( CLOSING( token )));
}
void XmlStreamBuilder::appendCharacters( const rtl::OUString& chars )
{
assert( !tags.empty());
tags.back().text += chars;
}
} // namespace
} // namespace
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// $Id: fe_clough.C,v 1.2 2005-02-22 22:17:36 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "fe.h"
#include "elem.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
switch (order)
{
// Piecewise cubic shape functions only
case THIRD:
{
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, order);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
return;
}
default:
{
error();
}
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
switch (o)
{
// Piecewise cubic Clough-Tocher element
case THIRD:
{
switch (t)
{
case TRI6:
return 12;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
switch (o)
{
// The third-order hierarchic shape functions
case THIRD:
{
switch (t)
{
// The 2D Clough-Tocher defined on a 6-noded triangle
case TRI6:
{
switch (n)
{
case 0:
case 1:
case 2:
return 3;
case 3:
case 4:
case 5:
return 1;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
switch (o)
{
// The third-order Clough-Tocher shape functions
case THIRD:
{
switch (t)
{
// The 2D hierarchic defined on a 6-noded triangle
case TRI6:
return 0;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
// Otherwise no DOFS per element
default:
error();
return 0;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (std::map<unsigned int,
std::map<unsigned int,
float> > &,
const unsigned int,
const unsigned int,
const FEType&,
const Elem*)
{
std::cerr << "ERROR: Not yet implemented for Clough-Tocher!"
<< std::endl;
error();
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiations
template class FE<1,CLOUGH>; // FIXME: 1D Not yet functional!
template class FE<2,CLOUGH>;
template class FE<3,CLOUGH>; // FIXME: 2D Not yet functional!
<commit_msg><commit_after>// $Id: fe_clough.C,v 1.3 2005-02-23 03:42:16 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson,
// Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "dense_matrix.h"
#include "dense_vector.h"
#include "dof_map.h"
#include "elem.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
// ------------------------------------------------------------
// Hierarchic-specific implementations
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::nodal_soln(const Elem* elem,
const Order order,
const std::vector<Number>& elem_soln,
std::vector<Number>& nodal_soln)
{
const unsigned int n_nodes = elem->n_nodes();
const ElemType type = elem->type();
nodal_soln.resize(n_nodes);
switch (order)
{
// Piecewise cubic shape functions only
case THIRD:
{
const unsigned int n_sf =
FE<Dim,T>::n_shape_functions(type, order);
for (unsigned int n=0; n<n_nodes; n++)
{
const Point mapped_point = FE<Dim,T>::inverse_map(elem,
elem->point(n));
assert (elem_soln.size() == n_sf);
// Zero before summation
nodal_soln[n] = 0;
// u_i = Sum (alpha_i phi_i)
for (unsigned int i=0; i<n_sf; i++)
nodal_soln[n] += elem_soln[i]*FE<Dim,T>::shape(elem,
order,
i,
mapped_point);
}
return;
}
default:
{
error();
}
}
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs(const ElemType t, const Order o)
{
switch (o)
{
// Piecewise cubic Clough-Tocher element
case THIRD:
{
switch (t)
{
case TRI6:
return 12;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_at_node(const ElemType t,
const Order o,
const unsigned int n)
{
switch (o)
{
// The third-order hierarchic shape functions
case THIRD:
{
switch (t)
{
// The 2D Clough-Tocher defined on a 6-noded triangle
case TRI6:
{
switch (n)
{
case 0:
case 1:
case 2:
return 3;
case 3:
case 4:
case 5:
return 1;
default:
error();
}
}
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
default:
{
error();
}
}
error();
return 0;
}
template <unsigned int Dim, FEFamily T>
unsigned int FE<Dim,T>::n_dofs_per_elem(const ElemType t,
const Order o)
{
switch (o)
{
// The third-order Clough-Tocher shape functions
case THIRD:
{
switch (t)
{
// The 2D hierarchic defined on a 6-noded triangle
case TRI6:
return 0;
default:
{
#ifdef DEBUG
std::cerr << "ERROR: Bad ElemType = " << t
<< " for " << o << "th order approximation!"
<< std::endl;
#endif
error();
}
}
}
// Otherwise no DOFS per element
default:
error();
return 0;
}
}
template <unsigned int Dim, FEFamily T>
void FE<Dim,T>::compute_constraints (std::map<unsigned int,
std::map<unsigned int, float> > &
constraints,
DofMap &dof_map,
const unsigned int variable_number,
const Elem* elem)
{
// Only constrain elements in 2,3D.
if (Dim == 1)
return;
assert (elem != NULL);
const FEType& fe_type = dof_map.variable_type(variable_number);
AutoPtr<FEBase> my_fe (FEBase::build(Dim, fe_type));
AutoPtr<FEBase> parent_fe (FEBase::build(Dim, fe_type));
QClough my_qface(Dim-1, fe_type.default_quadrature_order());
my_fe->attach_quadrature_rule (&my_qface);
std::vector<Point> parent_qface;
const std::vector<Real>& JxW = my_fe->get_JxW();
const std::vector<Point>& q_point = my_fe->get_xyz();
const std::vector<std::vector<Real> >& phi = my_fe->get_phi();
const std::vector<std::vector<Real> >& parent_phi =
parent_fe->get_phi();
const std::vector<Point>& face_normals = my_fe->get_normals();
const std::vector<std::vector<RealGradient> >& dphi =
my_fe->get_dphi();
const std::vector<std::vector<RealGradient> >& parent_dphi =
parent_fe->get_dphi();
const std::vector<unsigned int> child_dof_indices;
const std::vector<unsigned int> parent_dof_indices;
DenseMatrix<Number> Ke;
DenseVector<Number> Fe;
std::vector<DenseVector<Number> > Ue;
// Look at the element faces. Check to see if we need to
// build constraints.
for (unsigned int s=0; s<elem->n_sides(); s++)
if (elem->neighbor(s) != NULL)
// constrain dofs shared between
// this element and ones coarser
// than this element.
if (elem->neighbor(s)->level() < elem->level())
{
// FIXME: hanging nodes aren't working yet!
std::cerr << "Error: hanging nodes not yet implemented for "
<< "Clough-Tocher elements!" << std::endl;
error();
// Get pointers to the elements of interest and its parent.
const Elem* parent = elem->parent();
// This can't happen... Only level-0 elements have NULL
// parents, and no level-0 elements can be at a higher
// level than their neighbors!
assert (parent != NULL);
my_fe->reinit(elem, s);
const AutoPtr<Elem> my_side (elem->build_side(s));
const AutoPtr<Elem> parent_side (parent->build_side(s));
const unsigned int n_dofs = FEInterface::n_dofs(Dim-1,
fe_type,
my_side->type());
assert(n_dofs == FEInterface::n_dofs(Dim-1, fe_type,
parent_side->type()));
const unsigned int n_qp = my_qface.n_points();
FEInterface::inverse_map (Dim, fe_type, parent, q_point,
parent_qface);
parent_fe->reinit(parent, &parent_qface);
Ke.resize (n_dofs, n_dofs);
Ue.resize(n_dofs);
for (unsigned int i = 0; i != n_dofs; ++i)
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Ke(i,j) += JxW[qp] * (phi[i][qp] * phi[j][qp] +
(dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
for (unsigned int i = 0; i != n_dofs; ++i)
{
Fe.resize (n_dofs);
for (unsigned int j = 0; j != n_dofs; ++j)
for (unsigned int qp = 0; qp != n_qp; ++qp)
Fe(j) += JxW[qp] * (parent_phi[i][qp] * phi[j][qp] +
(parent_dphi[i][qp] *
face_normals[qp]) *
(dphi[j][qp] *
face_normals[qp]));
Ke.cholesky_solve(Fe, Ue[i]);
}
}
}
template <unsigned int Dim, FEFamily T>
bool FE<Dim,T>::shapes_need_reinit() const
{
return true;
}
//--------------------------------------------------------------
// Explicit instantiations
template class FE<1,CLOUGH>; // FIXME: 1D Not yet functional!
template class FE<2,CLOUGH>;
template class FE<3,CLOUGH>; // FIXME: 2D Not yet functional!
<|endoftext|> |
<commit_before>// @(#)root/winnt:$Name$:$Id$
// Author: Valery Fine([email protected]) 29/09/98
#include <process.h>
#include "Windows4Root.h"
#include "TTimer.h"
#include "TROOT.h"
#include "TWin32Timer.h"
#include "TWin32HookViaThread.h"
#include "TGWin32Command.h"
#include "TInterpreter.h"
struct WIN32TIMETHREAD {
HANDLE ThrSem;
TWin32Timer *ti;
} ;
enum ETimerCallbackCmd {kCreateTimer, kKillTimer};
const Char_t *TIMERCLASS = "Timer";
//*-*
//*-* Macros to call the Callback methods via Timer thread:
//*-*
#define CallMethodThread(_function,_p1,_p2,_p3) \
else \
{ \
TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(_p3)); \
ExecTimerThread(&code); \
code.Wait(); \
}
#define ReturnMethodThread(_type,_function,_p1,_p2) \
else \
{ \
_type _local; \
TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(&_local)); \
ExecTimerThread(&code); \
code.Wait(); \
return _local; \
}
//*-*
#define CallWindowMethod1(_function,_p1) \
if ( IsTimeThread()) \
{TWin32Timer::_function(_p1);} \
CallMethodThread(_function,_p1,0,0)
//*-*
#define CallWindowMethod(_function) \
if ( IsTimeThread()) \
{TWin32Timer::_function();} \
CallMethodThread(_function,0,0,0)
//*-*
#define ReturnWindowMethod1(_type,_function,_p1) \
if ( IsTimeThread()) \
{return TWin32Timer::_function(_p1);} \
ReturnMethodThread(_type,_function,_p1,0)
//*-*
#define ReturnWindowMethod(_type,_function) \
if ( IsTimeThread()) \
{return TWin32Timer::_function();} \
ReturnMethodThread(_type,_function,0,0)
//______________________________________________________________________________
static VOID CALLBACK DispatchTimers(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//*-*
//*-* HWND hwnd, // handle of window for timer messages
//*-* UINT uMsg, // WM_TIMER message
//*-* UINT idEvent, // timer identifier (pointer to TTimer object)
//*-* DWORD dwTime // current system time
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TTimer *ti = (TTimer *)idEvent;
if (ti) {
if (ti->IsAsync())
ti->Notify();
else
gROOT->ProcessLine(Form("((TTimer *)0x%lx)->Notify();",(Long_t)ti));
}
}
//______________________________________________________________________________
static LRESULT APIENTRY WndTimer(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
//////////////////////////////////////////////////////////////////////////
// //
// Main Universal Windows procedure to manage all dispatched events //
// //
//////////////////////////////////////////////////////////////////////////
return ::DefWindowProc(hwnd, uMsg, wParam, lParam);
}
//______________________________________________________________________________
static unsigned int _stdcall ROOT_TimerLoop(void *threadcmd)
{
//---------------------------------------
// Create windows
HWND fhdTimerWindow = CreateWindowEx(NULL,
TIMERCLASS,
NULL, // address of window name
WS_DISABLED , // window style
0,0, // start positio of the window,
0, 0, // size of the window
NULL, // handle of parent of owner window
NULL, // handle of menu, or child-window identifier
GetModuleHandle(NULL), // handle of application instance
NULL); // address of window-creation data
HANDLE ThrSem = ((WIN32TIMETHREAD *)threadcmd)->ThrSem;
((WIN32TIMETHREAD *)threadcmd)->ti->SetHWND(fhdTimerWindow);
//---------------------------------------
MSG msg;
int erret; // GetMessage result
ReleaseSemaphore(ThrSem, 1, NULL);
Bool_t EventLoopStop = kFALSE;
// create timer
while(!EventLoopStop)
{
if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1))
continue;
if (msg.hwnd == NULL & (msg.message == ROOT_CMD || msg.message == ROOT_SYNCH_CMD))
if (TWin32HookViaThread::ExecuteEvent(&msg, msg.message==ROOT_SYNCH_CMD)) continue;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (erret == -1)
{
erret = GetLastError();
fprintf(stderr," *** Error **** TimerLoop: %d \n", erret);
}
if (msg.wParam) ReleaseSemaphore((HANDLE) msg.wParam, 1, NULL);
_endthreadex(0);
return 0;
} /* ROOT_MsgLoop */
//______________________________________________________________________________
TWin32Timer::TWin32Timer()
{
fhdTimerWindow = 0;
fhdTimerThread = 0;
fhdTimerThreadId = 0;
}
//______________________________________________________________________________
TWin32Timer::~TWin32Timer()
{
if (fhdTimerThreadId) {
PostThreadMessage(fhdTimerThreadId,WM_QUIT,0,0);
if (WaitForSingleObject(fhdTimerThread,10000)==WAIT_FAILED)
TerminateThread(fhdTimerThread, -1);
CloseHandle(fhdTimerThread);
}
}
//______________________________________________________________________________
Int_t TWin32Timer::CreateTimerThread()
{
// Register class "Timer"
HMODULE instance = GetModuleHandle(NULL);
static const WNDCLASS timerwindowclass = {
CS_GLOBALCLASS
, WndTimer
, 0, 0
, instance
, NULL, NULL, NULL, NULL
, TIMERCLASS};
WNDCLASSEX timerinfo;
if (GetClassInfoEx(instance,TIMERCLASS,&timerinfo))
return 0;
if (!RegisterClass( &timerwindowclass))
{
DWORD l_err = GetLastError();
printf(" Last Error is %d \n", l_err);
return -1;
}
WIN32TIMETHREAD threadcmd;
//
// Create thread to do the cmd loop
//
threadcmd.ThrSem = CreateSemaphore(NULL, 0, 1, NULL);
threadcmd.ti = this;
// fhdTimerThread = (HANDLE)_beginthreadex(NULL,0, ROOT_TimerLoop,
fhdTimerThread = (unsigned long *) _beginthreadex(NULL,0, ROOT_TimerLoop,
(LPVOID) &threadcmd, 0, ((unsigned *)&fhdTimerThreadId));
if (Int_t(fhdTimerThread) == -1){
int erret = GetLastError();
printf(" *** Error *** CreatTimerThread <Thread was not created> %d \n", erret);
}
WaitForSingleObject(threadcmd.ThrSem, INFINITE);
CloseHandle(threadcmd.ThrSem);
return 0;
}
//______________________________________________________________________________
UInt_t TWin32Timer::CreateTimer(TTimer *timer)
{
if(!fhdTimerThreadId) CreateTimerThread();
CallWindowMethod1(CreateTimer,timer);
return 0;
}
//______________________________________________________________________________
void TWin32Timer::CreateTimerCB(TTimer *timer)
{
if (timer)
timer->SetTimerID((UInt_t)(::SetTimer(fhdTimerWindow,(UINT)timer,timer->GetTime()
, (TIMERPROC) ::DispatchTimers)) );
}
//______________________________________________________________________________
void TWin32Timer::ExecTimerThread(TGWin32Command *command)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-* Execute command via "Timer" thread
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Some extra flag is needed to mark the command = 0 turn !!!
TGWin32Command *code = command;
if (!code) code = new TWin32SendClass(this);
fSendFlag = 1;
int i = ExecCommand(code,kFALSE);
}
//______________________________________________________________________________
Bool_t TWin32Timer::ExecCommand(TGWin32Command *command,Bool_t synch)
{
// To exec a command coming from the other threads
BOOL postresult;
ERoot_Msgs cmd = ROOT_CMD;
if (fhdTimerThreadId == GetCurrentThreadId())
printf("TWin32Timer::ExecCommand --- > The dead lock danger\n");
if (synch) cmd = ROOT_SYNCH_CMD;
while (!(postresult = PostThreadMessage(fhdTimerThreadId,
cmd,
(WPARAM)command->GetCOP(),
(LPARAM)command))
){ ; }
return postresult;
}
//______________________________________________________________________________
Bool_t TWin32Timer::IsTimeThread(){
return fhdTimerThreadId == GetCurrentThreadId();
}
//______________________________________________________________________________
void TWin32Timer::KillTimer(TTimer *timer)
{
CallWindowMethod1(KillTimer,timer);
}
//______________________________________________________________________________
void TWin32Timer::KillTimerCB(TTimer *timer)
{
if(timer) {
// ::KillTimer(NULL,timer->GetTimerID());
::KillTimer(fhdTimerWindow,(UINT)timer);
timer->SetTimerID(0);
}
}
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* Callback methods:
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//______________________________________________________________________________
void TWin32Timer::ExecThreadCB(TWin32SendClass *command)
{
ETimerCallbackCmd cmd = (ETimerCallbackCmd)(command->GetData(0));
Bool_t debug = kFALSE;
char *listcmd[] = {
"CreateTimer"
,"KillTimer"
};
if (gDebug) printf("TWin32Timer: commamd %d: %s",cmd,listcmd[cmd]);
switch (cmd)
{
case kCreateTimer:
{
TTimer *ti = (TTimer *)(command->GetData(1));
if (gDebug) printf(" %lx ", (Long_t)ti);
CreateTimerCB(ti);
break;
}
case kKillTimer:
{
TTimer *ti = (TTimer *)(command->GetData(1));
if (gDebug) printf(" %lx ", (Long_t)ti);
KillTimerCB(ti);
break;
}
default:
break;
}
if (gDebug) printf(" \n");
if (LOWORD(command->GetCOP()) == kSendWaitClass)
((TWin32SendWaitClass *)command)->Release();
else
delete command;
}
<commit_msg>Fix a bug (thanks Axel Naumann) in ROOT_TimerLoop. Statement: if (msg.hwnd == NULL &(msg.message == ROOT_CMD || msg.message ... should be if (msg.hwnd == NULL && (msg.message == ROOT_CMD || msg.message...<commit_after>// @(#)root/winnt:$Name: $:$Id: TWin32Timer.cxx,v 1.1.1.1 2000/05/16 17:00:46 rdm Exp $
// Author: Valery Fine([email protected]) 29/09/98
#include <process.h>
#include "Windows4Root.h"
#include "TTimer.h"
#include "TROOT.h"
#include "TWin32Timer.h"
#include "TWin32HookViaThread.h"
#include "TGWin32Command.h"
#include "TInterpreter.h"
struct WIN32TIMETHREAD {
HANDLE ThrSem;
TWin32Timer *ti;
} ;
enum ETimerCallbackCmd {kCreateTimer, kKillTimer};
const Char_t *TIMERCLASS = "Timer";
//*-*
//*-* Macros to call the Callback methods via Timer thread:
//*-*
#define CallMethodThread(_function,_p1,_p2,_p3) \
else \
{ \
TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(_p3)); \
ExecTimerThread(&code); \
code.Wait(); \
}
#define ReturnMethodThread(_type,_function,_p1,_p2) \
else \
{ \
_type _local; \
TWin32SendWaitClass code(this,(UInt_t)k##_function,(UInt_t)(_p1),(UInt_t)(_p2),(UInt_t)(&_local)); \
ExecTimerThread(&code); \
code.Wait(); \
return _local; \
}
//*-*
#define CallWindowMethod1(_function,_p1) \
if ( IsTimeThread()) \
{TWin32Timer::_function(_p1);} \
CallMethodThread(_function,_p1,0,0)
//*-*
#define CallWindowMethod(_function) \
if ( IsTimeThread()) \
{TWin32Timer::_function();} \
CallMethodThread(_function,0,0,0)
//*-*
#define ReturnWindowMethod1(_type,_function,_p1) \
if ( IsTimeThread()) \
{return TWin32Timer::_function(_p1);} \
ReturnMethodThread(_type,_function,_p1,0)
//*-*
#define ReturnWindowMethod(_type,_function) \
if ( IsTimeThread()) \
{return TWin32Timer::_function();} \
ReturnMethodThread(_type,_function,0,0)
//______________________________________________________________________________
static VOID CALLBACK DispatchTimers(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
//*-*
//*-* HWND hwnd, // handle of window for timer messages
//*-* UINT uMsg, // WM_TIMER message
//*-* UINT idEvent, // timer identifier (pointer to TTimer object)
//*-* DWORD dwTime // current system time
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
TTimer *ti = (TTimer *)idEvent;
if (ti) {
if (ti->IsAsync())
ti->Notify();
else
gROOT->ProcessLine(Form("((TTimer *)0x%lx)->Notify();",(Long_t)ti));
}
}
//______________________________________________________________________________
static LRESULT APIENTRY WndTimer(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
//////////////////////////////////////////////////////////////////////////
// //
// Main Universal Windows procedure to manage all dispatched events //
// //
//////////////////////////////////////////////////////////////////////////
return ::DefWindowProc(hwnd, uMsg, wParam, lParam);
}
//______________________________________________________________________________
static unsigned int _stdcall ROOT_TimerLoop(void *threadcmd)
{
//---------------------------------------
// Create windows
HWND fhdTimerWindow = CreateWindowEx(NULL,
TIMERCLASS,
NULL, // address of window name
WS_DISABLED , // window style
0,0, // start positio of the window,
0, 0, // size of the window
NULL, // handle of parent of owner window
NULL, // handle of menu, or child-window identifier
GetModuleHandle(NULL), // handle of application instance
NULL); // address of window-creation data
HANDLE ThrSem = ((WIN32TIMETHREAD *)threadcmd)->ThrSem;
((WIN32TIMETHREAD *)threadcmd)->ti->SetHWND(fhdTimerWindow);
//---------------------------------------
MSG msg;
int erret; // GetMessage result
ReleaseSemaphore(ThrSem, 1, NULL);
Bool_t EventLoopStop = kFALSE;
// create timer
while(!EventLoopStop)
{
if (EventLoopStop = (!(erret=GetMessage(&msg,NULL,0,0)) || erret == -1))
continue;
if (msg.hwnd == NULL && (msg.message == ROOT_CMD || msg.message == ROOT_SYNCH_CMD))
if (TWin32HookViaThread::ExecuteEvent(&msg, msg.message==ROOT_SYNCH_CMD)) continue;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (erret == -1)
{
erret = GetLastError();
fprintf(stderr," *** Error **** TimerLoop: %d \n", erret);
}
if (msg.wParam) ReleaseSemaphore((HANDLE) msg.wParam, 1, NULL);
_endthreadex(0);
return 0;
} /* ROOT_MsgLoop */
//______________________________________________________________________________
TWin32Timer::TWin32Timer()
{
fhdTimerWindow = 0;
fhdTimerThread = 0;
fhdTimerThreadId = 0;
}
//______________________________________________________________________________
TWin32Timer::~TWin32Timer()
{
if (fhdTimerThreadId) {
PostThreadMessage(fhdTimerThreadId,WM_QUIT,0,0);
if (WaitForSingleObject(fhdTimerThread,10000)==WAIT_FAILED)
TerminateThread(fhdTimerThread, -1);
CloseHandle(fhdTimerThread);
}
}
//______________________________________________________________________________
Int_t TWin32Timer::CreateTimerThread()
{
// Register class "Timer"
HMODULE instance = GetModuleHandle(NULL);
static const WNDCLASS timerwindowclass = {
CS_GLOBALCLASS
, WndTimer
, 0, 0
, instance
, NULL, NULL, NULL, NULL
, TIMERCLASS};
WNDCLASSEX timerinfo;
if (GetClassInfoEx(instance,TIMERCLASS,&timerinfo))
return 0;
if (!RegisterClass( &timerwindowclass))
{
DWORD l_err = GetLastError();
printf(" Last Error is %d \n", l_err);
return -1;
}
WIN32TIMETHREAD threadcmd;
//
// Create thread to do the cmd loop
//
threadcmd.ThrSem = CreateSemaphore(NULL, 0, 1, NULL);
threadcmd.ti = this;
// fhdTimerThread = (HANDLE)_beginthreadex(NULL,0, ROOT_TimerLoop,
fhdTimerThread = (unsigned long *) _beginthreadex(NULL,0, ROOT_TimerLoop,
(LPVOID) &threadcmd, 0, ((unsigned *)&fhdTimerThreadId));
if (Int_t(fhdTimerThread) == -1){
int erret = GetLastError();
printf(" *** Error *** CreatTimerThread <Thread was not created> %d \n", erret);
}
WaitForSingleObject(threadcmd.ThrSem, INFINITE);
CloseHandle(threadcmd.ThrSem);
return 0;
}
//______________________________________________________________________________
UInt_t TWin32Timer::CreateTimer(TTimer *timer)
{
if(!fhdTimerThreadId) CreateTimerThread();
CallWindowMethod1(CreateTimer,timer);
return 0;
}
//______________________________________________________________________________
void TWin32Timer::CreateTimerCB(TTimer *timer)
{
if (timer)
timer->SetTimerID((UInt_t)(::SetTimer(fhdTimerWindow,(UINT)timer,timer->GetTime()
, (TIMERPROC) ::DispatchTimers)) );
}
//______________________________________________________________________________
void TWin32Timer::ExecTimerThread(TGWin32Command *command)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-* Execute command via "Timer" thread
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
// Some extra flag is needed to mark the command = 0 turn !!!
TGWin32Command *code = command;
if (!code) code = new TWin32SendClass(this);
fSendFlag = 1;
int i = ExecCommand(code,kFALSE);
}
//______________________________________________________________________________
Bool_t TWin32Timer::ExecCommand(TGWin32Command *command,Bool_t synch)
{
// To exec a command coming from the other threads
BOOL postresult;
ERoot_Msgs cmd = ROOT_CMD;
if (fhdTimerThreadId == GetCurrentThreadId())
printf("TWin32Timer::ExecCommand --- > The dead lock danger\n");
if (synch) cmd = ROOT_SYNCH_CMD;
while (!(postresult = PostThreadMessage(fhdTimerThreadId,
cmd,
(WPARAM)command->GetCOP(),
(LPARAM)command))
){ ; }
return postresult;
}
//______________________________________________________________________________
Bool_t TWin32Timer::IsTimeThread(){
return fhdTimerThreadId == GetCurrentThreadId();
}
//______________________________________________________________________________
void TWin32Timer::KillTimer(TTimer *timer)
{
CallWindowMethod1(KillTimer,timer);
}
//______________________________________________________________________________
void TWin32Timer::KillTimerCB(TTimer *timer)
{
if(timer) {
// ::KillTimer(NULL,timer->GetTimerID());
::KillTimer(fhdTimerWindow,(UINT)timer);
timer->SetTimerID(0);
}
}
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* Callback methods:
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//______________________________________________________________________________
void TWin32Timer::ExecThreadCB(TWin32SendClass *command)
{
ETimerCallbackCmd cmd = (ETimerCallbackCmd)(command->GetData(0));
Bool_t debug = kFALSE;
char *listcmd[] = {
"CreateTimer"
,"KillTimer"
};
if (gDebug) printf("TWin32Timer: commamd %d: %s",cmd,listcmd[cmd]);
switch (cmd)
{
case kCreateTimer:
{
TTimer *ti = (TTimer *)(command->GetData(1));
if (gDebug) printf(" %lx ", (Long_t)ti);
CreateTimerCB(ti);
break;
}
case kKillTimer:
{
TTimer *ti = (TTimer *)(command->GetData(1));
if (gDebug) printf(" %lx ", (Long_t)ti);
KillTimerCB(ti);
break;
}
default:
break;
}
if (gDebug) printf(" \n");
if (LOWORD(command->GetCOP()) == kSendWaitClass)
((TWin32SendWaitClass *)command)->Release();
else
delete command;
}
<|endoftext|> |
<commit_before>//
// Created by yanxq on 17/6/10.
//
#include <string>
#include <fcntl.h>
#include <elf.h>
#include "elfhook_utils.h"
#include "elf_log.h"
static inline Elf32_Phdr* find_segment_by_type(Elf32_Phdr * phdr_base, const Elf32_Word phnum, const Elf32_Word ph_type) {
Elf32_Phdr *target = NULL;
for (int i = 0; i < phnum; ++i) {
if ((phdr_base + i)->p_type == ph_type) {
target = phdr_base + i;
break;
}
}
return target;
}
static inline Elf32_Addr * find_symbol_offset(const char *symbol,
Elf32_Rel *rel_base_ptr,Elf32_Word size,
const char *strtab_base,Elf32_Sym *symtab_ptr) {
Elf32_Rel *each_rel = rel_base_ptr;
for (int i = 0; i < size; i++,each_rel++) {
uint16_t ndx = ELF32_R_SYM(each_rel->r_info);
if (ndx == 0) continue;
LOGI("ndx = %d, str = %s", ndx, strtab_base + symtab_ptr[ndx].st_name);
if (strcmp(strtab_base + symtab_ptr[ndx].st_name, symbol) == 0) {
LOGI("符号%s在got表的偏移地址为: 0x%x", symbol, each_rel->r_offset);
return &each_rel->r_offset;
}
}
return NULL;
}
int elfhook_p(const char *so_name,const char *symbol, void *new_func_addr,void **origin_func_addr_ptr) {
uint8_t * elf_base_address = (uint8_t *) find_so_base(so_name, NULL,0);
Elf32_Ehdr *endr = reinterpret_cast<Elf32_Ehdr*>(elf_base_address);
Elf32_Phdr *phdr_base = reinterpret_cast<Elf32_Phdr*>(elf_base_address + endr->e_phoff);
Elf32_Phdr *dynamic_phdr = find_segment_by_type(phdr_base,endr->e_phnum,PT_DYNAMIC);
Elf32_Dyn *dyn_ptr_base = reinterpret_cast<Elf32_Dyn *>(elf_base_address + dynamic_phdr->p_vaddr);
Elf32_Word dynamic_size = dynamic_phdr -> p_memsz;
Elf32_Word dyn_count = dynamic_size / sizeof(Elf32_Dyn);
Elf32_Sym *symtab_ptr = NULL;
const char * strtab_base = NULL;
Elf32_Rel *rel_dyn_ptr_base = NULL;
Elf32_Word rel_dyn_count;
Elf32_Rel *rel_plt_base = NULL;
Elf32_Word rel_plt_count;
Elf32_Word current_find_count = 0;
Elf32_Dyn * each_dyn = dyn_ptr_base;
for (int i = 0; i < dyn_count; ++i,++each_dyn) {
switch (each_dyn->d_tag) {
case DT_SYMTAB:
symtab_ptr = reinterpret_cast<Elf32_Sym *>(elf_base_address + each_dyn->d_un.d_ptr);
current_find_count ++;
break;
case DT_STRTAB:
current_find_count ++;
strtab_base = reinterpret_cast<const char *>(elf_base_address + each_dyn->d_un.d_ptr);
break;
case DT_REL:
current_find_count ++;
rel_dyn_ptr_base = reinterpret_cast<Elf32_Rel *>(elf_base_address + each_dyn->d_un.d_ptr);
break;
case DT_RELASZ:
current_find_count ++;
rel_dyn_count = each_dyn->d_un.d_ptr / sizeof(Elf32_Rel);
break;
case DT_JMPREL:
current_find_count ++;
rel_plt_base = reinterpret_cast<Elf32_Rel *>(elf_base_address + each_dyn->d_un.d_ptr);
break;
case DT_PLTRELSZ:
current_find_count ++;
rel_plt_count = each_dyn->d_un.d_ptr / sizeof(Elf32_Rel);
break;
default:
break;
}
if (current_find_count == 5) {
break;
}
}
Elf32_Addr *offset = find_symbol_offset(symbol, rel_plt_base, rel_plt_count,
strtab_base,symtab_ptr);
if (offset == NULL) {
LOGI(".rel.plt 查找符号失败,在 .rel.dyn 尝试查找...");
offset = find_symbol_offset(symbol,rel_dyn_ptr_base,rel_dyn_count,
strtab_base,symtab_ptr);
}
if (offset == NULL) {
LOGE("获取 Offset 失败!!!");
return 0;
}
LOGI("符号获取成功,进行符号地址修改...");
void * function_addr_ptr = (elf_base_address + *offset);
return replace_function((void **) function_addr_ptr,
new_func_addr, origin_func_addr_ptr);
}
static inline void read_data_form_fd(int fd, uint32_t seek,void * ptr, size_t size) {
lseek(fd, seek, SEEK_SET);
read(fd, ptr, size);
}
static inline Elf32_Word *find_symbol_offset(int fd,const char *symbol,
Elf32_Rel *rel_base_ptr,Elf32_Word size,
const char *strtab_base,Elf32_Sym *symtab_ptr) {
Elf32_Rel *each_rel = rel_base_ptr;
for (uint16_t i = 0; i < size; i++) {
uint16_t ndx = ELF32_R_SYM(each_rel->r_info);
if (ndx > 0) {
LOGI("ndx = %d, str = %s", ndx, strtab_base + symtab_ptr[ndx].st_name);
if (strcmp(strtab_base + symtab_ptr[ndx].st_name, symbol) == 0) {
LOGI("符号%s在got表的偏移地址为: 0x%x", symbol, each_rel->r_offset);
return &each_rel->r_offset;
}
}
if (read(fd, each_rel, sizeof(Elf32_Rel)) != sizeof(Elf32_Rel)) {
LOGI("获取符号%s的重定位信息失败", symbol);
return NULL;
}
}
return NULL;
}
int elfhook_s(const char *so_name,const char *symbol, void *new_func_addr,void **origin_func_addr_ptr) {
char so_path[256] = {0};
uint8_t * elf_base_address = (uint8_t *) find_so_base(so_name, so_path, sizeof(so_path));
//section 信息需要从 SO 文件中读取,因为该链接视图仅在 编译链接阶段有用,在执行中无用,
//因此加载到内存后不一定有 section 段;
int fd = open(so_path, O_RDONLY);
//读取 ELF HEADER
Elf32_Ehdr *ehdr = (Elf32_Ehdr *) malloc(sizeof(Elf32_Ehdr));
read(fd, ehdr, sizeof(Elf32_Ehdr));
//查找 .shstrtab section,这个 section 存放各个 section 的名字,
//我们需要通过它来找到我们需要的 section。
uint32_t shdr_base = ehdr->e_shoff;
uint16_t shnum = ehdr->e_shnum;
uint32_t shstr_base = shdr_base + ehdr->e_shstrndx * sizeof(Elf32_Shdr);
Elf32_Shdr *shstr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
read_data_form_fd(fd,shstr_base,shstr, sizeof(Elf32_Shdr));
//定位 shstrtab 中 section name 字符的首地址
char *shstrtab = (char *) malloc(shstr->sh_size);
read_data_form_fd(fd,shstr->sh_offset,shstrtab,shstr->sh_size);
//跳转到 section 开头,我们开始 section 遍历,通过 section 的 sh_name 可以在
//shstrtab 中对照找到该 section 的名字,然后判断是不是我们需要的 section.
Elf32_Shdr *shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
lseek(fd, shdr_base, SEEK_SET);
/**
* .rel.plt 保存外部符号的重定位信息, .dynsym 保存所有符号信息,
* .dynstr 保存有符号的对应字符串表示;
*
* 我们需要修改目标符号在 .rel.plt 的重定位,但首先我们需要知道 .rel.plt 中哪一条是在说明目标符号的;
* 定位的方法是,遍历 .rel.plt 的每一条,逐条拿出来查找它在 .dynsym 的对应详细信息,
* .dynsym 的符号详细信息可以指引我们在 .dynstr 找到该符号的 name,通过比对 name 就能判断 .rel.plt 的条目是不是在说明我们目标符号的重定位;
*/
char *sh_name = NULL;
Elf32_Shdr *relplt_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
Elf32_Shdr *dynsym_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
Elf32_Shdr *dynstr_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
Elf32_Shdr *reldyn_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
for (uint16_t i = 0; i < shnum; ++i) {
read(fd, shdr, sizeof(Elf32_Shdr));
sh_name = shstrtab + shdr->sh_name;
if (strcmp(sh_name, ".dynsym") == 0)
memcpy(dynsym_shdr, shdr, sizeof(Elf32_Shdr));
else if (strcmp(sh_name, ".dynstr") == 0)
memcpy(dynstr_shdr, shdr, sizeof(Elf32_Shdr));
else if (strcmp(sh_name, ".rel.plt") == 0)
memcpy(relplt_shdr, shdr, sizeof(Elf32_Shdr));
else if (strcmp(sh_name,".rel.dyn") == 0) {
memcpy(reldyn_shdr,shdr, sizeof(Elf32_Shdr));
}
}
//读取字符表
char *dynstr = (char *) malloc(sizeof(char) * dynstr_shdr->sh_size);
lseek(fd, dynstr_shdr->sh_offset, SEEK_SET);
if (read(fd, dynstr, dynstr_shdr->sh_size) != dynstr_shdr->sh_size)
return 0;
//读取符号表
Elf32_Sym *dynsymtab = (Elf32_Sym *) malloc(dynsym_shdr->sh_size);
printf("dynsym_shdr->sh_size\t0x%x\n", dynsym_shdr->sh_size);
lseek(fd, dynsym_shdr->sh_offset, SEEK_SET);
if (read(fd, dynsymtab, dynsym_shdr->sh_size) != dynsym_shdr->sh_size)
return 0;
//读取重定位表
Elf32_Rel *rel_ent = (Elf32_Rel *) malloc(sizeof(Elf32_Rel));
lseek(fd, relplt_shdr->sh_offset, SEEK_SET);
if (read(fd, rel_ent, sizeof(Elf32_Rel)) != sizeof(Elf32_Rel))
return 0;
LOGI("ELF 表准备完成, 开始查找符号%s的 got 表重定位地址...",symbol);
Elf32_Addr *offset = find_symbol_offset(fd,symbol,rel_ent,
relplt_shdr->sh_size / sizeof(Elf32_Rel),
dynstr,dynsymtab);
if (offset == NULL) {
LOGI(".rel.plt 查找符号失败,在 .rel.dyn 尝试查找...");
//读取重定向变量表
Elf32_Rel *rel_dyn = (Elf32_Rel *) malloc(sizeof(Elf32_Rel));
lseek(fd, reldyn_shdr->sh_offset, SEEK_SET);
if (read(fd, rel_dyn, sizeof(Elf32_Rel)) != sizeof(Elf32_Rel))
return 0;
offset = find_symbol_offset(fd,symbol,rel_ent,
relplt_shdr->sh_size / sizeof(Elf32_Rel),
dynstr,dynsymtab);
}
if (offset == 0) {
LOGE("符号%s地址获取失败", symbol);
return 0;
}
LOGI("符号获取成功,进行符号地址修改...");
void * function_addr_ptr = (elf_base_address + *offset);
return replace_function((void **) function_addr_ptr,
new_func_addr, origin_func_addr_ptr);
}<commit_msg>修改字符串比较为 memcmp 提供效率<commit_after>//
// Created by yanxq on 17/6/10.
//
#include <string>
#include <fcntl.h>
#include <elf.h>
#include "elfhook_utils.h"
#include "elf_log.h"
static inline Elf32_Phdr* find_segment_by_type(Elf32_Phdr * phdr_base, const Elf32_Word phnum, const Elf32_Word ph_type) {
Elf32_Phdr *target = NULL;
for (int i = 0; i < phnum; ++i) {
if ((phdr_base + i)->p_type == ph_type) {
target = phdr_base + i;
break;
}
}
return target;
}
static inline Elf32_Addr * find_symbol_offset(const char *symbol,
Elf32_Rel *rel_base_ptr,Elf32_Word size,
const char *strtab_base,Elf32_Sym *symtab_ptr) {
Elf32_Rel *each_rel = rel_base_ptr;
size_t symbol_length = strlen(symbol);
for (int i = 0; i < size; i++,each_rel++) {
uint16_t ndx = ELF32_R_SYM(each_rel->r_info);
if (ndx == 0) continue;
LOGI("ndx = %d, str = %s", ndx, strtab_base + symtab_ptr[ndx].st_name);
if (memcmp(strtab_base + symtab_ptr[ndx].st_name, symbol,symbol_length) == 0) {
LOGI("符号%s在got表的偏移地址为: 0x%x", symbol, each_rel->r_offset);
return &each_rel->r_offset;
}
}
return NULL;
}
int elfhook_p(const char *so_name,const char *symbol, void *new_func_addr,void **origin_func_addr_ptr) {
uint8_t * elf_base_address = (uint8_t *) find_so_base(so_name, NULL,0);
Elf32_Ehdr *endr = reinterpret_cast<Elf32_Ehdr*>(elf_base_address);
Elf32_Phdr *phdr_base = reinterpret_cast<Elf32_Phdr*>(elf_base_address + endr->e_phoff);
Elf32_Phdr *dynamic_phdr = find_segment_by_type(phdr_base,endr->e_phnum,PT_DYNAMIC);
Elf32_Dyn *dyn_ptr_base = reinterpret_cast<Elf32_Dyn *>(elf_base_address + dynamic_phdr->p_vaddr);
Elf32_Word dynamic_size = dynamic_phdr -> p_memsz;
Elf32_Word dyn_count = dynamic_size / sizeof(Elf32_Dyn);
Elf32_Sym *symtab_ptr = NULL;
const char * strtab_base = NULL;
Elf32_Rel *rel_dyn_ptr_base = NULL;
Elf32_Word rel_dyn_count;
Elf32_Rel *rel_plt_base = NULL;
Elf32_Word rel_plt_count;
Elf32_Word current_find_count = 0;
Elf32_Dyn * each_dyn = dyn_ptr_base;
for (int i = 0; i < dyn_count; ++i,++each_dyn) {
switch (each_dyn->d_tag) {
case DT_SYMTAB:
symtab_ptr = reinterpret_cast<Elf32_Sym *>(elf_base_address + each_dyn->d_un.d_ptr);
current_find_count ++;
break;
case DT_STRTAB:
current_find_count ++;
strtab_base = reinterpret_cast<const char *>(elf_base_address + each_dyn->d_un.d_ptr);
break;
case DT_REL:
current_find_count ++;
rel_dyn_ptr_base = reinterpret_cast<Elf32_Rel *>(elf_base_address + each_dyn->d_un.d_ptr);
break;
case DT_RELASZ:
current_find_count ++;
rel_dyn_count = each_dyn->d_un.d_ptr / sizeof(Elf32_Rel);
break;
case DT_JMPREL:
current_find_count ++;
rel_plt_base = reinterpret_cast<Elf32_Rel *>(elf_base_address + each_dyn->d_un.d_ptr);
break;
case DT_PLTRELSZ:
current_find_count ++;
rel_plt_count = each_dyn->d_un.d_ptr / sizeof(Elf32_Rel);
break;
default:
break;
}
if (current_find_count == 5) {
break;
}
}
Elf32_Addr *offset = find_symbol_offset(symbol, rel_plt_base, rel_plt_count,
strtab_base,symtab_ptr);
if (offset == NULL) {
LOGI(".rel.plt 查找符号失败,在 .rel.dyn 尝试查找...");
offset = find_symbol_offset(symbol,rel_dyn_ptr_base,rel_dyn_count,
strtab_base,symtab_ptr);
}
if (offset == NULL) {
LOGE("获取 Offset 失败!!!");
return 0;
}
LOGI("符号获取成功,进行符号地址修改...");
void * function_addr_ptr = (elf_base_address + *offset);
return replace_function((void **) function_addr_ptr,
new_func_addr, origin_func_addr_ptr);
}
static inline void read_data_form_fd(int fd, uint32_t seek,void * ptr, size_t size) {
lseek(fd, seek, SEEK_SET);
read(fd, ptr, size);
}
static inline Elf32_Word *find_symbol_offset(int fd,const char *symbol,
Elf32_Rel *rel_base_ptr,Elf32_Word size,
const char *strtab_base,Elf32_Sym *symtab_ptr) {
size_t symbol_length = strlen(symbol);
Elf32_Rel *each_rel = rel_base_ptr;
for (uint16_t i = 0; i < size; i++) {
uint16_t ndx = ELF32_R_SYM(each_rel->r_info);
if (ndx > 0) {
LOGI("ndx = %d, str = %s", ndx, strtab_base + symtab_ptr[ndx].st_name);
if (memcmp(strtab_base + symtab_ptr[ndx].st_name, symbol,symbol_length) == 0) {
LOGI("符号%s在got表的偏移地址为: 0x%x", symbol, each_rel->r_offset);
return &each_rel->r_offset;
}
}
if (read(fd, each_rel, sizeof(Elf32_Rel)) != sizeof(Elf32_Rel)) {
LOGI("获取符号%s的重定位信息失败", symbol);
return NULL;
}
}
return NULL;
}
int elfhook_s(const char *so_name,const char *symbol, void *new_func_addr,void **origin_func_addr_ptr) {
char so_path[256] = {0};
uint8_t * elf_base_address = (uint8_t *) find_so_base(so_name, so_path, sizeof(so_path));
//section 信息需要从 SO 文件中读取,因为该链接视图仅在 编译链接阶段有用,在执行中无用,
//因此加载到内存后不一定有 section 段;
int fd = open(so_path, O_RDONLY);
//读取 ELF HEADER
Elf32_Ehdr *ehdr = (Elf32_Ehdr *) malloc(sizeof(Elf32_Ehdr));
read(fd, ehdr, sizeof(Elf32_Ehdr));
//查找 .shstrtab section,这个 section 存放各个 section 的名字,
//我们需要通过它来找到我们需要的 section。
uint32_t shdr_base = ehdr->e_shoff;
uint16_t shnum = ehdr->e_shnum;
uint32_t shstr_base = shdr_base + ehdr->e_shstrndx * sizeof(Elf32_Shdr);
Elf32_Shdr *shstr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
read_data_form_fd(fd,shstr_base,shstr, sizeof(Elf32_Shdr));
//定位 shstrtab 中 section name 字符的首地址
char *shstrtab = (char *) malloc(shstr->sh_size);
read_data_form_fd(fd,shstr->sh_offset,shstrtab,shstr->sh_size);
//跳转到 section 开头,我们开始 section 遍历,通过 section 的 sh_name 可以在
//shstrtab 中对照找到该 section 的名字,然后判断是不是我们需要的 section.
Elf32_Shdr *shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
lseek(fd, shdr_base, SEEK_SET);
/**
* .rel.plt 保存外部符号的重定位信息, .dynsym 保存所有符号信息,
* .dynstr 保存有符号的对应字符串表示;
*
* 我们需要修改目标符号在 .rel.plt 的重定位,但首先我们需要知道 .rel.plt 中哪一条是在说明目标符号的;
* 定位的方法是,遍历 .rel.plt 的每一条,逐条拿出来查找它在 .dynsym 的对应详细信息,
* .dynsym 的符号详细信息可以指引我们在 .dynstr 找到该符号的 name,通过比对 name 就能判断 .rel.plt 的条目是不是在说明我们目标符号的重定位;
*/
char *sh_name = NULL;
Elf32_Shdr *relplt_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
Elf32_Shdr *dynsym_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
Elf32_Shdr *dynstr_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
Elf32_Shdr *reldyn_shdr = (Elf32_Shdr *) malloc(sizeof(Elf32_Shdr));
for (uint16_t i = 0; i < shnum; ++i) {
read(fd, shdr, sizeof(Elf32_Shdr));
sh_name = shstrtab + shdr->sh_name;
if (strcmp(sh_name, ".dynsym") == 0)
memcpy(dynsym_shdr, shdr, sizeof(Elf32_Shdr));
else if (strcmp(sh_name, ".dynstr") == 0)
memcpy(dynstr_shdr, shdr, sizeof(Elf32_Shdr));
else if (strcmp(sh_name, ".rel.plt") == 0)
memcpy(relplt_shdr, shdr, sizeof(Elf32_Shdr));
else if (strcmp(sh_name,".rel.dyn") == 0) {
memcpy(reldyn_shdr,shdr, sizeof(Elf32_Shdr));
}
}
//读取字符表
char *dynstr = (char *) malloc(sizeof(char) * dynstr_shdr->sh_size);
lseek(fd, dynstr_shdr->sh_offset, SEEK_SET);
if (read(fd, dynstr, dynstr_shdr->sh_size) != dynstr_shdr->sh_size)
return 0;
//读取符号表
Elf32_Sym *dynsymtab = (Elf32_Sym *) malloc(dynsym_shdr->sh_size);
printf("dynsym_shdr->sh_size\t0x%x\n", dynsym_shdr->sh_size);
lseek(fd, dynsym_shdr->sh_offset, SEEK_SET);
if (read(fd, dynsymtab, dynsym_shdr->sh_size) != dynsym_shdr->sh_size)
return 0;
//读取重定位表
Elf32_Rel *rel_ent = (Elf32_Rel *) malloc(sizeof(Elf32_Rel));
lseek(fd, relplt_shdr->sh_offset, SEEK_SET);
if (read(fd, rel_ent, sizeof(Elf32_Rel)) != sizeof(Elf32_Rel))
return 0;
LOGI("ELF 表准备完成, 开始查找符号%s的 got 表重定位地址...",symbol);
Elf32_Addr *offset = find_symbol_offset(fd,symbol,rel_ent,
relplt_shdr->sh_size / sizeof(Elf32_Rel),
dynstr,dynsymtab);
if (offset == NULL) {
LOGI(".rel.plt 查找符号失败,在 .rel.dyn 尝试查找...");
//读取重定向变量表
Elf32_Rel *rel_dyn = (Elf32_Rel *) malloc(sizeof(Elf32_Rel));
lseek(fd, reldyn_shdr->sh_offset, SEEK_SET);
if (read(fd, rel_dyn, sizeof(Elf32_Rel)) != sizeof(Elf32_Rel))
return 0;
offset = find_symbol_offset(fd,symbol,rel_ent,
relplt_shdr->sh_size / sizeof(Elf32_Rel),
dynstr,dynsymtab);
}
if (offset == 0) {
LOGE("符号%s地址获取失败", symbol);
return 0;
}
LOGI("符号获取成功,进行符号地址修改...");
void * function_addr_ptr = (elf_base_address + *offset);
return replace_function((void **) function_addr_ptr,
new_func_addr, origin_func_addr_ptr);
}<|endoftext|> |
<commit_before>#pragma once
#include <array>
#include <vector>
#include "zmsg_cmm.hpp"
namespace zmsg {
/**
* \brief typedefs
*/
typedef signed char CHAR;
typedef unsigned char UCHAR;
typedef signed short SHORT;
typedef unsigned short USHORT;
typedef int8_t INT8;
typedef uint8_t UINT8;
typedef int16_t INT16;
typedef uint16_t UINT16;
typedef int32_t INT32;
typedef uint32_t UINT32;
typedef signed long LONG;
typedef unsigned long ULONG;
typedef float FLOAT;
typedef ULONG BOOL;
typedef void VOID;
} /* namespace zmsg */
/**
* \brief service fs state
*/
enum class svc_fs_state_t : uint16_t {
fs_reseting,
fs_ready,
fs_clring,
fs_calibrating,
};
/**
* \brief service heat state
*/
enum class svc_heat_state_t : uint16_t {
heat_ready,
heat_ascending,
heat_stabling,
heat_descending,
};
/**
* \brief motor id
*/
enum motorId_t : uint8_t {
LZ = 0, // left z
RZ, // right z
X, // x
Y, // y
NUM, // total number
};
/**
* \brief fusion splice display mode
*/
enum class fs_display_mode_t : uint8_t {
X = 0x0, /// only x
Y, /// only y
TB, /// top <-> bottom
LR, /// left <-> right
NO, /// no
max, /// number
};
/**
* \brief fusion splice related error code
*/
enum class fs_err_t : uint8_t {
success,
cover_openned,
no_fiber,
fiber_defect,
};
<commit_msg>zmsg: fs_state: add 'idle'<commit_after>#pragma once
#include <array>
#include <vector>
#include "zmsg_cmm.hpp"
namespace zmsg {
/**
* \brief typedefs
*/
typedef signed char CHAR;
typedef unsigned char UCHAR;
typedef signed short SHORT;
typedef unsigned short USHORT;
typedef int8_t INT8;
typedef uint8_t UINT8;
typedef int16_t INT16;
typedef uint16_t UINT16;
typedef int32_t INT32;
typedef uint32_t UINT32;
typedef signed long LONG;
typedef unsigned long ULONG;
typedef float FLOAT;
typedef ULONG BOOL;
typedef void VOID;
} /* namespace zmsg */
/**
* \brief service fs state
*/
enum class svc_fs_state_t : uint16_t {
fs_reseting,
fs_idle,
fs_ready,
fs_clring,
fs_calibrating,
};
/**
* \brief service heat state
*/
enum class svc_heat_state_t : uint16_t {
heat_ready,
heat_ascending,
heat_stabling,
heat_descending,
};
/**
* \brief motor id
*/
enum motorId_t : uint8_t {
LZ = 0, // left z
RZ, // right z
X, // x
Y, // y
NUM, // total number
};
/**
* \brief fusion splice display mode
*/
enum class fs_display_mode_t : uint8_t {
X = 0x0, /// only x
Y, /// only y
TB, /// top <-> bottom
LR, /// left <-> right
NO, /// no
max, /// number
};
/**
* \brief fusion splice related error code
*/
enum class fs_err_t : uint8_t {
success,
cover_openned,
no_fiber,
fiber_defect,
};
<|endoftext|> |
<commit_before>#pragma once
#include <limits>
#include <cmath>
#include <array>
#include <vector>
#include "zmsg_cmm.hpp"
namespace zmsg {
/**
* \brief typedefs
*/
#if 0
int{8|16|32}_t
uint{8|16|32}_t
float
double
#endif
} /* namespace zmsg */
/**
* \brief img fiber defect description
*/
typedef uint32_t ifd_t;
static constexpr ifd_t ifd_end_crude = 0x1;
static constexpr ifd_t ifd_horizontal_angle = 0x2;
static constexpr ifd_t ifd_vertical_angle = 0x4;
static constexpr ifd_t ifd_cant_identify = 0x80000000;
static constexpr ifd_t ifd_all = std::numeric_limits<ifd_t>::max();
inline void ifd_clr(ifd_t & dst, const ifd_t src)
{
dst &= ~src;
}
inline void ifd_set(ifd_t & dst, const ifd_t src)
{
dst |= src;
}
struct ifd_line_t final {
ifd_t dbmp;
/// \note all angles' unit are degree
double h_angle;
double v_angle;
int32_t wrap_diameter; /// unit: pixel
ifd_line_t()
: dbmp(0)
, h_angle(0)
, v_angle(0)
, wrap_diameter(0)
{
}
void init(void)
{
this->dbmp = 0;
this->h_angle = 0;
this->v_angle = 0;
this->wrap_diameter = 0;
}
operator bool() const
{
return dbmp;
}
bool check(ifd_t msk) const
{
return (dbmp & msk);
}
public:
ZMSG_PU(dbmp, h_angle, v_angle, wrap_diameter)
};
struct img_defects_t final {
ifd_line_t yzl;
ifd_line_t yzr;
ifd_line_t xzl;
ifd_line_t xzr;
double yz_hangle_intersect;
double xz_hangle_intersect;
/// the image contain missed corner info
std::string yz_img;
std::string xz_img;
img_defects_t()
: yzl(), yzr(), xzl(), xzr()
, yz_hangle_intersect(0)
, xz_hangle_intersect(0)
, yz_img(), xz_img()
{
}
void init(void)
{
this->yzl.init();
this->yzr.init();
this->xzl.init();
this->xzr.init();
this->yz_hangle_intersect = 0;
this->xz_hangle_intersect = 0;
this->yz_img = "";
this->xz_img = "";
}
operator bool() const
{
return (yzl || yzr || xzl || xzr);
}
bool check(ifd_t msk) const
{
return (yzl.check(msk)
|| yzr.check(msk)
|| xzl.check(msk)
|| xzr.check(msk));
}
double left_cut_angle(void) const
{
return std::max(yzl.v_angle, xzl.v_angle);
}
double right_cut_angle(void) const
{
return std::max(yzr.v_angle, xzr.v_angle);
}
public:
ZMSG_PU(yzl, yzr, xzl, xzr, yz_hangle_intersect, xz_hangle_intersect, yz_img, xz_img)
};
/**
* \biref fiber recognition infomation
*/
struct fiber_rec_info_t final {
uint32_t wrap_diameter; /// unit: nm
uint32_t core_diameter; /// unit: nm
public:
ZMSG_PU(wrap_diameter, core_diameter)
};
/**
* \brief service fs state
* \note all states mean enter this state.
*/
enum class svc_fs_state_t : uint16_t {
fs_reseting,
fs_idle,
fs_ready,
fs_entering,
fs_push1,
fs_calibrating,
fs_waiting,
fs_clring,
fs_focusing,
fs_defect_detecting,
fs_push2,
fs_pause1,
fs_precise_calibrating,
fs_pause2,
fs_pre_splice,
fs_discharge1,
fs_discharge2,
fs_discharge_manual,
fs_loss_estimating,
fs_tension_testing,
fs_finished,
fs_wait_reset,
};
/**
* \brief service heat state
*/
enum class svc_heat_state_t : uint16_t {
heat_idle,
heat_ready,
heat_ascending,
heat_stabling,
heat_descending,
};
/**
* \brief motor id
*/
enum motorId_t : uint8_t {
LZ = 0, // left z
RZ, // right z
X, // x
Y, // y
NUM, // total number
};
/**
* \brief fusion splice display mode
*/
enum class fs_display_mode_t : uint8_t {
X = 0x0, /// only x
Y, /// only y
TB, /// top <-> bottom
LR, /// left <-> right
NO, /// no
max, /// number
};
/**
* \brief fusion splicer related error code
*/
enum class fs_err_t : uint8_t {
success,
cover_openned,
no_fiber,
fiber_defect,
fiber_cross_over, /// sw or hw problem
fiber_off_center,
img_brightness,
abnormal_arc,
tense_test_fail,
fiber_broken,
quit_midway,
push_timeout,
calibrate_timeout,
reset_timeout,
arc_time_zero,
ignore,
revise1_mag,
revise2_mag,
focus_x,
focus_y,
img_process_error,
system_error,
fiber_offside, /// user should replace fiber
cmos_exposure,
loss_estimate,
failed
};
/**
* \brief led id
*/
enum ledId_t : uint8_t {
CMOS_X = 0x0,
CMOS_Y,
LED_NUM,
};
struct mag2shrink_t {
double x; /// unit: volt
double y; /// unit: um
public:
ZMSG_PU(x, y)
};
/**
* \brief discharge_data_t, used for discharge revising
*/
struct discharge_data_t {
std::array<mag2shrink_t, 2> p;
double temp; /// unit: degree centigrade
double pressure; /// unit: bar
bool empty() const
{
return (p[0].x == p[1].x);
}
void clear()
{
p[0].x = p[1].x = 0;
p[0].y = p[1].y = 0;
temp = 0;
pressure = 0;
}
public:
ZMSG_PU(p, temp, pressure)
};
/**
* \brief rt_revise_data_t, used for real time discharge revising
*/
struct rt_revise_data_t {
int32_t rt_x_exposure;
int32_t rt_y_exposure;
double rt_revise_a3;
double rt_revise_a2;
double rt_revise_a1;
double rt_revise_a0;
double rt_offset_auto;
double rt_offset_cal;
bool empty() const
{
return (rt_x_exposure <= 0 || rt_y_exposure <= 0);
}
void clear()
{
rt_x_exposure = 0;
rt_y_exposure = 0;
rt_revise_a3 = rt_revise_a2 = rt_revise_a1 = rt_revise_a0 = 0;
rt_offset_auto = rt_offset_cal = 0;
}
public:
ZMSG_PU(rt_x_exposure,
rt_y_exposure,
rt_revise_a3,
rt_revise_a2,
rt_revise_a1,
rt_revise_a0,
rt_offset_auto,
rt_offset_cal)
};
enum class fiber_t : uint8_t {
sm = 0x0,
ds,
nz,
mm,
max,
};
/**
* \brief fusion splice pattern
*/
enum class fs_pattern_t : uint8_t {
automatic = 0x0,
calibrate,
normal,
special,
};
/**
* \brief loss estimate mode
*/
enum class loss_estimate_mode_t : uint8_t {
off = 0x0,
accurate,
core,
cladding,
};
/**
* \brief shrinkabletube length
*/
enum class shrink_tube_t : uint8_t {
len_20mm = 0x0,
len_40mm,
len_60mm,
};
/**
* \brief fiber align method
*/
enum class align_method_t : uint8_t {
fine = 0x0,
clad,
core,
manual,
};
<commit_msg>new error code : arc_off_center<commit_after>#pragma once
#include <limits>
#include <cmath>
#include <array>
#include <vector>
#include "zmsg_cmm.hpp"
namespace zmsg {
/**
* \brief typedefs
*/
#if 0
int{8|16|32}_t
uint{8|16|32}_t
float
double
#endif
} /* namespace zmsg */
/**
* \brief img fiber defect description
*/
typedef uint32_t ifd_t;
static constexpr ifd_t ifd_end_crude = 0x1;
static constexpr ifd_t ifd_horizontal_angle = 0x2;
static constexpr ifd_t ifd_vertical_angle = 0x4;
static constexpr ifd_t ifd_cant_identify = 0x80000000;
static constexpr ifd_t ifd_all = std::numeric_limits<ifd_t>::max();
inline void ifd_clr(ifd_t & dst, const ifd_t src)
{
dst &= ~src;
}
inline void ifd_set(ifd_t & dst, const ifd_t src)
{
dst |= src;
}
struct ifd_line_t final {
ifd_t dbmp;
/// \note all angles' unit are degree
double h_angle;
double v_angle;
int32_t wrap_diameter; /// unit: pixel
ifd_line_t()
: dbmp(0)
, h_angle(0)
, v_angle(0)
, wrap_diameter(0)
{
}
void init(void)
{
this->dbmp = 0;
this->h_angle = 0;
this->v_angle = 0;
this->wrap_diameter = 0;
}
operator bool() const
{
return dbmp;
}
bool check(ifd_t msk) const
{
return (dbmp & msk);
}
public:
ZMSG_PU(dbmp, h_angle, v_angle, wrap_diameter)
};
struct img_defects_t final {
ifd_line_t yzl;
ifd_line_t yzr;
ifd_line_t xzl;
ifd_line_t xzr;
double yz_hangle_intersect;
double xz_hangle_intersect;
/// the image contain missed corner info
std::string yz_img;
std::string xz_img;
img_defects_t()
: yzl(), yzr(), xzl(), xzr()
, yz_hangle_intersect(0)
, xz_hangle_intersect(0)
, yz_img(), xz_img()
{
}
void init(void)
{
this->yzl.init();
this->yzr.init();
this->xzl.init();
this->xzr.init();
this->yz_hangle_intersect = 0;
this->xz_hangle_intersect = 0;
this->yz_img = "";
this->xz_img = "";
}
operator bool() const
{
return (yzl || yzr || xzl || xzr);
}
bool check(ifd_t msk) const
{
return (yzl.check(msk)
|| yzr.check(msk)
|| xzl.check(msk)
|| xzr.check(msk));
}
double left_cut_angle(void) const
{
return std::max(yzl.v_angle, xzl.v_angle);
}
double right_cut_angle(void) const
{
return std::max(yzr.v_angle, xzr.v_angle);
}
public:
ZMSG_PU(yzl, yzr, xzl, xzr, yz_hangle_intersect, xz_hangle_intersect, yz_img, xz_img)
};
/**
* \biref fiber recognition infomation
*/
struct fiber_rec_info_t final {
uint32_t wrap_diameter; /// unit: nm
uint32_t core_diameter; /// unit: nm
public:
ZMSG_PU(wrap_diameter, core_diameter)
};
/**
* \brief service fs state
* \note all states mean enter this state.
*/
enum class svc_fs_state_t : uint16_t {
fs_reseting,
fs_idle,
fs_ready,
fs_entering,
fs_push1,
fs_calibrating,
fs_waiting,
fs_clring,
fs_focusing,
fs_defect_detecting,
fs_push2,
fs_pause1,
fs_precise_calibrating,
fs_pause2,
fs_pre_splice,
fs_discharge1,
fs_discharge2,
fs_discharge_manual,
fs_loss_estimating,
fs_tension_testing,
fs_finished,
fs_wait_reset,
};
/**
* \brief service heat state
*/
enum class svc_heat_state_t : uint16_t {
heat_idle,
heat_ready,
heat_ascending,
heat_stabling,
heat_descending,
};
/**
* \brief motor id
*/
enum motorId_t : uint8_t {
LZ = 0, // left z
RZ, // right z
X, // x
Y, // y
NUM, // total number
};
/**
* \brief fusion splice display mode
*/
enum class fs_display_mode_t : uint8_t {
X = 0x0, /// only x
Y, /// only y
TB, /// top <-> bottom
LR, /// left <-> right
NO, /// no
max, /// number
};
/**
* \brief fusion splicer related error code
*/
enum class fs_err_t : uint8_t {
success,
cover_openned,
no_fiber,
fiber_defect,
fiber_cross_over, /// sw or hw problem
fiber_off_center,
img_brightness,
abnormal_arc,
tense_test_fail,
fiber_broken,
quit_midway,
push_timeout,
calibrate_timeout,
reset_timeout,
arc_time_zero,
ignore,
revise1_mag,
revise2_mag,
focus_x,
focus_y,
img_process_error,
system_error,
fiber_offside, /// user should replace fiber
cmos_exposure,
loss_estimate,
arc_off_center,
failed
};
/**
* \brief led id
*/
enum ledId_t : uint8_t {
CMOS_X = 0x0,
CMOS_Y,
LED_NUM,
};
struct mag2shrink_t {
double x; /// unit: volt
double y; /// unit: um
public:
ZMSG_PU(x, y)
};
/**
* \brief discharge_data_t, used for discharge revising
*/
struct discharge_data_t {
std::array<mag2shrink_t, 2> p;
double temp; /// unit: degree centigrade
double pressure; /// unit: bar
bool empty() const
{
return (p[0].x == p[1].x);
}
void clear()
{
p[0].x = p[1].x = 0;
p[0].y = p[1].y = 0;
temp = 0;
pressure = 0;
}
public:
ZMSG_PU(p, temp, pressure)
};
/**
* \brief rt_revise_data_t, used for real time discharge revising
*/
struct rt_revise_data_t {
int32_t rt_x_exposure;
int32_t rt_y_exposure;
double rt_revise_a3;
double rt_revise_a2;
double rt_revise_a1;
double rt_revise_a0;
double rt_offset_auto;
double rt_offset_cal;
bool empty() const
{
return (rt_x_exposure <= 0 || rt_y_exposure <= 0);
}
void clear()
{
rt_x_exposure = 0;
rt_y_exposure = 0;
rt_revise_a3 = rt_revise_a2 = rt_revise_a1 = rt_revise_a0 = 0;
rt_offset_auto = rt_offset_cal = 0;
}
public:
ZMSG_PU(rt_x_exposure,
rt_y_exposure,
rt_revise_a3,
rt_revise_a2,
rt_revise_a1,
rt_revise_a0,
rt_offset_auto,
rt_offset_cal)
};
enum class fiber_t : uint8_t {
sm = 0x0,
ds,
nz,
mm,
max,
};
/**
* \brief fusion splice pattern
*/
enum class fs_pattern_t : uint8_t {
automatic = 0x0,
calibrate,
normal,
special,
};
/**
* \brief loss estimate mode
*/
enum class loss_estimate_mode_t : uint8_t {
off = 0x0,
accurate,
core,
cladding,
};
/**
* \brief shrinkabletube length
*/
enum class shrink_tube_t : uint8_t {
len_20mm = 0x0,
len_40mm,
len_60mm,
};
/**
* \brief fiber align method
*/
enum class align_method_t : uint8_t {
fine = 0x0,
clad,
core,
manual,
};
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2012 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <deal.II/base/partitioner.h>
DEAL_II_NAMESPACE_OPEN
namespace Utilities
{
namespace MPI
{
Partitioner::Partitioner ()
:
global_size (0),
local_range_data (std::pair<types::global_dof_index, types::global_dof_index> (0, 0)),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (MPI_COMM_SELF)
{}
Partitioner::Partitioner (const unsigned int size)
:
global_size (size),
local_range_data (std::pair<types::global_dof_index, types::global_dof_index> (0, size)),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (MPI_COMM_SELF)
{}
Partitioner::Partitioner (const IndexSet &locally_owned_indices,
const IndexSet &ghost_indices_in,
const MPI_Comm communicator_in)
:
global_size (static_cast<types::global_dof_index>(locally_owned_indices.size())),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (communicator_in)
{
set_owned_indices (locally_owned_indices);
set_ghost_indices (ghost_indices_in);
}
Partitioner::Partitioner (const IndexSet &locally_owned_indices,
const MPI_Comm communicator_in)
:
global_size (static_cast<types::global_dof_index>(locally_owned_indices.size())),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (communicator_in)
{
set_owned_indices (locally_owned_indices);
}
void
Partitioner::set_owned_indices (const IndexSet &locally_owned_indices)
{
if (Utilities::System::job_supports_mpi() == true)
{
my_pid = Utilities::MPI::this_mpi_process(communicator);
n_procs = Utilities::MPI::n_mpi_processes(communicator);
}
else
{
my_pid = 0;
n_procs = 1;
}
// set the local range
Assert (locally_owned_indices.is_contiguous() == 1,
ExcMessage ("The index set specified in locally_owned_indices "
"is not contiguous."));
locally_owned_indices.compress();
if (locally_owned_indices.n_elements()>0)
local_range_data = std::pair<types::global_dof_index, types::global_dof_index>
(locally_owned_indices.nth_index_in_set(0),
locally_owned_indices.nth_index_in_set(0)+
locally_owned_indices.n_elements());
locally_owned_range_data.set_size (locally_owned_indices.size());
locally_owned_range_data.add_range (local_range_data.first,local_range_data.second);
locally_owned_range_data.compress();
ghost_indices_data.set_size (locally_owned_indices.size());
}
void
Partitioner::set_ghost_indices (const IndexSet &ghost_indices_in)
{
// Set ghost indices from input. To be sure
// that no entries from the locally owned
// range are present, subtract the locally
// owned indices in any case.
Assert (ghost_indices_in.n_elements() == 0 ||
ghost_indices_in.size() == locally_owned_range_data.size(),
ExcDimensionMismatch (ghost_indices_in.size(),
locally_owned_range_data.size()));
ghost_indices_data = ghost_indices_in;
ghost_indices_data.subtract_set (locally_owned_range_data);
ghost_indices_data.compress();
n_ghost_indices_data = ghost_indices_data.n_elements();
// In the rest of this function, we determine
// the point-to-point communication pattern of
// the partitioner. We make up a list with
// both the processors the ghost indices
// actually belong to, and the indices that
// are locally held but ghost indices of other
// processors. This allows then to import and
// export data very easily.
// find out the end index for each processor
// and communicate it (this implies the start
// index for the next processor)
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
if (n_procs < 2)
{
Assert (ghost_indices_data.n_elements() == 0, ExcInternalError());
Assert (n_import_indices_data == 0, ExcInternalError());
Assert (n_ghost_indices_data == 0, ExcInternalError());
return;
}
std::vector<types::global_dof_index> first_index (n_procs+1);
first_index[0] = 0;
MPI_Allgather(&local_range_data.second, sizeof(types::global_dof_index),
MPI_BYTE, &first_index[1], sizeof(types::global_dof_index),
MPI_BYTE, communicator);
first_index[n_procs] = global_size;
// fix case when there are some processors
// without any locally owned indices: then
// there might be a zero in some entries
if (global_size > 0)
{
unsigned int first_proc_with_nonzero_dofs = 0;
for (unsigned int i=0; i<n_procs; ++i)
if (first_index[i+1]>0)
{
first_proc_with_nonzero_dofs = i;
break;
}
for (unsigned int i=first_proc_with_nonzero_dofs+1; i<n_procs; ++i)
if (first_index[i] == 0)
first_index[i] = first_index[i-1];
// correct if our processor has a wrong local
// range
if (first_index[my_pid] != local_range_data.first)
{
Assert(local_range_data.first == local_range_data.second,
ExcInternalError());
local_range_data.first = local_range_data.second = first_index[my_pid];
}
}
// Allocate memory for data that will be
// exported
std::vector<types::global_dof_index> expanded_ghost_indices (n_ghost_indices_data);
unsigned int n_ghost_targets = 0;
if (n_ghost_indices_data > 0)
{
// Create first a vector of ghost_targets from
// the list of ghost indices and then push
// back new values. When we are done, copy the
// data to that field of the partitioner. This
// way, the variable ghost_targets will have
// exactly the size we need, whereas the
// vector filled with push_back might actually
// be too long.
unsigned int current_proc = 0;
ghost_indices_data.fill_index_vector (expanded_ghost_indices);
unsigned int current_index = expanded_ghost_indices[0];
while(current_index >= first_index[current_proc+1])
current_proc++;
std::vector<std::pair<unsigned int,unsigned int> > ghost_targets_temp
(1, std::pair<unsigned int, unsigned int>(current_proc, 0));
n_ghost_targets++;
for (unsigned int iterator=1; iterator<n_ghost_indices_data; ++iterator)
{
current_index = expanded_ghost_indices[iterator];
while(current_index >= first_index[current_proc+1])
current_proc++;
AssertIndexRange (current_proc, n_procs);
if( ghost_targets_temp[n_ghost_targets-1].first < current_proc)
{
ghost_targets_temp[n_ghost_targets-1].second =
iterator - ghost_targets_temp[n_ghost_targets-1].second;
ghost_targets_temp.push_back(std::pair<unsigned int,
unsigned int>(current_proc,iterator));
n_ghost_targets++;
}
}
ghost_targets_temp[n_ghost_targets-1].second =
n_ghost_indices_data - ghost_targets_temp[n_ghost_targets-1].second;
ghost_targets_data = ghost_targets_temp;
}
// find the processes that want to import to
// me
{
std::vector<int> send_buffer (n_procs, 0);
std::vector<int> receive_buffer (n_procs, 0);
for (unsigned int i=0; i<n_ghost_targets; i++)
send_buffer[ghost_targets_data[i].first] = ghost_targets_data[i].second;
MPI_Alltoall (&send_buffer[0], 1, MPI_INT, &receive_buffer[0], 1,
MPI_INT, communicator);
// allocate memory for import data
std::vector<std::pair<unsigned int,unsigned int> > import_targets_temp;
n_import_indices_data = 0;
for (unsigned int i=0; i<n_procs; i++)
if (receive_buffer[i] > 0)
{
n_import_indices_data += receive_buffer[i];
import_targets_temp.push_back(std::pair<unsigned int,
unsigned int> (i, receive_buffer[i]));
}
import_targets_data = import_targets_temp;
}
// send and receive indices for import
// data. non-blocking receives and blocking
// sends
std::vector<types::global_dof_index> expanded_import_indices (n_import_indices_data);
{
unsigned int current_index_start = 0;
std::vector<MPI_Request> import_requests (import_targets_data.size());
for (unsigned int i=0; i<import_targets_data.size(); i++)
{
MPI_Irecv (&expanded_import_indices[current_index_start],
import_targets_data[i].second*sizeof(types::global_dof_index),
MPI_BYTE,
import_targets_data[i].first, import_targets_data[i].first,
communicator, &import_requests[i]);
current_index_start += import_targets_data[i].second;
}
AssertDimension (current_index_start, n_import_indices_data);
// use blocking send
current_index_start = 0;
for (unsigned int i=0; i<n_ghost_targets; i++)
{
MPI_Send (&expanded_ghost_indices[current_index_start],
ghost_targets_data[i].second*sizeof(types::global_dof_index),
MPI_BYTE, ghost_targets_data[i].first, my_pid,
communicator);
current_index_start += ghost_targets_data[i].second;
}
AssertDimension (current_index_start, n_ghost_indices_data);
MPI_Waitall (import_requests.size(), &import_requests[0],
MPI_STATUSES_IGNORE);
// transform import indices to local index
// space and compress contiguous indices in
// form of ranges
{
unsigned int last_index = numbers::invalid_unsigned_int-1;
std::vector<std::pair<unsigned int,unsigned int> > compressed_import_indices;
for (unsigned int i=0;i<n_import_indices_data;i++)
{
Assert (expanded_import_indices[i] >= local_range_data.first &&
expanded_import_indices[i] < local_range_data.second,
ExcIndexRange(expanded_import_indices[i], local_range_data.first,
local_range_data.second));
unsigned int new_index = (expanded_import_indices[i] -
local_range_data.first);
if (new_index == last_index+1)
compressed_import_indices.back().second++;
else
{
compressed_import_indices.push_back
(std::pair<unsigned int,unsigned int>(new_index,new_index+1));
}
last_index = new_index;
}
import_indices_data = compressed_import_indices;
// sanity check
#ifdef DEBUG
const unsigned int n_local_dofs = local_range_data.second-local_range_data.first;
for (unsigned int i=0; i<import_indices_data.size(); ++i)
{
AssertIndexRange (import_indices_data[i].first, n_local_dofs);
AssertIndexRange (import_indices_data[i].second-1, n_local_dofs);
}
#endif
}
}
#endif
}
std::size_t
Partitioner::memory_consumption() const
{
std::size_t memory = (3*sizeof(types::global_dof_index)+4*sizeof(unsigned int)+
sizeof(MPI_Comm));
memory += MemoryConsumption::memory_consumption(ghost_targets_data);
memory += MemoryConsumption::memory_consumption(import_targets_data);
memory += MemoryConsumption::memory_consumption(import_indices_data);
memory += MemoryConsumption::memory_consumption(ghost_indices_data);
return memory;
}
} // end of namespace MPI
} // end of namespace Utilities
DEAL_II_NAMESPACE_CLOSE
<commit_msg>Correct initialization of partitioner (bug pointed out by Martin Steigemann).<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2012 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <deal.II/base/partitioner.h>
DEAL_II_NAMESPACE_OPEN
namespace Utilities
{
namespace MPI
{
Partitioner::Partitioner ()
:
global_size (0),
local_range_data (std::pair<types::global_dof_index, types::global_dof_index> (0, 0)),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (MPI_COMM_SELF)
{}
Partitioner::Partitioner (const unsigned int size)
:
global_size (size),
local_range_data (std::pair<types::global_dof_index, types::global_dof_index> (0, size)),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (MPI_COMM_SELF)
{
ghost_indices_data.set_size (size);
}
Partitioner::Partitioner (const IndexSet &locally_owned_indices,
const IndexSet &ghost_indices_in,
const MPI_Comm communicator_in)
:
global_size (static_cast<types::global_dof_index>(locally_owned_indices.size())),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (communicator_in)
{
set_owned_indices (locally_owned_indices);
set_ghost_indices (ghost_indices_in);
}
Partitioner::Partitioner (const IndexSet &locally_owned_indices,
const MPI_Comm communicator_in)
:
global_size (static_cast<types::global_dof_index>(locally_owned_indices.size())),
n_ghost_indices_data (0),
n_import_indices_data (0),
my_pid (0),
n_procs (1),
communicator (communicator_in)
{
set_owned_indices (locally_owned_indices);
}
void
Partitioner::set_owned_indices (const IndexSet &locally_owned_indices)
{
if (Utilities::System::job_supports_mpi() == true)
{
my_pid = Utilities::MPI::this_mpi_process(communicator);
n_procs = Utilities::MPI::n_mpi_processes(communicator);
}
else
{
my_pid = 0;
n_procs = 1;
}
// set the local range
Assert (locally_owned_indices.is_contiguous() == 1,
ExcMessage ("The index set specified in locally_owned_indices "
"is not contiguous."));
locally_owned_indices.compress();
if (locally_owned_indices.n_elements()>0)
local_range_data = std::pair<types::global_dof_index, types::global_dof_index>
(locally_owned_indices.nth_index_in_set(0),
locally_owned_indices.nth_index_in_set(0)+
locally_owned_indices.n_elements());
locally_owned_range_data.set_size (locally_owned_indices.size());
locally_owned_range_data.add_range (local_range_data.first,local_range_data.second);
locally_owned_range_data.compress();
ghost_indices_data.set_size (locally_owned_indices.size());
}
void
Partitioner::set_ghost_indices (const IndexSet &ghost_indices_in)
{
// Set ghost indices from input. To be sure
// that no entries from the locally owned
// range are present, subtract the locally
// owned indices in any case.
Assert (ghost_indices_in.n_elements() == 0 ||
ghost_indices_in.size() == locally_owned_range_data.size(),
ExcDimensionMismatch (ghost_indices_in.size(),
locally_owned_range_data.size()));
ghost_indices_data = ghost_indices_in;
ghost_indices_data.subtract_set (locally_owned_range_data);
ghost_indices_data.compress();
n_ghost_indices_data = ghost_indices_data.n_elements();
// In the rest of this function, we determine
// the point-to-point communication pattern of
// the partitioner. We make up a list with
// both the processors the ghost indices
// actually belong to, and the indices that
// are locally held but ghost indices of other
// processors. This allows then to import and
// export data very easily.
// find out the end index for each processor
// and communicate it (this implies the start
// index for the next processor)
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
if (n_procs < 2)
{
Assert (ghost_indices_data.n_elements() == 0, ExcInternalError());
Assert (n_import_indices_data == 0, ExcInternalError());
Assert (n_ghost_indices_data == 0, ExcInternalError());
return;
}
std::vector<types::global_dof_index> first_index (n_procs+1);
first_index[0] = 0;
MPI_Allgather(&local_range_data.second, sizeof(types::global_dof_index),
MPI_BYTE, &first_index[1], sizeof(types::global_dof_index),
MPI_BYTE, communicator);
first_index[n_procs] = global_size;
// fix case when there are some processors
// without any locally owned indices: then
// there might be a zero in some entries
if (global_size > 0)
{
unsigned int first_proc_with_nonzero_dofs = 0;
for (unsigned int i=0; i<n_procs; ++i)
if (first_index[i+1]>0)
{
first_proc_with_nonzero_dofs = i;
break;
}
for (unsigned int i=first_proc_with_nonzero_dofs+1; i<n_procs; ++i)
if (first_index[i] == 0)
first_index[i] = first_index[i-1];
// correct if our processor has a wrong local
// range
if (first_index[my_pid] != local_range_data.first)
{
Assert(local_range_data.first == local_range_data.second,
ExcInternalError());
local_range_data.first = local_range_data.second = first_index[my_pid];
}
}
// Allocate memory for data that will be
// exported
std::vector<types::global_dof_index> expanded_ghost_indices (n_ghost_indices_data);
unsigned int n_ghost_targets = 0;
if (n_ghost_indices_data > 0)
{
// Create first a vector of ghost_targets from
// the list of ghost indices and then push
// back new values. When we are done, copy the
// data to that field of the partitioner. This
// way, the variable ghost_targets will have
// exactly the size we need, whereas the
// vector filled with push_back might actually
// be too long.
unsigned int current_proc = 0;
ghost_indices_data.fill_index_vector (expanded_ghost_indices);
unsigned int current_index = expanded_ghost_indices[0];
while(current_index >= first_index[current_proc+1])
current_proc++;
std::vector<std::pair<unsigned int,unsigned int> > ghost_targets_temp
(1, std::pair<unsigned int, unsigned int>(current_proc, 0));
n_ghost_targets++;
for (unsigned int iterator=1; iterator<n_ghost_indices_data; ++iterator)
{
current_index = expanded_ghost_indices[iterator];
while(current_index >= first_index[current_proc+1])
current_proc++;
AssertIndexRange (current_proc, n_procs);
if( ghost_targets_temp[n_ghost_targets-1].first < current_proc)
{
ghost_targets_temp[n_ghost_targets-1].second =
iterator - ghost_targets_temp[n_ghost_targets-1].second;
ghost_targets_temp.push_back(std::pair<unsigned int,
unsigned int>(current_proc,iterator));
n_ghost_targets++;
}
}
ghost_targets_temp[n_ghost_targets-1].second =
n_ghost_indices_data - ghost_targets_temp[n_ghost_targets-1].second;
ghost_targets_data = ghost_targets_temp;
}
// find the processes that want to import to
// me
{
std::vector<int> send_buffer (n_procs, 0);
std::vector<int> receive_buffer (n_procs, 0);
for (unsigned int i=0; i<n_ghost_targets; i++)
send_buffer[ghost_targets_data[i].first] = ghost_targets_data[i].second;
MPI_Alltoall (&send_buffer[0], 1, MPI_INT, &receive_buffer[0], 1,
MPI_INT, communicator);
// allocate memory for import data
std::vector<std::pair<unsigned int,unsigned int> > import_targets_temp;
n_import_indices_data = 0;
for (unsigned int i=0; i<n_procs; i++)
if (receive_buffer[i] > 0)
{
n_import_indices_data += receive_buffer[i];
import_targets_temp.push_back(std::pair<unsigned int,
unsigned int> (i, receive_buffer[i]));
}
import_targets_data = import_targets_temp;
}
// send and receive indices for import
// data. non-blocking receives and blocking
// sends
std::vector<types::global_dof_index> expanded_import_indices (n_import_indices_data);
{
unsigned int current_index_start = 0;
std::vector<MPI_Request> import_requests (import_targets_data.size());
for (unsigned int i=0; i<import_targets_data.size(); i++)
{
MPI_Irecv (&expanded_import_indices[current_index_start],
import_targets_data[i].second*sizeof(types::global_dof_index),
MPI_BYTE,
import_targets_data[i].first, import_targets_data[i].first,
communicator, &import_requests[i]);
current_index_start += import_targets_data[i].second;
}
AssertDimension (current_index_start, n_import_indices_data);
// use blocking send
current_index_start = 0;
for (unsigned int i=0; i<n_ghost_targets; i++)
{
MPI_Send (&expanded_ghost_indices[current_index_start],
ghost_targets_data[i].second*sizeof(types::global_dof_index),
MPI_BYTE, ghost_targets_data[i].first, my_pid,
communicator);
current_index_start += ghost_targets_data[i].second;
}
AssertDimension (current_index_start, n_ghost_indices_data);
MPI_Waitall (import_requests.size(), &import_requests[0],
MPI_STATUSES_IGNORE);
// transform import indices to local index
// space and compress contiguous indices in
// form of ranges
{
unsigned int last_index = numbers::invalid_unsigned_int-1;
std::vector<std::pair<unsigned int,unsigned int> > compressed_import_indices;
for (unsigned int i=0;i<n_import_indices_data;i++)
{
Assert (expanded_import_indices[i] >= local_range_data.first &&
expanded_import_indices[i] < local_range_data.second,
ExcIndexRange(expanded_import_indices[i], local_range_data.first,
local_range_data.second));
unsigned int new_index = (expanded_import_indices[i] -
local_range_data.first);
if (new_index == last_index+1)
compressed_import_indices.back().second++;
else
{
compressed_import_indices.push_back
(std::pair<unsigned int,unsigned int>(new_index,new_index+1));
}
last_index = new_index;
}
import_indices_data = compressed_import_indices;
// sanity check
#ifdef DEBUG
const unsigned int n_local_dofs = local_range_data.second-local_range_data.first;
for (unsigned int i=0; i<import_indices_data.size(); ++i)
{
AssertIndexRange (import_indices_data[i].first, n_local_dofs);
AssertIndexRange (import_indices_data[i].second-1, n_local_dofs);
}
#endif
}
}
#endif
}
std::size_t
Partitioner::memory_consumption() const
{
std::size_t memory = (3*sizeof(types::global_dof_index)+4*sizeof(unsigned int)+
sizeof(MPI_Comm));
memory += MemoryConsumption::memory_consumption(ghost_targets_data);
memory += MemoryConsumption::memory_consumption(import_targets_data);
memory += MemoryConsumption::memory_consumption(import_indices_data);
memory += MemoryConsumption::memory_consumption(ghost_indices_data);
return memory;
}
} // end of namespace MPI
} // end of namespace Utilities
DEAL_II_NAMESPACE_CLOSE
<|endoftext|> |
<commit_before>#include "SeparateToComplex.h"
#include "check_params.h"
#include "lr_config.h"
#include <easyshape.h>
namespace edb
{
std::string SeparateToComplex::Command() const
{
return "separate2complex";
}
std::string SeparateToComplex::Description() const
{
return "separate lr's sprites to easycompex file";
}
std::string SeparateToComplex::Usage() const
{
// separate2complex e:/test2/test_lr.json point
std::string usage = Command() + " [filepath] [point dir]";
return usage;
}
void SeparateToComplex::Run(int argc, char *argv[])
{
if (!check_number(this, argc, 4)) return;
if (!check_file(argv[2])) return;
m_point_dir = argv[3];
Run(argv[2]);
}
void SeparateToComplex::Run(const std::string& filepath)
{
Json::Value lr_val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, lr_val);
fin.close();
Json::Value new_lr_val = lr_val;
m_dir = d2d::FilenameTools::getFileDir(filepath);
std::string dst_folder = m_dir + "\\" + LR_OUTDIR;
d2d::mk_dir(dst_folder, false);
for (int layer_idx = 0; layer_idx < 8; ++layer_idx)
{
if (layer_idx == 1)
{
int idx = 0;
Json::Value src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
while (!src_val.isNull()) {
Json::Value& dst_val = new_lr_val["layer"][layer_idx]["sprite"][idx-1];
SeparateSprite(src_val, dst_val);
src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
}
}
else if (layer_idx == 0 || layer_idx == 2 || layer_idx == 3 || layer_idx == 7)
{
int idx = 0;
Json::Value src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
while (!src_val.isNull()) {
Json::Value& dst_val = new_lr_val["layer"][layer_idx]["sprite"][idx-1];
FixSpriteName(src_val, dst_val);
src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
}
}
}
std::string outfile = dst_folder + "\\" + d2d::FilenameTools::getFilenameWithExtension(filepath);
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(outfile.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, new_lr_val);
fout.close();
}
void SeparateToComplex::SeparateSprite(const Json::Value& src, Json::Value& dst)
{
std::string name = CreateNewComplexFile(src);
ResetOldSpriteVal(dst, name);
}
void SeparateToComplex::FixSpriteName(const Json::Value& src, Json::Value& dst)
{
dst["filepath"] = "..\\" + dst["filepath"].asString();
}
std::string SeparateToComplex::CreateNewComplexFile(const Json::Value& value) const
{
std::string name = wxString::Format("lr_decorate_%d", m_count++).ToStdString();
Json::Value out_val;
out_val["name"] = name;
out_val["use_render_cache"] = false;
out_val["xmin"] = 0;
out_val["xmax"] = 0;
out_val["ymin"] = 0;
out_val["ymax"] = 0;
Json::Value spr_val = value;
spr_val["filepath"] = "..\\" + spr_val["filepath"].asString();
d2d::Vector pos;
pos.x = spr_val["position"]["x"].asDouble();
pos.y = spr_val["position"]["y"].asDouble();
FixPosWithShape(pos, value["filepath"].asString());
spr_val["position"]["x"] = pos.x;
spr_val["position"]["y"] = pos.y;
int idx = 0;
out_val["sprite"][idx] = spr_val;
std::string outpath = m_dir + "\\" + LR_OUTDIR + "\\" + name + "_complex.json";
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(outpath.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, out_val);
fout.close();
return name;
}
void SeparateToComplex::ResetOldSpriteVal(Json::Value& val, const std::string& name) const
{
val["filepath"] = name + "_complex.json";
val["position"]["x"] = 0;
val["position"]["y"] = 0;
val["angle"] = 0;
val["x scale"] = 1;
val["y scale"] = 1;
val["x shear"] = 0;
val["y shear"] = 0;
val["x offset"] = 0;
val["y offset"] = 0;
val["x mirror"] = false;
val["y mirror"] = false;
val["name"] = "";
val["tag"] = "";
val["clip"] = false;
val["multi color"] = "0xffffffff";
val["add color"] = "0x00000000";
val["r trans"] = "0xff0000ff";
val["g trans"] = "0x00ff00ff";
val["b trans"] = "0x0000ffff";
}
void SeparateToComplex::FixPosWithShape(d2d::Vector& pos, const std::string& filepath) const
{
std::string path = filepath.substr(0, filepath.find_last_of('.')) + "_shape.json";
std::string shape_path = m_dir + "\\" + m_point_dir + "\\" + path;
if (!d2d::FilenameTools::isExist(shape_path)) {
return;
}
d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(shape_path);
libshape::Symbol* shape_symbol = dynamic_cast<libshape::Symbol*>(symbol);
if (!shape_symbol) {
throw d2d::Exception("shape file err:%s", filepath);
}
std::vector<d2d::IShape*> shapes = shape_symbol->GetShapes();
if (shapes.empty()) {
throw d2d::Exception("shape file empty:%s", filepath);
}
if (libshape::PointShape* point = dynamic_cast<libshape::PointShape*>(shapes[0])) {
pos += point->GetPos();
} else {
throw d2d::Exception("shape file is not point:%s", filepath);
}
symbol->Release();
}
}<commit_msg>[FIXED] lr打包export name<commit_after>#include "SeparateToComplex.h"
#include "check_params.h"
#include "lr_config.h"
#include <easyshape.h>
namespace edb
{
std::string SeparateToComplex::Command() const
{
return "separate2complex";
}
std::string SeparateToComplex::Description() const
{
return "separate lr's sprites to easycompex file";
}
std::string SeparateToComplex::Usage() const
{
// separate2complex e:/test2/test_lr.json point
std::string usage = Command() + " [filepath] [point dir]";
return usage;
}
void SeparateToComplex::Run(int argc, char *argv[])
{
if (!check_number(this, argc, 4)) return;
if (!check_file(argv[2])) return;
m_point_dir = argv[3];
Run(argv[2]);
}
void SeparateToComplex::Run(const std::string& filepath)
{
Json::Value lr_val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, lr_val);
fin.close();
Json::Value new_lr_val = lr_val;
m_dir = d2d::FilenameTools::getFileDir(filepath);
std::string dst_folder = m_dir + "\\" + LR_OUTDIR;
d2d::mk_dir(dst_folder, false);
for (int layer_idx = 0; layer_idx < 8; ++layer_idx)
{
if (layer_idx == 1)
{
int idx = 0;
Json::Value src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
while (!src_val.isNull()) {
Json::Value& dst_val = new_lr_val["layer"][layer_idx]["sprite"][idx-1];
SeparateSprite(src_val, dst_val);
src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
}
}
else if (layer_idx == 0 || layer_idx == 2 || layer_idx == 3 || layer_idx == 7)
{
int idx = 0;
Json::Value src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
while (!src_val.isNull()) {
Json::Value& dst_val = new_lr_val["layer"][layer_idx]["sprite"][idx-1];
FixSpriteName(src_val, dst_val);
src_val = lr_val["layer"][layer_idx]["sprite"][idx++];
}
}
}
std::string outfile = dst_folder + "\\" + d2d::FilenameTools::getFilenameWithExtension(filepath);
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(outfile.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, new_lr_val);
fout.close();
}
void SeparateToComplex::SeparateSprite(const Json::Value& src, Json::Value& dst)
{
std::string name = CreateNewComplexFile(src);
ResetOldSpriteVal(dst, name);
}
void SeparateToComplex::FixSpriteName(const Json::Value& src, Json::Value& dst)
{
dst["filepath"] = "..\\" + dst["filepath"].asString();
}
std::string SeparateToComplex::CreateNewComplexFile(const Json::Value& value) const
{
std::string name = wxString::Format("lr_decorate_%d", m_count++).ToStdString();
Json::Value out_val;
out_val["name"] = name;
out_val["use_render_cache"] = false;
out_val["xmin"] = 0;
out_val["xmax"] = 0;
out_val["ymin"] = 0;
out_val["ymax"] = 0;
Json::Value spr_val = value;
spr_val["filepath"] = "..\\" + spr_val["filepath"].asString();
d2d::Vector pos;
pos.x = spr_val["position"]["x"].asDouble();
pos.y = spr_val["position"]["y"].asDouble();
FixPosWithShape(pos, value["filepath"].asString());
spr_val["position"]["x"] = pos.x;
spr_val["position"]["y"] = pos.y;
int idx = 0;
out_val["sprite"][idx] = spr_val;
std::string outpath = m_dir + "\\" + LR_OUTDIR + "\\" + name + "_complex.json";
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(outpath.c_str());
std::locale::global(std::locale("C"));
writer.write(fout, out_val);
fout.close();
return name;
}
void SeparateToComplex::ResetOldSpriteVal(Json::Value& val, const std::string& name) const
{
val["filepath"] = name + "_complex.json";
val["position"]["x"] = 0;
val["position"]["y"] = 0;
val["angle"] = 0;
val["x scale"] = 1;
val["y scale"] = 1;
val["x shear"] = 0;
val["y shear"] = 0;
val["x offset"] = 0;
val["y offset"] = 0;
val["x mirror"] = false;
val["y mirror"] = false;
val["name"] = name;
val["tag"] = "";
val["clip"] = false;
val["multi color"] = "0xffffffff";
val["add color"] = "0x00000000";
val["r trans"] = "0xff0000ff";
val["g trans"] = "0x00ff00ff";
val["b trans"] = "0x0000ffff";
}
void SeparateToComplex::FixPosWithShape(d2d::Vector& pos, const std::string& filepath) const
{
std::string path = filepath.substr(0, filepath.find_last_of('.')) + "_shape.json";
std::string shape_path = m_dir + "\\" + m_point_dir + "\\" + path;
if (!d2d::FilenameTools::isExist(shape_path)) {
return;
}
d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(shape_path);
libshape::Symbol* shape_symbol = dynamic_cast<libshape::Symbol*>(symbol);
if (!shape_symbol) {
throw d2d::Exception("shape file err:%s", filepath);
}
std::vector<d2d::IShape*> shapes = shape_symbol->GetShapes();
if (shapes.empty()) {
throw d2d::Exception("shape file empty:%s", filepath);
}
if (libshape::PointShape* point = dynamic_cast<libshape::PointShape*>(shapes[0])) {
pos += point->GetPos();
} else {
throw d2d::Exception("shape file is not point:%s", filepath);
}
symbol->Release();
}
}<|endoftext|> |
<commit_before>#include <flusspferd/current_context_scope.hpp>
#include <flusspferd/context.hpp>
#include <flusspferd/init.hpp>
#include <flusspferd/value.hpp>
#include <flusspferd/object.hpp>
#include <flusspferd/string.hpp>
#include <flusspferd/string_io.hpp>
#include <flusspferd/value_io.hpp>
#include <flusspferd/create.hpp>
#include <flusspferd/evaluate.hpp>
#include <flusspferd/native_object_base.hpp>
#include <flusspferd/class.hpp>
#include <iostream>
#include <ostream>
#include <set>
class StringSet : public flusspferd::native_object_base {
public:
struct class_info : flusspferd::class_info {
static char const *constructor_name() { return "StringSet"; }
static char const *full_name() { return "StringSet"; }
};
StringSet(flusspferd::object const &self, flusspferd::call_context &x)
: flusspferd::native_object_base(self)
{
std::cout << "Creating StringSet" << std::endl;
}
~StringSet()
{
std::cout << "Destroying StringSet" << std::endl;
}
};
void print(flusspferd::string const &x) {
std::cout << x << std::endl;
}
int main() {
flusspferd::current_context_scope context_scope(
flusspferd::context::create());
flusspferd::create_native_function(flusspferd::global(), "print", &print);
flusspferd::load_class<StringSet>();
flusspferd::evaluate(
"var set = new StringSet('a', 'b', 'c');\n"
"//set.add('d');\n");
}
<commit_msg>doc: make example more complete<commit_after>#include <flusspferd/current_context_scope.hpp>
#include <flusspferd/context.hpp>
#include <flusspferd/init.hpp>
#include <flusspferd/value.hpp>
#include <flusspferd/object.hpp>
#include <flusspferd/string.hpp>
#include <flusspferd/string_io.hpp>
#include <flusspferd/value_io.hpp>
#include <flusspferd/create.hpp>
#include <flusspferd/evaluate.hpp>
#include <flusspferd/native_object_base.hpp>
#include <flusspferd/class.hpp>
#include <iostream>
#include <ostream>
#include <set>
class StringSet : public flusspferd::native_object_base {
public:
struct class_info : flusspferd::class_info {
static char const *constructor_name() { return "StringSet"; }
static char const *full_name() { return "StringSet"; }
static object create_prototype() {
flusspferd::object o = flusspferd::create_object();
create_native_method(o, "dump", 0);
create_native_method(o, "add", 1);
create_native_method(o, "delete", 1);
create_native_method(o, "toArray", 0);
return o;
}
};
void init() {
register_native_method("dump", &StringSet::dump);
register_native_method("add", &StringSet::add);
register_native_method("delete", &StringSet::delete_);
register_native_method("toArray", &StringSet::to_array);
}
StringSet(flusspferd::object const &self, flusspferd::call_context &x)
: flusspferd::native_object_base(self)
{
init();
std::cout << "Creating StringSet" << std::endl;
for (flusspferd::arguments::iterator it = x.arg.begin();
it != x.arg.end();
++it)
{
data.insert(flusspferd::string(*it).to_string());
}
}
~StringSet()
{
std::cout << "Destroying StringSet" << std::endl;
}
private:
void dump() {
std::cout << "Dumping StringSet: ";
for (std::set<std::string>::iterator it = data.begin();
it != data.end();
++it)
{
if (it != data.begin())
std::cout << ',';
std::cout << *it;
}
std::cout << std::endl;
}
void add(std::string const &x) {
data.insert(x);
}
void delete_(std::string const &x) {
data.erase(x);
}
flusspferd::array to_array() {
flusspferd::array result = flusspferd::create_array();
for (std::set<std::string>::iterator it = data.begin();
it != data.end();
++it)
{
result.call("push", *it);
}
return result;
}
private:
std::set<std::string> data;
};
void print(flusspferd::string const &x) {
std::cout << x << std::endl;
}
int main() {
flusspferd::current_context_scope context_scope(
flusspferd::context::create());
flusspferd::create_native_function(flusspferd::global(), "print", &print);
flusspferd::load_class<StringSet>();
flusspferd::evaluate(
"var set = new StringSet('b', 'a', 'd');\n"
"set.add('c');\n"
"set.dump();\n"
"set.delete('a'); set.delete('b');\n"
"print('As Array: ' + set.toArray().toSource());\n"
);
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Maximilian Knespel
*
* 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 "createAtomCluster.hpp"
#include <iostream>
#include <vector>
#include <cassert>
#include <cstdlib> // srand, RAND_MAX, rand
#include <cmath> // fmin, sqrtf, max
#include "libs/gaussian.hpp"
namespace examples
{
namespace createTestData
{
#define SCALE_EXAMPLE_IMAGE 1
float * createAtomCluster
(
const unsigned & Nx,
const unsigned & Ny
)
{
assert( Nx > 0 and Ny );
const unsigned nElements = Nx * Ny;
float * data = new float[nElements];
/* Add random background noise and blur it, so that it isn't pixelwise */
srand(4628941);
const float noiseAmplitude = 0.00;
for ( unsigned i = 0; i < nElements; ++i )
data[i] = 0.7*noiseAmplitude * rand() / (float) RAND_MAX;
imresh::libs::gaussianBlur( data, Nx, Ny, 1.5 /*sigma in pixels*/ );
/* add more fine grained noise in a second step */
for ( unsigned i = 0; i < nElements; ++i )
data[i] += 0.3*noiseAmplitude * rand() / (float) RAND_MAX;
/* choose a radious, so that the atom cluster will fit into the image
* and will fill it pretty well */
#if SCALE_EXAMPLE_IMAGE == 1
const float atomRadius = fmin( 0.05f*Nx, 0.01f*Ny );
#else
const float atomRadius = 1.6;
#endif
#ifndef NDEBUG
std::cout << "atomRadius = "<<atomRadius<<" px\n";
#endif
/* The centers are given as offsets in multiplies of 2*atomradius
* The virtual position is at ix=iy=0 at first */
std::vector< std::vector<float> > atomCenters = {
{ 0.45f*Nx/(2*atomRadius), 0.61f*Ny/(2*atomRadius) } /*0*/
,{ 0.10f, 0.90f } /*1*/ /* */
,{ 1.00f,-0.10f } /*2*/ /* gh */
,{ 0.70f,-0.70f } /*3*/ /* df i */
,{ 0.70f,-0.70f } /*4*/ /* ce j k */
,{ 0.94f, 0.15f } /*5*/ /* b */
,{-0.70f, 0.70f } /*6*/ /* 1 2 7 8 a */
,{-0.70f, 0.70f } /*7*/ /* 0 3 6 9 */
,{ 0.94f, 0.14f } /*8*/ /* 4 5 */
,{ 0.75f,-0.70f } /*9*/
,{ 0.00f,+1.00f } /*a*/
,{-1.80f, 0.50f } /*b*/
,{-0.70f, 0.70f } /*c*/
,{ 0.10f, 0.95f } /*d*/
,{ 0.70f,-0.70f } /*e*/
,{ 0.10f, 0.95f } /*f*/
,{-0.25f, 0.90f } /*g*/
,{ 0.90f, 0.14f } /*h*/
,{ 0.20f,-0.90f } /*i*/
,{ 0.60f,-0.70f } /*j*/
#if false
,{ 0.65f,-0.60f } /*k*/
#endif
/* second cluster to the lower left from the first */
,{-6.00f,-25.0f }
,{-0.10f, 0.90f }
,{-0.70f, 0.95f }
,{ 0.40f, 0.80f }
,{ 0.25f, 0.90f }
,{ 0.25f, 0.90f }
,{ 0.25f, 0.90f }
,{-0.60f, 0.90f }
,{-0.25f,-0.90f }
,{-0.25f,-0.90f }
,{-0.25f,-0.90f }
,{-0.25f,-1.10f }
,{ 0.20f, 3.50f }
,{-0.05f, 1.00f }
,{-0.15f, 0.90f }
};
/* spherical intensity function */
auto f = []( float r ) { return std::abs(r) < 1.0f ? 1.0f - pow(r,6)
: 0.0f; };
float x = 0;
float y = 0;
for ( auto r : atomCenters )
{
x += r[0] * 2*atomRadius;
y += r[1] * 2*atomRadius;
int ix0 = std::max( (int) 0 , (int) floor(x-atomRadius)-1 );
int ix1 = std::min( (int) Nx-1, (int) ceil (x+atomRadius)+1 );
int iy0 = std::max( (int) 0 , (int) floor(y-atomRadius)-1 );
int iy1 = std::min( (int) Ny-1, (int) ceil (y+atomRadius)+1 );
for ( int ix = ix0; ix < ix1; ++ix )
for ( int iy = iy0; iy < iy1; ++iy )
{
data[iy*Nx+ix] += (1-noiseAmplitude) * f( sqrt(pow(ix-x,2)
+ pow(iy-y,2)) / atomRadius );
data[iy*Nx+ix] = std::min( 1.0f, data[iy*Nx+ix] );
}
}
return data;
}
} // namespace createTestData
} // namespace examples
<commit_msg>Make 0 default, because 1 will lead to reconstruction problems, see Issue #39<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Maximilian Knespel
*
* 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 "createAtomCluster.hpp"
#include <iostream>
#include <vector>
#include <cassert>
#include <cstdlib> // srand, RAND_MAX, rand
#include <cmath> // fmin, sqrtf, max
#include "libs/gaussian.hpp"
namespace examples
{
namespace createTestData
{
#define SCALE_EXAMPLE_IMAGE 0
float * createAtomCluster
(
const unsigned & Nx,
const unsigned & Ny
)
{
assert( Nx > 0 and Ny );
const unsigned nElements = Nx * Ny;
float * data = new float[nElements];
/* Add random background noise and blur it, so that it isn't pixelwise */
srand(4628941);
const float noiseAmplitude = 0.00;
for ( unsigned i = 0; i < nElements; ++i )
data[i] = 0.7*noiseAmplitude * rand() / (float) RAND_MAX;
imresh::libs::gaussianBlur( data, Nx, Ny, 1.5 /*sigma in pixels*/ );
/* add more fine grained noise in a second step */
for ( unsigned i = 0; i < nElements; ++i )
data[i] += 0.3*noiseAmplitude * rand() / (float) RAND_MAX;
/* choose a radious, so that the atom cluster will fit into the image
* and will fill it pretty well */
#if SCALE_EXAMPLE_IMAGE == 1
const float atomRadius = fmin( 0.05f*Nx, 0.01f*Ny );
#else
const float atomRadius = 1.6;
#endif
#ifndef NDEBUG
std::cout << "atomRadius = "<<atomRadius<<" px\n";
#endif
/* The centers are given as offsets in multiplies of 2*atomradius
* The virtual position is at ix=iy=0 at first */
std::vector< std::vector<float> > atomCenters = {
{ 0.45f*Nx/(2*atomRadius), 0.61f*Ny/(2*atomRadius) } /*0*/
,{ 0.10f, 0.90f } /*1*/ /* */
,{ 1.00f,-0.10f } /*2*/ /* gh */
,{ 0.70f,-0.70f } /*3*/ /* df i */
,{ 0.70f,-0.70f } /*4*/ /* ce j k */
,{ 0.94f, 0.15f } /*5*/ /* b */
,{-0.70f, 0.70f } /*6*/ /* 1 2 7 8 a */
,{-0.70f, 0.70f } /*7*/ /* 0 3 6 9 */
,{ 0.94f, 0.14f } /*8*/ /* 4 5 */
,{ 0.75f,-0.70f } /*9*/
,{ 0.00f,+1.00f } /*a*/
,{-1.80f, 0.50f } /*b*/
,{-0.70f, 0.70f } /*c*/
,{ 0.10f, 0.95f } /*d*/
,{ 0.70f,-0.70f } /*e*/
,{ 0.10f, 0.95f } /*f*/
,{-0.25f, 0.90f } /*g*/
,{ 0.90f, 0.14f } /*h*/
,{ 0.20f,-0.90f } /*i*/
,{ 0.60f,-0.70f } /*j*/
#if false
,{ 0.65f,-0.60f } /*k*/
#endif
/* second cluster to the lower left from the first */
,{-6.00f,-25.0f }
,{-0.10f, 0.90f }
,{-0.70f, 0.95f }
,{ 0.40f, 0.80f }
,{ 0.25f, 0.90f }
,{ 0.25f, 0.90f }
,{ 0.25f, 0.90f }
,{-0.60f, 0.90f }
,{-0.25f,-0.90f }
,{-0.25f,-0.90f }
,{-0.25f,-0.90f }
,{-0.25f,-1.10f }
,{ 0.20f, 3.50f }
,{-0.05f, 1.00f }
,{-0.15f, 0.90f }
};
/* spherical intensity function */
auto f = []( float r ) { return std::abs(r) < 1.0f ? 1.0f - pow(r,6)
: 0.0f; };
float x = 0;
float y = 0;
for ( auto r : atomCenters )
{
x += r[0] * 2*atomRadius;
y += r[1] * 2*atomRadius;
int ix0 = std::max( (int) 0 , (int) floor(x-atomRadius)-1 );
int ix1 = std::min( (int) Nx-1, (int) ceil (x+atomRadius)+1 );
int iy0 = std::max( (int) 0 , (int) floor(y-atomRadius)-1 );
int iy1 = std::min( (int) Ny-1, (int) ceil (y+atomRadius)+1 );
for ( int ix = ix0; ix < ix1; ++ix )
for ( int iy = iy0; iy < iy1; ++iy )
{
data[iy*Nx+ix] += (1-noiseAmplitude) * f( sqrt(pow(ix-x,2)
+ pow(iy-y,2)) / atomRadius );
data[iy*Nx+ix] = std::min( 1.0f, data[iy*Nx+ix] );
}
}
return data;
}
} // namespace createTestData
} // namespace examples
<|endoftext|> |
<commit_before>#include "Queue.h"
#include "gtest/gtest.h"
class QueueTest : public testing::Test {
protected:
virtual void SetUp() {
//NOT YET IMPLEMENTED
}
virtual void TearDown() {
}
// setup fixtures
Queue<int> q0_;
};
TEST_F(QueueTest, DefaultConstructor) {
EXPECT_NE(0u, 1u);
}
<commit_msg>Queue: add def ctor and enqueue tests.<commit_after>#include "Queue.h"
#include "gtest/gtest.h"
/* The Queue data structure
* Public interface:
* enqueue()
* dequeue()
* size()
* clear()
* begin()
* end() : one pass the last item
* empty()
*/
class QueueTest : public testing::Test {
protected:
// SetUp() & TearDown() are virtual functions from testting::Test,
// so we just signify that we override them here
virtual void SetUp() {
q1_.enqueue(1);
q1_.enqueue(2);
q2_.enqueue(1);
q2_.enqueue(3);
}
virtual void TearDown() {
}
// setup fixtures
Queue<int> q0_;
Queue<int> q1_;
Queue<int> q2_;
};
// Use TEST_F to test with fixtures.
TEST_F(QueueTest, DefaultConstructor) {
EXPECT_EQ(0u, q0_.size());
}
TEST_F(QueueTest, Enqueue){
EXPECT_EQ(2u, q1_.size());
EXPECT_EQ(2u, q2_.size());
q2_.enqueue(100);
EXPECT_EQ(3u, q2_.size());
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <string.h>
#include <sys/stat.h>
using namespace std;
char numToStr(int num)
//only used to convert single digit number to char
{
if(num < 0 | num > 9)
{
cout << "Use single digit\n";
}
return (num + 48);
}
string intToStr(int i)
//converts integer to string
{
string result = "";
if(i == 0)
return "0";
while(i != 0)
{
result = numToStr(i % 10) + result;
i = i / 10;
}
return result;
}
int main(int argc, char const *argv[])
{
string path = getenv("USER");
path = "/Users/" + path + "/Desktop/";
cout << "Series name: ";
string hold;
getline(cin, hold);
path = path + hold;
cout << "Season number: ";
int s, e;
cin >> s;
cout << "Episode count: ";
cin >> e;
mkdir(path.c_str(), ACCESSPERMS);
cout << "Making...\n";
cout << path << endl;
path = path + "/s" + intToStr(s);
mkdir(path.c_str(), ACCESSPERMS);
cout << path << endl;
path = path + "/e";
for(int j = 1; j <= e; j++)
{
hold = path + intToStr(j);
mkdir(hold.c_str(), ACCESSPERMS);
cout << hold << endl;
}
return 0;
}
<commit_msg>Source<commit_after>//Yigit Suoglu Aug 17, 2016
#include <iostream>
#include <string>
#include <string.h>
#include <sys/stat.h>
using namespace std;
char numToStr(int num)
//only used to convert single digit number to char
{
if(num < 0 | num > 9)
{
cout << "Use single digit\n";
}
return (num + 48);
}
string intToStr(int i)
//converts integer to string
{
string result = "";
if(i == 0)
return "0";
while(i != 0)
{
result = numToStr(i % 10) + result;
i = i / 10;
}
return result;
}
int main(int argc, char const *argv[])
{
string path = getenv("USER");
path = "/Users/" + path + "/Desktop/";
cout << "Series name: ";
string hold;
getline(cin, hold);
path = path + hold;
cout << "Season number: ";
int s, e;
cin >> s;
cout << "Episode count: ";
cin >> e;
mkdir(path.c_str(), ACCESSPERMS);
cout << "Making...\n";
cout << path << endl;
path = path + "/s" + intToStr(s);
mkdir(path.c_str(), ACCESSPERMS);
cout << path << endl;
path = path + "/e";
for(int j = 1; j <= e; j++)
{
hold = path + intToStr(j);
mkdir(hold.c_str(), ACCESSPERMS);
cout << hold << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2012 J-P Nurmi <[email protected]>
*
* 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.
*/
#include "sessiontabwidget.h"
#include "messageview.h"
#include "settings.h"
#include "session.h"
#include <irccommand.h>
#include <QtGui>
SessionTabWidget::SessionTabWidget(Session* session, QWidget* parent) :
TabWidget(parent)
{
d.handler.setSession(session);
connect(this, SIGNAL(currentChanged(int)), this, SLOT(tabActivated(int)));
connect(this, SIGNAL(newTabRequested()), this, SLOT(onNewTabRequested()), Qt::QueuedConnection);
connect(this, SIGNAL(tabMenuRequested(int,QPoint)), this, SLOT(onTabMenuRequested(int,QPoint)));
connect(session, SIGNAL(activeChanged(bool)), this, SLOT(updateStatus()));
connect(session, SIGNAL(connectedChanged(bool)), this, SLOT(updateStatus()));
connect(&d.handler, SIGNAL(receiverToBeAdded(QString)), this, SLOT(openView(QString)));
connect(&d.handler, SIGNAL(receiverToBeRemoved(QString)), this, SLOT(removeView(QString)));
connect(&d.handler, SIGNAL(receiverToBeRenamed(QString,QString)), this, SLOT(renameView(QString,QString)));
d.tabLeftShortcut = new QShortcut(this);
connect(d.tabLeftShortcut, SIGNAL(activated()), this, SLOT(moveToPrevTab()));
d.tabRightShortcut = new QShortcut(this);
connect(d.tabRightShortcut, SIGNAL(activated()), this, SLOT(moveToNextTab()));
QShortcut* shortcut = new QShortcut(QKeySequence::AddTab, this);
connect(shortcut, SIGNAL(activated()), this, SLOT(onNewTabRequested()));
shortcut = new QShortcut(QKeySequence::Close, this);
connect(shortcut, SIGNAL(activated()), this, SLOT(closeCurrentView()));
MessageView* view = openView(d.handler.session()->host());
d.handler.setDefaultReceiver(view);
updateStatus();
applySettings(d.settings);
}
Session* SessionTabWidget::session() const
{
return qobject_cast<Session*>(d.handler.session());
}
MessageView* SessionTabWidget::openView(const QString& receiver)
{
MessageView* view = d.views.value(receiver.toLower());
if (!view)
{
MessageView::ViewType type = MessageView::ServerView;
if (!d.views.isEmpty())
type = session()->isChannel(receiver) ? MessageView::ChannelView : MessageView::QueryView;
view = new MessageView(type, d.handler.session(), this);
view->setReceiver(receiver);
connect(view, SIGNAL(alerted(IrcMessage*)), this, SLOT(onTabAlerted(IrcMessage*)));
connect(view, SIGNAL(highlighted(IrcMessage*)), this, SLOT(onTabHighlighted(IrcMessage*)));
connect(view, SIGNAL(queried(QString)), this, SLOT(openView(QString)));
d.handler.addReceiver(receiver, view);
d.views.insert(receiver.toLower(), view);
addTab(view, receiver);
}
setCurrentWidget(view);
return view;
}
void SessionTabWidget::removeView(const QString& receiver)
{
MessageView* view = d.views.take(receiver.toLower());
if (view)
{
view->deleteLater();
if (indexOf(view) == 0)
{
deleteLater();
session()->destructLater();
}
}
}
void SessionTabWidget::closeCurrentView()
{
closeView(currentIndex());
}
void SessionTabWidget::closeView(int index)
{
MessageView* view = d.views.value(tabText(index).toLower());
if (view)
{
QString reason = tr("%1 %2").arg(QApplication::applicationName())
.arg(QApplication::applicationVersion());
if (indexOf(view) == 0)
session()->quit(reason);
else if (view->viewType() == MessageView::ChannelView)
d.handler.session()->sendCommand(IrcCommand::createPart(view->receiver(), reason));
d.handler.removeReceiver(view->receiver());
}
}
void SessionTabWidget::renameView(const QString& from, const QString& to)
{
MessageView* view = d.views.take(from.toLower());
if (view)
{
view->setReceiver(to);
d.views.insert(to.toLower(), view);
int index = indexOf(view);
if (index != -1)
setTabText(index, view->receiver());
}
}
bool SessionTabWidget::event(QEvent* event)
{
if (event->type() == QEvent::WindowActivate)
delayedTabReset();
return TabWidget::event(event);
}
void SessionTabWidget::updateStatus()
{
bool inactive = !session()->isActive() && !session()->isConnected();
setTabInactive(0, inactive);
emit inactiveStatusChanged(inactive);
}
void SessionTabWidget::tabActivated(int index)
{
if (index < count() - 1)
{
d.handler.setCurrentReceiver(qobject_cast<MessageView*>(currentWidget()));
setTabAlert(index, false);
setTabHighlight(index, false);
if (isVisible())
{
window()->setWindowFilePath(tabText(index));
if (currentWidget())
currentWidget()->setFocus();
}
}
}
void SessionTabWidget::onNewTabRequested()
{
QString channel = QInputDialog::getText(this, tr("Join channel"), tr("Channel:"));
if (!channel.isEmpty())
{
if (session()->isChannel(channel))
d.handler.session()->sendCommand(IrcCommand::createJoin(channel));
openView(channel);
}
}
void SessionTabWidget::onTabMenuRequested(int index, const QPoint& pos)
{
QMenu menu;
if (index == 0)
{
if (session()->isActive())
menu.addAction(tr("Disconnect"), session(), SLOT(quit()));
else
menu.addAction(tr("Reconnect"), session(), SLOT(reconnect()));
}
if (static_cast<MessageView*>(widget(index))->viewType() == MessageView::ChannelView)
menu.addAction(tr("Part"), this, SLOT(onTabCloseRequested()))->setData(index);
else
menu.addAction(tr("Close"), this, SLOT(onTabCloseRequested()))->setData(index);
menu.exec(pos);
}
void SessionTabWidget::onTabCloseRequested()
{
QAction* action = qobject_cast<QAction*>(sender());
if (action)
closeView(action->data().toInt());
}
void SessionTabWidget::delayedTabReset()
{
d.delayedIndexes += currentIndex();
QTimer::singleShot(500, this, SLOT(delayedTabResetTimeout()));
}
void SessionTabWidget::delayedTabResetTimeout()
{
if (d.delayedIndexes.isEmpty())
return;
int index = d.delayedIndexes.takeFirst();
tabActivated(index);
}
void SessionTabWidget::onTabAlerted(IrcMessage* message)
{
int index = indexOf(static_cast<QWidget*>(sender()));
if (index != -1)
{
if (!isVisible() || !isActiveWindow() || index != currentIndex())
{
setTabAlert(index, true);
emit alerted(message);
}
}
}
void SessionTabWidget::onTabHighlighted(IrcMessage* message)
{
int index = indexOf(static_cast<QWidget*>(sender()));
if (index != -1)
{
if (!isVisible() || !isActiveWindow() || index != currentIndex())
{
setTabHighlight(index, true);
emit highlighted(message);
}
}
}
void SessionTabWidget::applySettings(const Settings& settings)
{
d.tabLeftShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::TabLeft)));
d.tabRightShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::TabRight)));
QColor color(settings.colors.value(Settings::Highlight));
setTabTextColor(Alert, color);
setTabTextColor(Highlight, color);
foreach (MessageView* view, d.views)
view->applySettings(settings);
d.settings = settings;
}
<commit_msg>SessionTabWidget: escape mnemonics in tab titles<commit_after>/*
* Copyright (C) 2008-2012 J-P Nurmi <[email protected]>
*
* 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.
*/
#include "sessiontabwidget.h"
#include "messageview.h"
#include "settings.h"
#include "session.h"
#include <irccommand.h>
#include <QtGui>
SessionTabWidget::SessionTabWidget(Session* session, QWidget* parent) :
TabWidget(parent)
{
d.handler.setSession(session);
connect(this, SIGNAL(currentChanged(int)), this, SLOT(tabActivated(int)));
connect(this, SIGNAL(newTabRequested()), this, SLOT(onNewTabRequested()), Qt::QueuedConnection);
connect(this, SIGNAL(tabMenuRequested(int,QPoint)), this, SLOT(onTabMenuRequested(int,QPoint)));
connect(session, SIGNAL(activeChanged(bool)), this, SLOT(updateStatus()));
connect(session, SIGNAL(connectedChanged(bool)), this, SLOT(updateStatus()));
connect(&d.handler, SIGNAL(receiverToBeAdded(QString)), this, SLOT(openView(QString)));
connect(&d.handler, SIGNAL(receiverToBeRemoved(QString)), this, SLOT(removeView(QString)));
connect(&d.handler, SIGNAL(receiverToBeRenamed(QString,QString)), this, SLOT(renameView(QString,QString)));
d.tabLeftShortcut = new QShortcut(this);
connect(d.tabLeftShortcut, SIGNAL(activated()), this, SLOT(moveToPrevTab()));
d.tabRightShortcut = new QShortcut(this);
connect(d.tabRightShortcut, SIGNAL(activated()), this, SLOT(moveToNextTab()));
QShortcut* shortcut = new QShortcut(QKeySequence::AddTab, this);
connect(shortcut, SIGNAL(activated()), this, SLOT(onNewTabRequested()));
shortcut = new QShortcut(QKeySequence::Close, this);
connect(shortcut, SIGNAL(activated()), this, SLOT(closeCurrentView()));
MessageView* view = openView(d.handler.session()->host());
d.handler.setDefaultReceiver(view);
updateStatus();
applySettings(d.settings);
}
Session* SessionTabWidget::session() const
{
return qobject_cast<Session*>(d.handler.session());
}
MessageView* SessionTabWidget::openView(const QString& receiver)
{
MessageView* view = d.views.value(receiver.toLower());
if (!view)
{
MessageView::ViewType type = MessageView::ServerView;
if (!d.views.isEmpty())
type = session()->isChannel(receiver) ? MessageView::ChannelView : MessageView::QueryView;
view = new MessageView(type, d.handler.session(), this);
view->setReceiver(receiver);
connect(view, SIGNAL(alerted(IrcMessage*)), this, SLOT(onTabAlerted(IrcMessage*)));
connect(view, SIGNAL(highlighted(IrcMessage*)), this, SLOT(onTabHighlighted(IrcMessage*)));
connect(view, SIGNAL(queried(QString)), this, SLOT(openView(QString)));
d.handler.addReceiver(receiver, view);
d.views.insert(receiver.toLower(), view);
addTab(view, QString(receiver).replace("&", "&&"));
}
setCurrentWidget(view);
return view;
}
void SessionTabWidget::removeView(const QString& receiver)
{
MessageView* view = d.views.take(receiver.toLower());
if (view)
{
view->deleteLater();
if (indexOf(view) == 0)
{
deleteLater();
session()->destructLater();
}
}
}
void SessionTabWidget::closeCurrentView()
{
closeView(currentIndex());
}
void SessionTabWidget::closeView(int index)
{
MessageView* view = d.views.value(tabText(index).toLower());
if (view)
{
QString reason = tr("%1 %2").arg(QApplication::applicationName())
.arg(QApplication::applicationVersion());
if (indexOf(view) == 0)
session()->quit(reason);
else if (view->viewType() == MessageView::ChannelView)
d.handler.session()->sendCommand(IrcCommand::createPart(view->receiver(), reason));
d.handler.removeReceiver(view->receiver());
}
}
void SessionTabWidget::renameView(const QString& from, const QString& to)
{
MessageView* view = d.views.take(from.toLower());
if (view)
{
view->setReceiver(to);
d.views.insert(to.toLower(), view);
int index = indexOf(view);
if (index != -1)
setTabText(index, view->receiver());
}
}
bool SessionTabWidget::event(QEvent* event)
{
if (event->type() == QEvent::WindowActivate)
delayedTabReset();
return TabWidget::event(event);
}
void SessionTabWidget::updateStatus()
{
bool inactive = !session()->isActive() && !session()->isConnected();
setTabInactive(0, inactive);
emit inactiveStatusChanged(inactive);
}
void SessionTabWidget::tabActivated(int index)
{
if (index < count() - 1)
{
d.handler.setCurrentReceiver(qobject_cast<MessageView*>(currentWidget()));
setTabAlert(index, false);
setTabHighlight(index, false);
if (isVisible())
{
window()->setWindowFilePath(tabText(index));
if (currentWidget())
currentWidget()->setFocus();
}
}
}
void SessionTabWidget::onNewTabRequested()
{
QString channel = QInputDialog::getText(this, tr("Join channel"), tr("Channel:"));
if (!channel.isEmpty())
{
if (session()->isChannel(channel))
d.handler.session()->sendCommand(IrcCommand::createJoin(channel));
openView(channel);
}
}
void SessionTabWidget::onTabMenuRequested(int index, const QPoint& pos)
{
QMenu menu;
if (index == 0)
{
if (session()->isActive())
menu.addAction(tr("Disconnect"), session(), SLOT(quit()));
else
menu.addAction(tr("Reconnect"), session(), SLOT(reconnect()));
}
if (static_cast<MessageView*>(widget(index))->viewType() == MessageView::ChannelView)
menu.addAction(tr("Part"), this, SLOT(onTabCloseRequested()))->setData(index);
else
menu.addAction(tr("Close"), this, SLOT(onTabCloseRequested()))->setData(index);
menu.exec(pos);
}
void SessionTabWidget::onTabCloseRequested()
{
QAction* action = qobject_cast<QAction*>(sender());
if (action)
closeView(action->data().toInt());
}
void SessionTabWidget::delayedTabReset()
{
d.delayedIndexes += currentIndex();
QTimer::singleShot(500, this, SLOT(delayedTabResetTimeout()));
}
void SessionTabWidget::delayedTabResetTimeout()
{
if (d.delayedIndexes.isEmpty())
return;
int index = d.delayedIndexes.takeFirst();
tabActivated(index);
}
void SessionTabWidget::onTabAlerted(IrcMessage* message)
{
int index = indexOf(static_cast<QWidget*>(sender()));
if (index != -1)
{
if (!isVisible() || !isActiveWindow() || index != currentIndex())
{
setTabAlert(index, true);
emit alerted(message);
}
}
}
void SessionTabWidget::onTabHighlighted(IrcMessage* message)
{
int index = indexOf(static_cast<QWidget*>(sender()));
if (index != -1)
{
if (!isVisible() || !isActiveWindow() || index != currentIndex())
{
setTabHighlight(index, true);
emit highlighted(message);
}
}
}
void SessionTabWidget::applySettings(const Settings& settings)
{
d.tabLeftShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::TabLeft)));
d.tabRightShortcut->setKey(QKeySequence(settings.shortcuts.value(Settings::TabRight)));
QColor color(settings.colors.value(Settings::Highlight));
setTabTextColor(Alert, color);
setTabTextColor(Highlight, color);
foreach (MessageView* view, d.views)
view->applySettings(settings);
d.settings = settings;
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2015 Virgil Security Inc.
*
* Lead Maintainer: Virgil Security Inc. <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* (1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* (2) 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.
*
* (3) Neither the name of the copyright holder 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 AUTHOR ''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 AUTHOR 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 <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <tclap/CmdLine.h>
#include <virgil/crypto/VirgilByteArray.h>
#include <virgil/crypto/VirgilStreamSigner.h>
#include <virgil/crypto/stream/VirgilStreamDataSource.h>
#include <virgil/sdk/models/CardModel.h>
#include <cli/version.h>
#include <cli/pair.h>
#include <cli/util.h>
namespace vcrypto = virgil::crypto;
namespace vsdk = virgil::sdk;
namespace vcli = virgil::cli;
#ifdef SPLIT_CLI
#define MAIN main
#else
#define MAIN verify_main
#endif
static void checkFormatRecipientArg(const std::pair<std::string, std::string>& pairRecipientArg);
int MAIN(int argc, char** argv) {
try {
std::string description = "Verify data and signature with given user's identifier"
" or with it Virgil Card.\n";
std::vector<std::string> examples;
examples.push_back("virgil verify -i plain.txt -s plain.txt.sign -r email:[email protected]\n");
std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples);
// Parse arguments.
TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());
TCLAP::ValueArg<std::string> inArg("i", "in", "Data to be verified. If omitted stdin is used.", false, "",
"file");
TCLAP::ValueArg<std::string> outArg(
"o", "out", "Verification result: success | failure. If omitted stdout is used.", false, "", "file");
TCLAP::ValueArg<std::string> signArg("s", "sign", "Digest sign.", true, "", "file");
TCLAP::ValueArg<bool> unconfirmedArg("u", "unconfirmed", "Search Cards with unconfirm "
"identity. Default false",
false, "", "");
TCLAP::ValueArg<std::string> recipientArg(
"r", "recipient", "Recipient defined in format:\n"
"[id|vcard|email]:<value>\n"
"where:\n"
"if `id`, then <value> - UUID associated with Virgil Card identifier;\n"
"if `vcard`, then <value> - user's Virgil Card file stored locally;\n"
"if `email`, then <value> - user email associated with Public Key.",
true, "", "arg");
cmd.add(recipientArg);
cmd.add(unconfirmedArg);
cmd.add(signArg);
cmd.add(outArg);
cmd.add(inArg);
cmd.parse(argc, argv);
auto recipientFormat = vcli::parsePair(recipientArg.getValue());
checkFormatRecipientArg(recipientFormat);
// Prepare input
std::istream* inStream;
std::ifstream inFile;
if (inArg.getValue().empty() || inArg.getValue() == "-") {
inStream = &std::cin;
} else {
inFile.open(inArg.getValue(), std::ios::in | std::ios::binary);
if (!inFile) {
throw std::invalid_argument("can not read file: " + inArg.getValue());
}
inStream = &inFile;
}
// Verify data
vcrypto::stream::VirgilStreamDataSource dataSource(*inStream);
// Read sign
std::ifstream signFile(signArg.getValue(), std::ios::in | std::ios::binary);
if (!signFile) {
throw std::invalid_argument("can not read file: " + signArg.getValue());
}
vcrypto::VirgilByteArray sign((std::istreambuf_iterator<char>(signFile)), std::istreambuf_iterator<char>());
// Create signer
vcrypto::VirgilStreamSigner signer;
std::string type = recipientFormat.first;
std::string value = recipientFormat.second;
std::vector<vsdk::models::CardModel> recipientCards =
vcli::getRecipientCards(type, value, unconfirmedArg.getValue());
for (const auto& recipientCard : recipientCards) {
bool verified = signer.verify(dataSource, sign, recipientCard.getPublicKey().getKey());
std::string recipientCardId = recipientCard.getId();
if (verified) {
vcli::writeBytes(outArg.getValue(), "card-id " + recipientCardId + " - success");
return EXIT_SUCCESS;
} else {
vcli::writeBytes(outArg.getValue(), "card-id " + recipientCardId + " - failure");
return EXIT_FAILURE;
}
}
} catch (TCLAP::ArgException& exception) {
std::cerr << "verify. Error: " << exception.error() << " for arg " << exception.argId() << std::endl;
return EXIT_FAILURE;
} catch (std::exception& exception) {
std::cerr << "verify. Error: " << exception.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void checkFormatRecipientArg(const std::pair<std::string, std::string>& pairRecipientArg) {
const std::string type = pairRecipientArg.first;
if (type != "id" && type != "vcard" && type != "email") {
throw std::invalid_argument("invalid type format: " + type + ". Expected format: '<key>:<value>'. "
"Where <key> = [id|vcard|email]");
}
}
<commit_msg>Add '[key]:<value>' pub-key:public.vkey to arg -r, recipirnt *arg*<commit_after>/**
* Copyright (C) 2015 Virgil Security Inc.
*
* Lead Maintainer: Virgil Security Inc. <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* (1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* (2) 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.
*
* (3) Neither the name of the copyright holder 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 AUTHOR ''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 AUTHOR 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 <fstream>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <tclap/CmdLine.h>
#include <virgil/crypto/VirgilByteArray.h>
#include <virgil/crypto/VirgilStreamSigner.h>
#include <virgil/crypto/stream/VirgilStreamDataSource.h>
#include <virgil/sdk/models/CardModel.h>
#include <cli/version.h>
#include <cli/pair.h>
#include <cli/util.h>
namespace vcrypto = virgil::crypto;
namespace vsdk = virgil::sdk;
namespace vcli = virgil::cli;
#ifdef SPLIT_CLI
#define MAIN main
#else
#define MAIN verify_main
#endif
static void checkFormatRecipientArg(const std::pair<std::string, std::string>& pairRecipientArg);
int MAIN(int argc, char** argv) {
try {
std::string description = "Verify data and signature with given user's identifier"
" or with it Virgil Card.\n";
std::vector<std::string> examples;
examples.push_back("virgil verify -i plain.txt -s plain.txt.sign -r email:[email protected]\n");
examples.push_back("virgil verify -i plain.txt -s plain.txt.sign -r pub-key:public.vkey\n");
std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples);
// Parse arguments.
TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());
TCLAP::ValueArg<std::string> inArg("i", "in", "Data to be verified. If omitted stdin is used.", false, "",
"file");
TCLAP::ValueArg<std::string> outArg(
"o", "out", "Verification result: success | failure. If omitted stdout is used.", false, "", "file");
TCLAP::ValueArg<std::string> signArg("s", "sign", "Digest sign.", true, "", "file");
TCLAP::ValueArg<bool> unconfirmedArg("u", "unconfirmed", "Search Cards with unconfirm "
"identity. Default false",
false, "", "");
TCLAP::ValueArg<std::string> recipientArg(
"r", "recipient", "Recipient defined in format:\n"
"[id|vcard|email|pub-key]:<value>\n"
"where:\n"
"if `id`, then <value> - UUID associated with Virgil Card identifier;\n"
"if `vcard`, then <value> - user's Virgil Card file stored locally;\n"
"if `email`, then <value> - user email associated with Public Key.\n"
"if `pub-key`, then <value> - user Public Key.\n",
true, "", "arg");
cmd.add(recipientArg);
cmd.add(unconfirmedArg);
cmd.add(signArg);
cmd.add(outArg);
cmd.add(inArg);
cmd.parse(argc, argv);
auto recipientFormat = vcli::parsePair(recipientArg.getValue());
checkFormatRecipientArg(recipientFormat);
// Prepare input
std::istream* inStream;
std::ifstream inFile;
if (inArg.getValue().empty() || inArg.getValue() == "-") {
inStream = &std::cin;
} else {
inFile.open(inArg.getValue(), std::ios::in | std::ios::binary);
if (!inFile) {
throw std::invalid_argument("can not read file: " + inArg.getValue());
}
inStream = &inFile;
}
// Verify data
vcrypto::stream::VirgilStreamDataSource dataSource(*inStream);
// Read sign
std::ifstream signFile(signArg.getValue(), std::ios::in | std::ios::binary);
if (!signFile) {
throw std::invalid_argument("can not read file: " + signArg.getValue());
}
vcrypto::VirgilByteArray sign((std::istreambuf_iterator<char>(signFile)), std::istreambuf_iterator<char>());
// Create signer
vcrypto::VirgilStreamSigner signer;
std::string type = recipientFormat.first;
std::string value = recipientFormat.second;
if (type == "pub-key") {
std::string pathToPublicKey = value;
vcrypto::VirgilByteArray publicKey = vcli::readFileBytes(pathToPublicKey);
bool verified = signer.verify(dataSource, sign, publicKey);
if (verified) {
vcli::writeBytes(outArg.getValue(), "success");
return EXIT_SUCCESS;
} else {
vcli::writeBytes(outArg.getValue(), "failure");
return EXIT_FAILURE;
}
} else {
std::vector<vsdk::models::CardModel> recipientCards =
vcli::getRecipientCards(type, value, unconfirmedArg.getValue());
for (const auto& recipientCard : recipientCards) {
bool verified = signer.verify(dataSource, sign, recipientCard.getPublicKey().getKey());
std::string recipientCardId = recipientCard.getId();
if (verified) {
vcli::writeBytes(outArg.getValue(), "card-id " + recipientCardId + " - success");
return EXIT_SUCCESS;
} else {
vcli::writeBytes(outArg.getValue(), "card-id " + recipientCardId + " - failure");
return EXIT_FAILURE;
}
}
}
} catch (TCLAP::ArgException& exception) {
std::cerr << "verify. Error: " << exception.error() << " for arg " << exception.argId() << std::endl;
return EXIT_FAILURE;
} catch (std::exception& exception) {
std::cerr << "verify. Error: " << exception.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
void checkFormatRecipientArg(const std::pair<std::string, std::string>& pairRecipientArg) {
const std::string type = pairRecipientArg.first;
if (type != "id" && type != "vcard" && type != "email" && type != "pub-key") {
throw std::invalid_argument("invalid type format: " + type + ". Expected format: '<key>:<value>'. "
"Where <key> = [id|vcard|email|pub-key]");
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
This software allows for filtering in high-dimensional observation and
state spaces, as described in
M. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.
Probabilistic Object Tracking using a Range Camera
IEEE/RSJ Intl Conf on Intelligent Robots and Systems, 2013
In a publication based on this software pleace cite the above reference.
Copyright (C) 2014 Manuel Wuthrich
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 3 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, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#include <vector>
#include <limits>
#include <string>
#include <algorithm>
#include <cmath>
#include <memory>
#include <Eigen/Core>
#include <fl/util/math.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/profiling.hpp>
#include <fl/util/assertions.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/interface/standard_gaussian_mapping.hpp>
#include <ff/utils/helper_functions.hpp>
#include <ff/distributions/sum_of_deltas.hpp>
#include <ff/models/observation_models/interfaces/rao_blackwell_observation_model.hpp>
namespace fl
{
/// \todo MISSING DOC. MISSING UTESTS
template<typename ProcessModel, typename ObservationModel>
class RaoBlackwellCoordinateParticleFilter
{
public:
typedef typename Traits<ProcessModel>::Scalar Scalar;
typedef typename Traits<ProcessModel>::State State;
typedef typename Traits<ProcessModel>::Input Input;
typedef typename Traits<ProcessModel>::Noise Noise;
typedef typename ObservationModel::Observation Observation;
// state distribution
typedef SumOfDeltas<State> StateDistributionType;
public:
RaoBlackwellCoordinateParticleFilter(
const std::shared_ptr<ProcessModel> process_model,
const std::shared_ptr<ObservationModel> observation_model,
const std::vector<std::vector<size_t>>& sampling_blocks,
const Scalar& max_kl_divergence = 0):
observation_model_(observation_model),
process_model_(process_model),
max_kl_divergence_(max_kl_divergence)
{
// static_assert_base(
// ProcessModel,
// StationaryProcessModel<State, Input>);
static_assert_base(
ProcessModel,
StandardGaussianMapping<State, Noise>);
static_assert_base(
ObservationModel,
RaoBlackwellObservationModel<State, Observation>);
SamplingBlocks(sampling_blocks);
}
virtual ~RaoBlackwellCoordinateParticleFilter() { }
public:
void Filter(const Observation& observation,
const Scalar& delta_time,
const Input& input)
{
observation_model_->SetObservation(observation, delta_time);
loglikes_ = std::vector<Scalar>(samples_.size(), 0);
noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->standard_variate_dimension()));
next_samples_ = samples_;
for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++)
{
INIT_PROFILING;
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++)
noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.sample()(0);
}
MEASURE("sampling");
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
// process_model_->condition(delta_time,
// samples_[particle_index],
// input);
// next_samples_[particle_index] = process_model_->map_standard_normal(noises_[particle_index]);
next_samples_[particle_index] =
process_model_->predict_state(delta_time,
samples_[particle_index],
noises_[particle_index],
input);
}
MEASURE("propagation");
bool update_occlusions = (block_index == sampling_blocks_.size()-1);
std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_,
indices_,
update_occlusions);
MEASURE("evaluation");
std::vector<Scalar> delta_loglikes(new_loglikes.size());
for(size_t i = 0; i < delta_loglikes.size(); i++)
delta_loglikes[i] = new_loglikes[i] - loglikes_[i];
loglikes_ = new_loglikes;
UpdateWeights(delta_loglikes);
MEASURE("updating weights");
}
samples_ = next_samples_;
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
void Resample(const size_t& sample_count)
{
std::vector<State> samples(sample_count);
std::vector<size_t> indices(sample_count);
std::vector<Noise> noises(sample_count);
std::vector<State> next_samples(sample_count);
std::vector<Scalar> loglikes(sample_count);
hf::DiscreteDistribution sampler(log_weights_);
for(size_t i = 0; i < sample_count; i++)
{
size_t index = sampler.sample();
samples[i] = samples_[index];
indices[i] = indices_[index];
noises[i] = noises_[index];
next_samples[i] = next_samples_[index];
loglikes[i] = loglikes_[index];
}
samples_ = samples;
indices_ = indices;
noises_ = noises;
next_samples_ = next_samples;
loglikes_ = loglikes;
log_weights_ = std::vector<Scalar>(samples_.size(), 0.);
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
private:
// O(6n + nlog(n)) might be reducible to O(4n)
void UpdateWeights(std::vector<Scalar> log_weight_diffs)
{
for(size_t i = 0; i < log_weight_diffs.size(); i++)
log_weights_[i] += log_weight_diffs[i];
std::vector<Scalar> weights = log_weights_;
// descendant sorting
std::sort(weights.begin(), weights.end(), std::greater<Scalar>());
for(int i = weights.size() - 1; i >= 0; i--)
weights[i] -= weights[0];
std::for_each(weights.begin(), weights.end(), [](Scalar& w){ w = std::exp(w); });
weights = fl::normalize(weights, Scalar(1));
// compute KL divergence to uniform distribution KL(p|u)
Scalar kl_divergence = std::log(Scalar(weights.size()));
for(size_t i = 0; i < weights.size(); i++)
{
Scalar information = - std::log(weights[i]) * weights[i];
if(!std::isfinite(information))
information = 0; // the limit for weight -> 0 is equal to 0
kl_divergence -= information;
}
if(kl_divergence > max_kl_divergence_)
Resample(samples_.size());
}
public:
// set
void Samples(const std::vector<State >& samples)
{
samples_ = samples;
indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset();
log_weights_ = std::vector<Scalar>(samples_.size(), 0);
}
void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks)
{
sampling_blocks_ = sampling_blocks;
// make sure sizes are consistent
size_t dimension = 0;
for(size_t i = 0; i < sampling_blocks_.size(); i++)
for(size_t j = 0; j < sampling_blocks_[i].size(); j++)
dimension++;
if(dimension != process_model_->standard_variate_dimension())
{
std::cout << "the dimension of the sampling blocks is " << dimension
<< " while the dimension of the noise is "
<< process_model_->standard_variate_dimension() << std::endl;
exit(-1);
}
}
// get
const std::vector<State>& Samples() const
{
return samples_;
}
StateDistributionType& StateDistribution()
{
return state_distribution_;
}
private:
// internal state TODO: THIS COULD BE MADE MORE COMPACT!!
StateDistributionType state_distribution_;
std::vector<State > samples_;
std::vector<size_t> indices_;
std::vector<Scalar> log_weights_;
std::vector<Noise> noises_;
std::vector<State> next_samples_;
std::vector<Scalar> loglikes_;
// observation model
std::shared_ptr<ObservationModel> observation_model_;
// process model
std::shared_ptr<ProcessModel> process_model_;
// parameters
std::vector<std::vector<size_t>> sampling_blocks_;
Scalar max_kl_divergence_;
// distribution for sampling
Gaussian<Eigen::Matrix<Scalar,1,1>> unit_gaussian_;
};
}
#endif
<commit_msg>Added static_assert_base for the ProcessModelInterface. Removed a loop within Filter()<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file integrated_damped_wiener_process_model.hpp
* \date 05/25/2014
* \author Manuel Wuthrich ([email protected])
* \author Jan Issac ([email protected])
*/
#ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP
#include <vector>
#include <limits>
#include <string>
#include <algorithm>
#include <cmath>
#include <memory>
#include <Eigen/Core>
#include <fl/util/math.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/profiling.hpp>
#include <fl/util/assertions.hpp>
#include <fl/distribution/gaussian.hpp>
#include <fl/distribution/sum_of_deltas.hpp>
#include <fl/distribution/interface/standard_gaussian_mapping.hpp>
#include <fl/model/process/process_model_interface.hpp>
#include <ff/utils/helper_functions.hpp>
#include <ff/models/observation_models/interfaces/rao_blackwell_observation_model.hpp>
namespace fl
{
/// \todo MISSING DOC. MISSING UTESTS
template<typename ProcessModel, typename ObservationModel>
class RaoBlackwellCoordinateParticleFilter
{
public:
typedef typename Traits<ProcessModel>::Scalar Scalar;
typedef typename Traits<ProcessModel>::State State;
typedef typename Traits<ProcessModel>::Input Input;
typedef typename Traits<ProcessModel>::Noise Noise;
typedef typename ObservationModel::Observation Observation;
// state distribution
typedef SumOfDeltas<State> StateDistributionType;
public:
RaoBlackwellCoordinateParticleFilter(
const std::shared_ptr<ProcessModel> process_model,
const std::shared_ptr<ObservationModel> observation_model,
const std::vector<std::vector<size_t>>& sampling_blocks,
const Scalar& max_kl_divergence = 0):
observation_model_(observation_model),
process_model_(process_model),
max_kl_divergence_(max_kl_divergence)
{
static_assert_base(
ProcessModel,
ProcessModelInterface<State, Noise, Input>);
static_assert_base(
ProcessModel,
StandardGaussianMapping<State, Noise>);
static_assert_base(
ObservationModel,
RaoBlackwellObservationModel<State, Observation>);
SamplingBlocks(sampling_blocks);
}
virtual ~RaoBlackwellCoordinateParticleFilter() { }
public:
void Filter(const Observation& observation,
const Scalar& delta_time,
const Input& input)
{
observation_model_->SetObservation(observation, delta_time);
loglikes_ = std::vector<Scalar>(samples_.size(), 0);
noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->noise_dimension()));
next_samples_ = samples_;
for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++)
{
for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)
{
for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++)
noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.sample()(0);
next_samples_[particle_index] =
process_model_->predict_state(delta_time,
samples_[particle_index],
noises_[particle_index],
input);
}
bool update_occlusions = (block_index == sampling_blocks_.size()-1);
std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_,
indices_,
update_occlusions);
std::vector<Scalar> delta_loglikes(new_loglikes.size());
for(size_t i = 0; i < delta_loglikes.size(); i++)
delta_loglikes[i] = new_loglikes[i] - loglikes_[i];
loglikes_ = new_loglikes;
UpdateWeights(delta_loglikes);
}
samples_ = next_samples_;
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
void Resample(const size_t& sample_count)
{
std::vector<State> samples(sample_count);
std::vector<size_t> indices(sample_count);
std::vector<Noise> noises(sample_count);
std::vector<State> next_samples(sample_count);
std::vector<Scalar> loglikes(sample_count);
hf::DiscreteDistribution sampler(log_weights_);
for(size_t i = 0; i < sample_count; i++)
{
size_t index = sampler.sample();
samples[i] = samples_[index];
indices[i] = indices_[index];
noises[i] = noises_[index];
next_samples[i] = next_samples_[index];
loglikes[i] = loglikes_[index];
}
samples_ = samples;
indices_ = indices;
noises_ = noises;
next_samples_ = next_samples;
loglikes_ = loglikes;
log_weights_ = std::vector<Scalar>(samples_.size(), 0.);
state_distribution_.SetDeltas(samples_); // not sure whether this is the right place
}
private:
// O(6n + nlog(n)) might be reducible to O(4n)
void UpdateWeights(std::vector<Scalar> log_weight_diffs)
{
for(size_t i = 0; i < log_weight_diffs.size(); i++)
log_weights_[i] += log_weight_diffs[i];
std::vector<Scalar> weights = log_weights_;
// descendant sorting
std::sort(weights.begin(), weights.end(), std::greater<Scalar>());
for(int i = weights.size() - 1; i >= 0; i--)
weights[i] -= weights[0];
std::for_each(weights.begin(), weights.end(), [](Scalar& w){ w = std::exp(w); });
weights = fl::normalize(weights, Scalar(1));
// compute KL divergence to uniform distribution KL(p|u)
Scalar kl_divergence = std::log(Scalar(weights.size()));
for(size_t i = 0; i < weights.size(); i++)
{
Scalar information = - std::log(weights[i]) * weights[i];
if(!std::isfinite(information))
information = 0; // the limit for weight -> 0 is equal to 0
kl_divergence -= information;
}
if(kl_divergence > max_kl_divergence_)
Resample(samples_.size());
}
public:
// set
void Samples(const std::vector<State >& samples)
{
samples_ = samples;
indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset();
log_weights_ = std::vector<Scalar>(samples_.size(), 0);
}
void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks)
{
sampling_blocks_ = sampling_blocks;
// make sure sizes are consistent
size_t dimension = 0;
for(size_t i = 0; i < sampling_blocks_.size(); i++)
for(size_t j = 0; j < sampling_blocks_[i].size(); j++)
dimension++;
if(dimension != process_model_->standard_variate_dimension())
{
std::cout << "the dimension of the sampling blocks is " << dimension
<< " while the dimension of the noise is "
<< process_model_->standard_variate_dimension() << std::endl;
exit(-1);
}
}
// get
const std::vector<State>& Samples() const
{
return samples_;
}
StateDistributionType& StateDistribution()
{
return state_distribution_;
}
private:
// internal state TODO: THIS COULD BE MADE MORE COMPACT!!
StateDistributionType state_distribution_;
std::vector<State > samples_;
std::vector<size_t> indices_;
std::vector<Scalar> log_weights_;
std::vector<Noise> noises_;
std::vector<State> next_samples_;
std::vector<Scalar> loglikes_;
// observation model
std::shared_ptr<ObservationModel> observation_model_;
// process model
std::shared_ptr<ProcessModel> process_model_;
// parameters
std::vector<std::vector<size_t>> sampling_blocks_;
Scalar max_kl_divergence_;
// distribution for sampling
Gaussian<Eigen::Matrix<Scalar,1,1>> unit_gaussian_;
};
}
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin_explorer.
*
* libbitcoin_explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// #include "precompile.hpp"
#include <bitcoin/explorer/commands/input-set.hpp>
#include <iostream>
#include <cstdint>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/primitives/transaction.hpp>
#include <bitcoin/explorer/utility/utility.hpp>
using namespace bc;
using namespace bc::explorer;
using namespace bc::explorer::commands;
using namespace bc::explorer::primitives;
console_result input_set::invoke(std::ostream& output, std::ostream& error)
{
// Bound parameters.
const auto index = get_index_option();
const auto& transaction_original = get_transaction_argument();
const auto& script = get_signature_and_pubkey_script_argument();
// Clone so we can keep arguments const.
auto transaction_copy = transaction(transaction_original);
auto& tx = transaction_copy.data();
if (tx.inputs.size() < index)
{
error << BX_INPUT_SET_INDEX_OUT_OF_RANGE << std::endl;
return console_result::failure;
}
tx.inputs[index].script = script_to_raw_data_script(script);
output << transaction_copy << std::endl;
return console_result::okay;
}<commit_msg>Fix index bounds check.<commit_after>/**
* Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin_explorer.
*
* libbitcoin_explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// #include "precompile.hpp"
#include <bitcoin/explorer/commands/input-set.hpp>
#include <iostream>
#include <cstdint>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/primitives/transaction.hpp>
#include <bitcoin/explorer/utility/utility.hpp>
using namespace bc;
using namespace bc::explorer;
using namespace bc::explorer::commands;
using namespace bc::explorer::primitives;
console_result input_set::invoke(std::ostream& output, std::ostream& error)
{
// Bound parameters.
const auto index = get_index_option();
const auto& transaction_original = get_transaction_argument();
const auto& script = get_signature_and_pubkey_script_argument();
// Clone so we can keep arguments const.
auto transaction_copy = transaction(transaction_original);
auto& tx = transaction_copy.data();
if (tx.inputs.size() <= index)
{
error << BX_INPUT_SET_INDEX_OUT_OF_RANGE << std::endl;
return console_result::failure;
}
tx.inputs[index].script = script_to_raw_data_script(script);
output << transaction_copy << std::endl;
return console_result::okay;
}<|endoftext|> |
<commit_before><commit_msg>Updated to use MemoryManager<commit_after><|endoftext|> |
<commit_before>//
// Copyright (c) 2017 The Khronos Group 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 "testBase.h"
#include "harness/imageHelpers.h"
#include <stdlib.h>
#include <ctype.h>
int test_get_sampler_info_compatibility(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
int error;
size_t size;
PASSIVE_REQUIRE_IMAGE_SUPPORT( deviceID )
clSamplerWrapper sampler = clCreateSampler( context, CL_TRUE, CL_ADDRESS_CLAMP, CL_FILTER_LINEAR, &error );
test_error( error, "Unable to create sampler to test with" );
cl_uint refCount;
error = clGetSamplerInfo( sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof( refCount ), &refCount, &size );
test_error( error, "Unable to get sampler ref count" );
if( size != sizeof( refCount ) )
{
log_error( "ERROR: Returned size of sampler refcount does not validate! (expected %d, got %d)\n", (int)sizeof( refCount ), (int)size );
return -1;
}
cl_context otherCtx;
error = clGetSamplerInfo( sampler, CL_SAMPLER_CONTEXT, sizeof( otherCtx ), &otherCtx, &size );
test_error( error, "Unable to get sampler context" );
if( otherCtx != context )
{
log_error( "ERROR: Sampler context does not validate! (expected %p, got %p)\n", context, otherCtx );
return -1;
}
if( size != sizeof( otherCtx ) )
{
log_error( "ERROR: Returned size of sampler context does not validate! (expected %d, got %d)\n", (int)sizeof( otherCtx ), (int)size );
return -1;
}
cl_addressing_mode mode;
error = clGetSamplerInfo( sampler, CL_SAMPLER_ADDRESSING_MODE, sizeof( mode ), &mode, &size );
test_error( error, "Unable to get sampler addressing mode" );
if( mode != CL_ADDRESS_CLAMP )
{
log_error( "ERROR: Sampler addressing mode does not validate! (expected %d, got %d)\n", (int)CL_ADDRESS_CLAMP, (int)mode );
return -1;
}
if( size != sizeof( mode ) )
{
log_error( "ERROR: Returned size of sampler addressing mode does not validate! (expected %d, got %d)\n", (int)sizeof( mode ), (int)size );
return -1;
}
cl_filter_mode fmode;
error = clGetSamplerInfo( sampler, CL_SAMPLER_FILTER_MODE, sizeof( fmode ), &fmode, &size );
test_error( error, "Unable to get sampler filter mode" );
if( fmode != CL_FILTER_LINEAR )
{
log_error( "ERROR: Sampler filter mode does not validate! (expected %d, got %d)\n", (int)CL_FILTER_LINEAR, (int)fmode );
return -1;
}
if( size != sizeof( fmode ) )
{
log_error( "ERROR: Returned size of sampler filter mode does not validate! (expected %d, got %d)\n", (int)sizeof( fmode ), (int)size );
return -1;
}
cl_int norm;
error = clGetSamplerInfo( sampler, CL_SAMPLER_NORMALIZED_COORDS, sizeof( norm ), &norm, &size );
test_error( error, "Unable to get sampler normalized flag" );
if( norm != CL_TRUE )
{
log_error( "ERROR: Sampler normalized flag does not validate! (expected %d, got %d)\n", (int)CL_TRUE, (int)norm );
return -1;
}
if( size != sizeof( norm ) )
{
log_error( "ERROR: Returned size of sampler normalized flag does not validate! (expected %d, got %d)\n", (int)sizeof( norm ), (int)size );
return -1;
}
return 0;
}
#define TEST_COMMAND_QUEUE_PARAM( queue, paramName, val, expected, name, type, cast ) \
error = clGetCommandQueueInfo( queue, paramName, sizeof( val ), &val, &size ); \
test_error( error, "Unable to get command queue " name ); \
if( val != expected ) \
{ \
log_error( "ERROR: Command queue " name " did not validate! (expected " type ", got " type ")\n", (cast)expected, (cast)val ); \
return -1; \
} \
if( size != sizeof( val ) ) \
{ \
log_error( "ERROR: Returned size of command queue " name " does not validate! (expected %d, got %d)\n", (int)sizeof( val ), (int)size ); \
return -1; \
}
int test_get_command_queue_info_compatibility(cl_device_id deviceID, cl_context context, cl_command_queue ignoreQueue, int num_elements)
{
int error;
size_t size;
cl_command_queue_properties device_props;
clGetDeviceInfo(deviceID, CL_DEVICE_QUEUE_PROPERTIES, sizeof(device_props), &device_props, NULL);
log_info("CL_DEVICE_QUEUE_PROPERTIES is %d\n", (int)device_props);
clCommandQueueWrapper queue = clCreateCommandQueue( context, deviceID, device_props, &error );
test_error( error, "Unable to create command queue to test with" );
cl_uint refCount;
error = clGetCommandQueueInfo( queue, CL_QUEUE_REFERENCE_COUNT, sizeof( refCount ), &refCount, &size );
test_error( error, "Unable to get command queue reference count" );
if( size != sizeof( refCount ) )
{
log_error( "ERROR: Returned size of command queue reference count does not validate! (expected %d, got %d)\n", (int)sizeof( refCount ), (int)size );
return -1;
}
cl_context otherCtx;
TEST_COMMAND_QUEUE_PARAM( queue, CL_QUEUE_CONTEXT, otherCtx, context, "context", "%p", cl_context )
cl_device_id otherDevice;
error = clGetCommandQueueInfo( queue, CL_QUEUE_DEVICE, sizeof(otherDevice), &otherDevice, &size);
test_error(error, "clGetCommandQueue failed.");
if (size != sizeof(cl_device_id)) {
log_error( " ERROR: Returned size of command queue CL_QUEUE_DEVICE does not validate! (expected %d, got %d)\n", (int)sizeof( otherDevice ), (int)size );
return -1;
}
/* Since the device IDs are opaque types we check the CL_DEVICE_VENDOR_ID which is unique for identical hardware. */
cl_uint otherDevice_vid, deviceID_vid;
error = clGetDeviceInfo(otherDevice, CL_DEVICE_VENDOR_ID, sizeof(otherDevice_vid), &otherDevice_vid, NULL );
test_error( error, "Unable to get device CL_DEVICE_VENDOR_ID" );
error = clGetDeviceInfo(deviceID, CL_DEVICE_VENDOR_ID, sizeof(deviceID_vid), &deviceID_vid, NULL );
test_error( error, "Unable to get device CL_DEVICE_VENDOR_ID" );
if( otherDevice_vid != deviceID_vid )
{
log_error( "ERROR: Incorrect device returned for queue! (Expected vendor ID 0x%x, got 0x%x)\n", deviceID_vid, otherDevice_vid );
return -1;
}
cl_command_queue_properties props;
TEST_COMMAND_QUEUE_PARAM( queue, CL_QUEUE_PROPERTIES, props, (unsigned int)( device_props ), "properties", "%d", unsigned int )
return 0;
}
<commit_msg>api: Allow vendor flags (#957)<commit_after>//
// Copyright (c) 2017 The Khronos Group 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 "testBase.h"
#include "harness/imageHelpers.h"
#include <stdlib.h>
#include <ctype.h>
int test_get_sampler_info_compatibility(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements)
{
int error;
size_t size;
PASSIVE_REQUIRE_IMAGE_SUPPORT( deviceID )
clSamplerWrapper sampler = clCreateSampler( context, CL_TRUE, CL_ADDRESS_CLAMP, CL_FILTER_LINEAR, &error );
test_error( error, "Unable to create sampler to test with" );
cl_uint refCount;
error = clGetSamplerInfo( sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof( refCount ), &refCount, &size );
test_error( error, "Unable to get sampler ref count" );
if( size != sizeof( refCount ) )
{
log_error( "ERROR: Returned size of sampler refcount does not validate! (expected %d, got %d)\n", (int)sizeof( refCount ), (int)size );
return -1;
}
cl_context otherCtx;
error = clGetSamplerInfo( sampler, CL_SAMPLER_CONTEXT, sizeof( otherCtx ), &otherCtx, &size );
test_error( error, "Unable to get sampler context" );
if( otherCtx != context )
{
log_error( "ERROR: Sampler context does not validate! (expected %p, got %p)\n", context, otherCtx );
return -1;
}
if( size != sizeof( otherCtx ) )
{
log_error( "ERROR: Returned size of sampler context does not validate! (expected %d, got %d)\n", (int)sizeof( otherCtx ), (int)size );
return -1;
}
cl_addressing_mode mode;
error = clGetSamplerInfo( sampler, CL_SAMPLER_ADDRESSING_MODE, sizeof( mode ), &mode, &size );
test_error( error, "Unable to get sampler addressing mode" );
if( mode != CL_ADDRESS_CLAMP )
{
log_error( "ERROR: Sampler addressing mode does not validate! (expected %d, got %d)\n", (int)CL_ADDRESS_CLAMP, (int)mode );
return -1;
}
if( size != sizeof( mode ) )
{
log_error( "ERROR: Returned size of sampler addressing mode does not validate! (expected %d, got %d)\n", (int)sizeof( mode ), (int)size );
return -1;
}
cl_filter_mode fmode;
error = clGetSamplerInfo( sampler, CL_SAMPLER_FILTER_MODE, sizeof( fmode ), &fmode, &size );
test_error( error, "Unable to get sampler filter mode" );
if( fmode != CL_FILTER_LINEAR )
{
log_error( "ERROR: Sampler filter mode does not validate! (expected %d, got %d)\n", (int)CL_FILTER_LINEAR, (int)fmode );
return -1;
}
if( size != sizeof( fmode ) )
{
log_error( "ERROR: Returned size of sampler filter mode does not validate! (expected %d, got %d)\n", (int)sizeof( fmode ), (int)size );
return -1;
}
cl_int norm;
error = clGetSamplerInfo( sampler, CL_SAMPLER_NORMALIZED_COORDS, sizeof( norm ), &norm, &size );
test_error( error, "Unable to get sampler normalized flag" );
if( norm != CL_TRUE )
{
log_error( "ERROR: Sampler normalized flag does not validate! (expected %d, got %d)\n", (int)CL_TRUE, (int)norm );
return -1;
}
if( size != sizeof( norm ) )
{
log_error( "ERROR: Returned size of sampler normalized flag does not validate! (expected %d, got %d)\n", (int)sizeof( norm ), (int)size );
return -1;
}
return 0;
}
#define TEST_COMMAND_QUEUE_PARAM( queue, paramName, val, expected, name, type, cast ) \
error = clGetCommandQueueInfo( queue, paramName, sizeof( val ), &val, &size ); \
test_error( error, "Unable to get command queue " name ); \
if( val != expected ) \
{ \
log_error( "ERROR: Command queue " name " did not validate! (expected " type ", got " type ")\n", (cast)expected, (cast)val ); \
return -1; \
} \
if( size != sizeof( val ) ) \
{ \
log_error( "ERROR: Returned size of command queue " name " does not validate! (expected %d, got %d)\n", (int)sizeof( val ), (int)size ); \
return -1; \
}
int test_get_command_queue_info_compatibility(cl_device_id deviceID, cl_context context, cl_command_queue ignoreQueue, int num_elements)
{
int error;
size_t size;
cl_command_queue_properties device_props;
clGetDeviceInfo(deviceID, CL_DEVICE_QUEUE_PROPERTIES, sizeof(device_props), &device_props, NULL);
log_info("CL_DEVICE_QUEUE_PROPERTIES is %d\n", (int)device_props);
// Mask off vendor extension properties. Only test standard OpenCL
// properties
device_props &=
CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_PROFILING_ENABLE;
clCommandQueueWrapper queue = clCreateCommandQueue( context, deviceID, device_props, &error );
test_error( error, "Unable to create command queue to test with" );
cl_uint refCount;
error = clGetCommandQueueInfo( queue, CL_QUEUE_REFERENCE_COUNT, sizeof( refCount ), &refCount, &size );
test_error( error, "Unable to get command queue reference count" );
if( size != sizeof( refCount ) )
{
log_error( "ERROR: Returned size of command queue reference count does not validate! (expected %d, got %d)\n", (int)sizeof( refCount ), (int)size );
return -1;
}
cl_context otherCtx;
TEST_COMMAND_QUEUE_PARAM( queue, CL_QUEUE_CONTEXT, otherCtx, context, "context", "%p", cl_context )
cl_device_id otherDevice;
error = clGetCommandQueueInfo( queue, CL_QUEUE_DEVICE, sizeof(otherDevice), &otherDevice, &size);
test_error(error, "clGetCommandQueue failed.");
if (size != sizeof(cl_device_id)) {
log_error( " ERROR: Returned size of command queue CL_QUEUE_DEVICE does not validate! (expected %d, got %d)\n", (int)sizeof( otherDevice ), (int)size );
return -1;
}
/* Since the device IDs are opaque types we check the CL_DEVICE_VENDOR_ID which is unique for identical hardware. */
cl_uint otherDevice_vid, deviceID_vid;
error = clGetDeviceInfo(otherDevice, CL_DEVICE_VENDOR_ID, sizeof(otherDevice_vid), &otherDevice_vid, NULL );
test_error( error, "Unable to get device CL_DEVICE_VENDOR_ID" );
error = clGetDeviceInfo(deviceID, CL_DEVICE_VENDOR_ID, sizeof(deviceID_vid), &deviceID_vid, NULL );
test_error( error, "Unable to get device CL_DEVICE_VENDOR_ID" );
if( otherDevice_vid != deviceID_vid )
{
log_error( "ERROR: Incorrect device returned for queue! (Expected vendor ID 0x%x, got 0x%x)\n", deviceID_vid, otherDevice_vid );
return -1;
}
cl_command_queue_properties props;
TEST_COMMAND_QUEUE_PARAM( queue, CL_QUEUE_PROPERTIES, props, (unsigned int)( device_props ), "properties", "%d", unsigned int )
return 0;
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief ChipSpiMasterLowLevel class implementation for SPIv1 in STM32
*
* \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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 "distortos/chip/ChipSpiMasterLowLevel.hpp"
#include "distortos/chip/STM32-SPIv1-SpiPeripheral.hpp"
#include "distortos/devices/communication/SpiMasterBase.hpp"
#include "distortos/assert.h"
#include <cerrno>
namespace distortos
{
namespace chip
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Gets current word length of SPI peripheral.
*
* \param [in] cr2 is the current value of CR1 register in SPI module
*
* \return current word length, bits, {8, 16}
*/
constexpr uint8_t getWordLength(const uint16_t cr1)
{
return (cr1 & SPI_CR1_DFF) == 0 ? 8 : 16;
}
/**
* \brief Modifies current value of CR1 register.
*
* \param [in] spiPeripheral is a reference to raw SPI peripheral
* \param [in] clear is the bitmask of bits that should be cleared in CR1 register
* \param [in] set is the bitmask of bits that should be set in CR1 register
*/
void modifyCr1(const SpiPeripheral& spiPeripheral, const uint32_t clear, const uint32_t set)
{
spiPeripheral.writeCr1((spiPeripheral.readCr1() & ~clear) | set);
}
/**
* \brief Modifies current value of CR2 register.
*
* \param [in] spiPeripheral is a reference to raw SPI peripheral
* \param [in] clear is the bitmask of bits that should be cleared in CR2 register
* \param [in] set is the bitmask of bits that should be set in CR2 register
*/
void modifyCr2(const SpiPeripheral& spiPeripheral, const uint32_t clear, const uint32_t set)
{
spiPeripheral.writeCr2((spiPeripheral.readCr2() & ~clear) | set);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
ChipSpiMasterLowLevel::~ChipSpiMasterLowLevel()
{
if (isStarted() == false)
return;
// reset peripheral
spiPeripheral_.writeCr1({});
spiPeripheral_.writeCr2({});
}
std::pair<int, uint32_t> ChipSpiMasterLowLevel::configure(const devices::SpiMode mode, const uint32_t clockFrequency,
const uint8_t wordLength, const bool lsbFirst, const uint32_t dummyData)
{
if (wordLength != 8 && wordLength != 16)
return {EINVAL, {}};
if (isStarted() == false)
return {EBADF, {}};
if (isTransferInProgress() == true)
return {EBUSY, {}};
const auto peripheralFrequency = spiPeripheral_.getPeripheralFrequency();
const auto divider = (peripheralFrequency + clockFrequency - 1) / clockFrequency;
if (divider > 256)
return {EINVAL, {}};
const uint32_t br = divider <= 2 ? 0 : 31 - __builtin_clz(divider - 1);
// value of DFF bit (which determines word length) must be changed only when SPI peripheral is disabled
const auto disablePeripheral = wordLength != getWordLength(spiPeripheral_.readCr1());
if (disablePeripheral == true)
modifyCr1(spiPeripheral_, SPI_CR1_SPE, {}); // disable peripheral
modifyCr1(spiPeripheral_, SPI_CR1_DFF | SPI_CR1_LSBFIRST | SPI_CR1_BR | SPI_CR1_CPOL | SPI_CR1_CPHA,
(wordLength == 16) << SPI_CR1_DFF_Pos |
lsbFirst << SPI_CR1_LSBFIRST_Pos |
br << SPI_CR1_BR_Pos |
(mode == devices::SpiMode::cpol1cpha0 || mode == devices::SpiMode::cpol1cpha1) << SPI_CR1_CPOL_Pos |
(mode == devices::SpiMode::cpol0cpha1 || mode == devices::SpiMode::cpol1cpha1) << SPI_CR1_CPHA_Pos);
if (disablePeripheral == true)
modifyCr1(spiPeripheral_, {}, SPI_CR1_SPE); // enable peripheral
dummyData_ = dummyData;
return {{}, peripheralFrequency / (1 << (br + 1))};
}
void ChipSpiMasterLowLevel::interruptHandler()
{
bool done {};
const auto sr = spiPeripheral_.readSr();
const auto cr2 = spiPeripheral_.readCr2();
const auto wordLength = getWordLength(spiPeripheral_.readCr1());
if ((sr & SPI_SR_OVR) != 0 && (cr2 & SPI_CR2_ERRIE) != 0) // overrun error?
{
spiPeripheral_.readDr();
spiPeripheral_.readSr(); // clears OVR flag
modifyCr2(spiPeripheral_, SPI_CR2_TXEIE, {}); // disable TXE interrupt
if ((sr & SPI_SR_BSY) == 0)
done = true;
}
else if ((sr & SPI_SR_RXNE) != 0 && (cr2 & SPI_CR2_RXNEIE) != 0) // read?
{
const uint16_t word = spiPeripheral_.readDr();
const auto readBuffer = readBuffer_;
auto readPosition = readPosition_;
if (readBuffer != nullptr)
{
readBuffer[readPosition++] = word;
if (wordLength == 16)
readBuffer[readPosition++] = word >> 8;
}
else
readPosition += wordLength / 8;
readPosition_ = readPosition;
if (readPosition == size_)
done = true;
else
modifyCr2(spiPeripheral_, {}, SPI_CR2_TXEIE); // enable TXE interrupt
}
else if ((sr & SPI_SR_TXE) != 0 && (cr2 & SPI_CR2_TXEIE) != 0) // write?
{
const auto writeBuffer = writeBuffer_;
auto writePosition = writePosition_;
uint16_t word;
if (writeBuffer != nullptr)
{
const uint16_t characterLow = writeBuffer[writePosition++];
const uint16_t characterHigh = wordLength == 16 ? writeBuffer[writePosition++] : 0;
word = characterLow | characterHigh << 8;
}
else
{
writePosition += wordLength / 8;
word = dummyData_;
}
writePosition_ = writePosition;
spiPeripheral_.writeDr(word);
modifyCr2(spiPeripheral_, SPI_CR2_TXEIE, {}); // disable TXE interrupt
}
if (done == true) // transfer finished of failed?
{
// disable TXE, RXNE and ERR interrupts
modifyCr2(spiPeripheral_, SPI_CR2_TXEIE | SPI_CR2_RXNEIE | SPI_CR2_ERRIE, {});
writePosition_ = {};
const auto bytesTransfered = readPosition_;
readPosition_ = {};
size_ = {};
writeBuffer_ = {};
readBuffer_ = {};
const auto spiMasterBase = spiMasterBase_;
spiMasterBase_ = nullptr;
assert(spiMasterBase != nullptr);
spiMasterBase->transferCompleteEvent(bytesTransfered);
}
}
int ChipSpiMasterLowLevel::start()
{
if (isStarted() == true)
return EBADF;
spiPeripheral_.writeCr1(SPI_CR1_SSM | SPI_CR1_SSI | SPI_CR1_SPE | SPI_CR1_BR | SPI_CR1_MSTR);
spiPeripheral_.writeCr2({});
started_ = true;
return 0;
}
int ChipSpiMasterLowLevel::startTransfer(devices::SpiMasterBase& spiMasterBase, const void* const writeBuffer,
void* const readBuffer, const size_t size)
{
if (size == 0)
return EINVAL;
if (isStarted() == false)
return EBADF;
if (isTransferInProgress() == true)
return EBUSY;
if (size % (getWordLength(spiPeripheral_.readCr1()) / 8) != 0)
return EINVAL;
spiMasterBase_ = &spiMasterBase;
readBuffer_ = static_cast<uint8_t*>(readBuffer);
writeBuffer_ = static_cast<const uint8_t*>(writeBuffer);
size_ = size;
readPosition_ = 0;
writePosition_ = 0;
// enable TXE, RXNE and ERR interrupts
modifyCr2(spiPeripheral_, {}, SPI_CR2_TXEIE | SPI_CR2_RXNEIE | SPI_CR2_ERRIE);
return 0;
}
int ChipSpiMasterLowLevel::stop()
{
if (isStarted() == false)
return EBADF;
if (isTransferInProgress() == true)
return EBUSY;
// reset peripheral
spiPeripheral_.writeCr1({});
spiPeripheral_.writeCr2({});
started_ = false;
return 0;
}
} // namespace chip
} // namespace distortos
<commit_msg>Optimize access to registers in STM32 SPIv1 ChipSpiMasterLowLevel<commit_after>/**
* \file
* \brief ChipSpiMasterLowLevel class implementation for SPIv1 in STM32
*
* \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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 "distortos/chip/ChipSpiMasterLowLevel.hpp"
#include "distortos/chip/STM32-SPIv1-SpiPeripheral.hpp"
#include "distortos/devices/communication/SpiMasterBase.hpp"
#include "distortos/assert.h"
#include <cerrno>
namespace distortos
{
namespace chip
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Gets current word length of SPI peripheral.
*
* \param [in] cr2 is the current value of CR1 register in SPI module
*
* \return current word length, bits, {8, 16}
*/
constexpr uint8_t getWordLength(const uint16_t cr1)
{
return (cr1 & SPI_CR1_DFF) == 0 ? 8 : 16;
}
/**
* \brief Modifies current value of CR1 register.
*
* \param [in] cr1 is the current value of CR1 register
* \param [in] spiPeripheral is a reference to raw SPI peripheral
* \param [in] clear is the bitmask of bits that should be cleared in CR1 register
* \param [in] set is the bitmask of bits that should be set in CR1 register
*
* \return value written to CR1 register
*/
uint32_t modifyCr1(const uint32_t cr1, const SpiPeripheral& spiPeripheral, const uint32_t clear, const uint32_t set)
{
const auto newCr1 = (cr1 & ~clear) | set;
spiPeripheral.writeCr1(newCr1);
return newCr1;
}
/**
* \brief Modifies current value of CR2 register.
*
* \param [in] cr2 is the current value of CR2 register
* \param [in] spiPeripheral is a reference to raw SPI peripheral
* \param [in] clear is the bitmask of bits that should be cleared in CR2 register
* \param [in] set is the bitmask of bits that should be set in CR2 register
*
* \return value written to CR2 register
*/
uint32_t modifyCr2(const uint32_t cr2, const SpiPeripheral& spiPeripheral, const uint32_t clear, const uint32_t set)
{
const auto newCr2 = (cr2 & ~clear) | set;
spiPeripheral.writeCr2(newCr2);
return newCr2;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
ChipSpiMasterLowLevel::~ChipSpiMasterLowLevel()
{
if (isStarted() == false)
return;
// reset peripheral
spiPeripheral_.writeCr1({});
spiPeripheral_.writeCr2({});
}
std::pair<int, uint32_t> ChipSpiMasterLowLevel::configure(const devices::SpiMode mode, const uint32_t clockFrequency,
const uint8_t wordLength, const bool lsbFirst, const uint32_t dummyData)
{
if (wordLength != 8 && wordLength != 16)
return {EINVAL, {}};
if (isStarted() == false)
return {EBADF, {}};
if (isTransferInProgress() == true)
return {EBUSY, {}};
const auto peripheralFrequency = spiPeripheral_.getPeripheralFrequency();
const auto divider = (peripheralFrequency + clockFrequency - 1) / clockFrequency;
if (divider > 256)
return {EINVAL, {}};
const uint32_t br = divider <= 2 ? 0 : 31 - __builtin_clz(divider - 1);
auto cr1 = spiPeripheral_.readCr1();
// value of DFF bit (which determines word length) must be changed only when SPI peripheral is disabled
const auto disablePeripheral = wordLength != getWordLength(cr1);
if (disablePeripheral == true)
cr1 = modifyCr1(cr1, spiPeripheral_, SPI_CR1_SPE, {}); // disable peripheral
cr1 = modifyCr1(cr1, spiPeripheral_, SPI_CR1_DFF | SPI_CR1_LSBFIRST | SPI_CR1_BR | SPI_CR1_CPOL | SPI_CR1_CPHA,
(wordLength == 16) << SPI_CR1_DFF_Pos |
lsbFirst << SPI_CR1_LSBFIRST_Pos |
br << SPI_CR1_BR_Pos |
(mode == devices::SpiMode::cpol1cpha0 || mode == devices::SpiMode::cpol1cpha1) << SPI_CR1_CPOL_Pos |
(mode == devices::SpiMode::cpol0cpha1 || mode == devices::SpiMode::cpol1cpha1) << SPI_CR1_CPHA_Pos);
if (disablePeripheral == true)
cr1 = modifyCr1(cr1, spiPeripheral_, {}, SPI_CR1_SPE); // enable peripheral
dummyData_ = dummyData;
return {{}, peripheralFrequency / (1 << (br + 1))};
}
void ChipSpiMasterLowLevel::interruptHandler()
{
bool done {};
const auto sr = spiPeripheral_.readSr();
auto cr2 = spiPeripheral_.readCr2();
const auto wordLength = getWordLength(spiPeripheral_.readCr1());
if ((sr & SPI_SR_OVR) != 0 && (cr2 & SPI_CR2_ERRIE) != 0) // overrun error?
{
spiPeripheral_.readDr();
spiPeripheral_.readSr(); // clears OVR flag
cr2 = modifyCr2(cr2, spiPeripheral_, SPI_CR2_TXEIE, {}); // disable TXE interrupt
if ((sr & SPI_SR_BSY) == 0)
done = true;
}
else if ((sr & SPI_SR_RXNE) != 0 && (cr2 & SPI_CR2_RXNEIE) != 0) // read?
{
const uint16_t word = spiPeripheral_.readDr();
const auto readBuffer = readBuffer_;
auto readPosition = readPosition_;
if (readBuffer != nullptr)
{
readBuffer[readPosition++] = word;
if (wordLength == 16)
readBuffer[readPosition++] = word >> 8;
}
else
readPosition += wordLength / 8;
readPosition_ = readPosition;
if (readPosition == size_)
done = true;
else
cr2 = modifyCr2(cr2, spiPeripheral_, {}, SPI_CR2_TXEIE); // enable TXE interrupt
}
else if ((sr & SPI_SR_TXE) != 0 && (cr2 & SPI_CR2_TXEIE) != 0) // write?
{
const auto writeBuffer = writeBuffer_;
auto writePosition = writePosition_;
uint16_t word;
if (writeBuffer != nullptr)
{
const uint16_t characterLow = writeBuffer[writePosition++];
const uint16_t characterHigh = wordLength == 16 ? writeBuffer[writePosition++] : 0;
word = characterLow | characterHigh << 8;
}
else
{
writePosition += wordLength / 8;
word = dummyData_;
}
writePosition_ = writePosition;
spiPeripheral_.writeDr(word);
cr2 = modifyCr2(cr2, spiPeripheral_, SPI_CR2_TXEIE, {}); // disable TXE interrupt
}
if (done == true) // transfer finished of failed?
{
// disable TXE, RXNE and ERR interrupts
cr2 = modifyCr2(cr2, spiPeripheral_, SPI_CR2_TXEIE | SPI_CR2_RXNEIE | SPI_CR2_ERRIE, {});
writePosition_ = {};
const auto bytesTransfered = readPosition_;
readPosition_ = {};
size_ = {};
writeBuffer_ = {};
readBuffer_ = {};
const auto spiMasterBase = spiMasterBase_;
spiMasterBase_ = nullptr;
assert(spiMasterBase != nullptr);
spiMasterBase->transferCompleteEvent(bytesTransfered);
}
}
int ChipSpiMasterLowLevel::start()
{
if (isStarted() == true)
return EBADF;
spiPeripheral_.writeCr1(SPI_CR1_SSM | SPI_CR1_SSI | SPI_CR1_SPE | SPI_CR1_BR | SPI_CR1_MSTR);
spiPeripheral_.writeCr2({});
started_ = true;
return 0;
}
int ChipSpiMasterLowLevel::startTransfer(devices::SpiMasterBase& spiMasterBase, const void* const writeBuffer,
void* const readBuffer, const size_t size)
{
if (size == 0)
return EINVAL;
if (isStarted() == false)
return EBADF;
if (isTransferInProgress() == true)
return EBUSY;
if (size % (getWordLength(spiPeripheral_.readCr1()) / 8) != 0)
return EINVAL;
spiMasterBase_ = &spiMasterBase;
readBuffer_ = static_cast<uint8_t*>(readBuffer);
writeBuffer_ = static_cast<const uint8_t*>(writeBuffer);
size_ = size;
readPosition_ = 0;
writePosition_ = 0;
// enable TXE, RXNE and ERR interrupts
modifyCr2(spiPeripheral_.readCr2(), spiPeripheral_, {}, SPI_CR2_TXEIE | SPI_CR2_RXNEIE | SPI_CR2_ERRIE);
return 0;
}
int ChipSpiMasterLowLevel::stop()
{
if (isStarted() == false)
return EBADF;
if (isTransferInProgress() == true)
return EBUSY;
// reset peripheral
spiPeripheral_.writeCr1({});
spiPeripheral_.writeCr2({});
started_ = false;
return 0;
}
} // namespace chip
} // namespace distortos
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "FileManager.h"
#include "string"
#include "StateDatabase.h"
#include <ctype.h>
#include <fstream>
//
// FileManager
//
FileManager* FileManager::mgr = NULL;
FileManager::FileManager()
{
// do nothing
}
FileManager::~FileManager()
{
mgr = NULL;
}
FileManager* FileManager::getInstance()
{
if (mgr == NULL)
mgr = new FileManager;
return mgr;
}
std::istream* FileManager::createDataInStream(
const std::string& filename,
bool binary) const
{
// choose open mode
std::ios::openmode mode = std::ios::in;
if (binary)
mode |= std::ios::binary;
const bool relative = !isAbsolute(filename);
if (relative) {
// try directory stored in DB
if (BZDB->isSet("directory")) {
std::ifstream* stream = new std::ifstream(catPath(BZDB->get("directory"),
filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
// try data directory
{
std::ifstream* stream = new std::ifstream(catPath("data", filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
}
// try current directory (or absolute path)
{
std::ifstream* stream = new std::ifstream(filename.c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
// try install directory
#if defined(INSTALL_DATA_DIR)
if (relative) {
std::ifstream* stream = new std::ifstream(catPath(INSTALL_DATA_DIR,
filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
#endif
return NULL;
}
std::ostream* FileManager::createDataOutStream(
const std::string& filename,
bool binary,
bool truncate) const
{
// choose open mode
std::ios::openmode mode = std::ios::out;
if (binary)
mode |= std::ios::binary;
if (truncate)
mode |= std::ios::trunc;
const bool relative = !isAbsolute(filename);
if (relative) {
// try directory stored in DB
if (BZDB->isSet("directory")) {
std::ofstream* stream = new std::ofstream(catPath(BZDB->get("directory"),
filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
return NULL;
}
// try data directory
{
std::ofstream* stream = new std::ofstream(catPath("data", filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
return NULL;
}
} else {
// try absolute path
std::ofstream* stream = new std::ofstream(filename.c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
return NULL;
}
}
bool FileManager::isAbsolute(const std::string& path) const
{
if (path.empty())
return false;
#if defined(_WIN32)
const char* cpath = path.c_str();
if (cpath[0] == '\\' || cpath[0] == '/')
return true;
if (path.size() >= 3 && isalpha(cpath[0]) && cpath[1] == ':' &&
(cpath[2] == '\\' || cpath[2] == '/'))
return true;
#elif defined(macintosh)
#error FIXME -- what indicates an absolute path on mac?
#else
if (path.c_str()[0] == '/')
return true;
#endif
return false;
}
std::string FileManager::catPath(
const std::string& a,
const std::string& b) const
{
// handle trivial cases
if (a.empty())
return b;
if (b.empty())
return a;
#if defined(_WIN32)
std::string c = a;
c += "\\";
c += b;
return c;
#elif defined(macintosh)
std::string c = a;
c += ':';
c += b;
#else
std::string c = a;
c += "/";
c += b;
return c;
#endif
}
// ex: shiftwidth=4 tabstop=4
<commit_msg>updated ex: whitespace setting to 2/8<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "FileManager.h"
#include "string"
#include "StateDatabase.h"
#include <ctype.h>
#include <fstream>
//
// FileManager
//
FileManager* FileManager::mgr = NULL;
FileManager::FileManager()
{
// do nothing
}
FileManager::~FileManager()
{
mgr = NULL;
}
FileManager* FileManager::getInstance()
{
if (mgr == NULL)
mgr = new FileManager;
return mgr;
}
std::istream* FileManager::createDataInStream(
const std::string& filename,
bool binary) const
{
// choose open mode
std::ios::openmode mode = std::ios::in;
if (binary)
mode |= std::ios::binary;
const bool relative = !isAbsolute(filename);
if (relative) {
// try directory stored in DB
if (BZDB->isSet("directory")) {
std::ifstream* stream = new std::ifstream(catPath(BZDB->get("directory"),
filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
// try data directory
{
std::ifstream* stream = new std::ifstream(catPath("data", filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
}
// try current directory (or absolute path)
{
std::ifstream* stream = new std::ifstream(filename.c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
// try install directory
#if defined(INSTALL_DATA_DIR)
if (relative) {
std::ifstream* stream = new std::ifstream(catPath(INSTALL_DATA_DIR,
filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
}
#endif
return NULL;
}
std::ostream* FileManager::createDataOutStream(
const std::string& filename,
bool binary,
bool truncate) const
{
// choose open mode
std::ios::openmode mode = std::ios::out;
if (binary)
mode |= std::ios::binary;
if (truncate)
mode |= std::ios::trunc;
const bool relative = !isAbsolute(filename);
if (relative) {
// try directory stored in DB
if (BZDB->isSet("directory")) {
std::ofstream* stream = new std::ofstream(catPath(BZDB->get("directory"),
filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
return NULL;
}
// try data directory
{
std::ofstream* stream = new std::ofstream(catPath("data", filename).c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
return NULL;
}
} else {
// try absolute path
std::ofstream* stream = new std::ofstream(filename.c_str(), mode);
if (stream && *stream)
return stream;
delete stream;
return NULL;
}
}
bool FileManager::isAbsolute(const std::string& path) const
{
if (path.empty())
return false;
#if defined(_WIN32)
const char* cpath = path.c_str();
if (cpath[0] == '\\' || cpath[0] == '/')
return true;
if (path.size() >= 3 && isalpha(cpath[0]) && cpath[1] == ':' &&
(cpath[2] == '\\' || cpath[2] == '/'))
return true;
#elif defined(macintosh)
#error FIXME -- what indicates an absolute path on mac?
#else
if (path.c_str()[0] == '/')
return true;
#endif
return false;
}
std::string FileManager::catPath(
const std::string& a,
const std::string& b) const
{
// handle trivial cases
if (a.empty())
return b;
if (b.empty())
return a;
#if defined(_WIN32)
std::string c = a;
c += "\\";
c += b;
return c;
#elif defined(macintosh)
std::string c = a;
c += ':';
c += b;
#else
std::string c = a;
c += "/";
c += b;
return c;
#endif
}
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/**
* Copyright 2015 Silvana Trindade
*
* 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 "Graph.hpp"
#include "BestBalancedPathEdge.hpp"
#include "BestBalancedPathNode.hpp"
#include "Suurballe.hpp"
#include <sstream>
vector<string> &split(const string &s, char delim, vector<string> &elems);
vector<string> split(const string &s, char delim);
/**
* Compilar : g++ *.cpp -o b -g -std=c++11 -pthread -Wall
* Executar : ./b <arquivo>
*/
int main(int argc, char const *argv[])
{
if (argc <= 1)
{
return 0;
}
ifstream file;
file.open(argv[1]);
vector<string> pathFile = split(argv[1],'/');
if (file.is_open())
{
Graph g1,g2;
g1.setUseEdgeWeight(false);
g2.setUseEdgeWeight(false);
string line = " ";
getline (file,line);
int n = stoi(line);//obtêm o número de nós
g1.setNumberOfNodes(n);
g1.setMinimumDegree(2);
g1.setMaximumDegree(n-1);
g2.setNumberOfNodes(n);
g2.setMinimumDegree(2);
g2.setMaximumDegree(n-1);
// cout<<"Número de nós: "<<n<<endl;
vector<string> nodes;
while( getline (file,line) )
{
nodes = split(line.c_str(),' ');
int u = stoi(nodes[0])-1;
int v = stoi(nodes[1])-1;
// g.setEdgeDirected(u,v);
g1.setEdge(u,v);
g1.setWeight(u,v,1.0);
g1.setWeight(v,u,1.0);
g2.setEdge(u,v);
g2.setWeight(u,v,1.0);
g2.setWeight(v,u,1.0);
}
// g.setWeightEdgeDirected(1-1,8-1,2.0f);
// g.setWeightEdgeDirected(1-1,7-1,8.0f);
// g.setWeightEdgeDirected(1-1,2-1,3.0f);
// g.setWeightEdgeDirected(2-1,3-1,1.0f);
// g.setWeightEdgeDirected(2-1,6-1,6.0f);
// g.setWeightEdgeDirected(2-1,7-1,4.0f);
// g.setWeightEdgeDirected(3-1,4-1,5.0f);
// g.setWeightEdgeDirected(5-1,4-1,7.0f);
// g.setWeightEdgeDirected(6-1,5-1,2.0f);
// g.setWeightEdgeDirected(5-1,8-1,3.0f);
// g.setWeightEdgeDirected(8-1,6-1,5.0f);
// g.setWeightEdgeDirected(7-1,4-1,1.0f);
// Suurballe bs;
// bool sobrevivente = bs.execute(g2,pathFile[pathFile.size()-1]);
// if (!sobrevivente)
// {
// cout<<"Topologia não sobrevivente "<<endl;
// return 0;
// }
// cout<<"sobrevivente "<<sobrevivente<<"\n\n"<<endl;
// Suurballe s;
// bool sobrevivente = s.execute(g2,pathFile[pathFile.size()-1]);
// cout<<"sobrevivente "<<sobrevivente<<endl;
BestBalancedPathEdge be;
be.execute(g1,"best_balanced_edge_"+pathFile[pathFile.size()-1]);
// BestBalancedPathNode bn;
// bn.execute(g1,"best_balanced_node_"+pathFile[pathFile.size()-1]);
file.close();
}
else
{
cout<<"ERROR"<<endl;
}
// TreeNode *t = new TreeNode(5);
// TreeNode *n3 = new TreeNode(3);
// TreeNode *n6_1 = new TreeNode(6);
// TreeNode *n6_2 = new TreeNode(6);
// TreeNode *n7_1 = new TreeNode(7);
// TreeNode *n7_2 = new TreeNode(7);
// TreeNode *n8_1 = new TreeNode(8);
// TreeNode *n8_2 = new TreeNode(8);
// TreeNode *n8_3 = new TreeNode(8);
// TreeNode *n8_4 = new TreeNode(8);
// n3->parent = t;
// n6_1->parent = t;
// n7_1->parent = n6_1;
// n8_1->parent = n6_1;
// n8_2->parent = n7_1;
// n6_2->parent = n3;
// n7_2->parent = n6_2;
// n8_3->parent = n6_2;
// n8_4->parent = n7_2;
// t->addChild(n6_1);
// t->addChild(n3);
// n3->addChild(n6_2);
// n6_2->addChild(n7_2);
// n6_2->addChild(n8_3);
// n7_2->addChild(n8_4);
// n6_1->addChild(n7_1);
// n6_1->addChild(n8_1);
// n7_1->addChild(n8_2);
// TreeNode *temp = n8_4;
// while (temp) {
// printf("%d\n", temp->index);
// temp = temp->parent;
// }
return 0;
}
vector<string> &split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
vector<string> split(const string &s, char delim) {
vector<string> elems;
split(s, delim, elems);
return elems;
}<commit_msg>Adicionando todos os casos na Main.<commit_after>/**
* Copyright 2015 Silvana Trindade
*
* 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 "Graph.hpp"
#include "BestBalancedPathEdge.hpp"
#include "BestBalancedPathNode.hpp"
#include "Suurballe.hpp"
#include <sstream>
vector<string> &split(const string &s, char delim, vector<string> &elems);
vector<string> split(const string &s, char delim);
/**
* Compilar : g++ *.cpp -o b -g -std=c++11 -pthread -Wall
* Executar : ./b <arquivo>
*/
int main(int argc, char const *argv[])
{
if (argc <= 1)
{
return 0;
}
ifstream file;
file.open(argv[1]);
vector<string> pathFile = split(argv[1],'/');
if (file.is_open())
{
Graph g1,g2;
g1.setUseEdgeWeight(false);
g2.setUseEdgeWeight(false);
string line = " ";
getline (file,line);
int n = stoi(line);//obtêm o número de nós
g1.setNumberOfNodes(n);
g1.setMinimumDegree(2);
g1.setMaximumDegree(n-1);
g2.setNumberOfNodes(n);
g2.setMinimumDegree(2);
g2.setMaximumDegree(n-1);
// cout<<"Número de nós: "<<n<<endl;
vector<string> nodes;
while( getline (file,line) )
{
nodes = split(line.c_str(),' ');
int u = stoi(nodes[0])-1;
int v = stoi(nodes[1])-1;
// g.setEdgeDirected(u,v);
g1.setEdge(u,v);
g1.setWeight(u,v,1.0);
g1.setWeight(v,u,1.0);
g2.setEdge(u,v);
g2.setWeight(u,v,1.0);
g2.setWeight(v,u,1.0);
}
// g.setWeightEdgeDirected(1-1,8-1,2.0f);
// g.setWeightEdgeDirected(1-1,7-1,8.0f);
// g.setWeightEdgeDirected(1-1,2-1,3.0f);
// g.setWeightEdgeDirected(2-1,3-1,1.0f);
// g.setWeightEdgeDirected(2-1,6-1,6.0f);
// g.setWeightEdgeDirected(2-1,7-1,4.0f);
// g.setWeightEdgeDirected(3-1,4-1,5.0f);
// g.setWeightEdgeDirected(5-1,4-1,7.0f);
// g.setWeightEdgeDirected(6-1,5-1,2.0f);
// g.setWeightEdgeDirected(5-1,8-1,3.0f);
// g.setWeightEdgeDirected(8-1,6-1,5.0f);
// g.setWeightEdgeDirected(7-1,4-1,1.0f);
// Suurballe bs;
// bool sobrevivente = bs.execute(g2,pathFile[pathFile.size()-1]);
// if (!sobrevivente)
// {
// cout<<"Topologia não sobrevivente "<<endl;
// return 0;
// }
// cout<<"sobrevivente "<<sobrevivente<<"\n\n"<<endl;
Suurballe s;
bool sobrevivente = s.execute(g2,pathFile[pathFile.size()-1]);
// cout<<"sobrevivente "<<sobrevivente<<endl;
BestBalancedPathEdge be;
be.execute(g1,"best_balanced_edge_"+pathFile[pathFile.size()-1]);
BestBalancedPathNode bn;
bn.execute(g1,"best_balanced_node_"+pathFile[pathFile.size()-1]);
WorstBalancedPathNode bn;
bn.execute(g1,"worst_balanced_node_"+pathFile[pathFile.size()-1]);
WorstBalancedPathEdge bn;
bn.execute(g1,"worst_balanced_edge_"+pathFile[pathFile.size()-1]);
file.close();
}
else
{
cout<<"ERROR"<<endl;
}
// TreeNode *t = new TreeNode(5);
// TreeNode *n3 = new TreeNode(3);
// TreeNode *n6_1 = new TreeNode(6);
// TreeNode *n6_2 = new TreeNode(6);
// TreeNode *n7_1 = new TreeNode(7);
// TreeNode *n7_2 = new TreeNode(7);
// TreeNode *n8_1 = new TreeNode(8);
// TreeNode *n8_2 = new TreeNode(8);
// TreeNode *n8_3 = new TreeNode(8);
// TreeNode *n8_4 = new TreeNode(8);
// n3->parent = t;
// n6_1->parent = t;
// n7_1->parent = n6_1;
// n8_1->parent = n6_1;
// n8_2->parent = n7_1;
// n6_2->parent = n3;
// n7_2->parent = n6_2;
// n8_3->parent = n6_2;
// n8_4->parent = n7_2;
// t->addChild(n6_1);
// t->addChild(n3);
// n3->addChild(n6_2);
// n6_2->addChild(n7_2);
// n6_2->addChild(n8_3);
// n7_2->addChild(n8_4);
// n6_1->addChild(n7_1);
// n6_1->addChild(n8_1);
// n7_1->addChild(n8_2);
// TreeNode *temp = n8_4;
// while (temp) {
// printf("%d\n", temp->index);
// temp = temp->parent;
// }
return 0;
}
vector<string> &split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
vector<string> split(const string &s, char delim) {
vector<string> elems;
split(s, delim, elems);
return elems;
}<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkAffineTransform.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkNearestNeighborExtrapolateImageFunction.h"
/* Further testing of itkResampleImageFilter
* Output is compared with baseline image using the cmake itk_add_test
* '--compare' option.
*/
namespace {
template<typename TCoordRepType, unsigned int NDimensions>
class NonlinearAffineTransform:
public itk::AffineTransform<TCoordRepType,NDimensions>
{
public:
/** Standard class typedefs. */
typedef NonlinearAffineTransform Self;
typedef itk::AffineTransform< TCoordRepType, NDimensions > Superclass;
typedef itk::SmartPointer< Self > Pointer;
typedef itk::SmartPointer< const Self > ConstPointer;
/** New macro for creation of through a smart pointer. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(NonlinearAffineTransform, AffineTransform);
/** Dimension of the domain space. */
itkStaticConstMacro(InputSpaceDimension, unsigned int, NDimensions);
itkStaticConstMacro(OutputSpaceDimension, unsigned int, NDimensions);
itkStaticConstMacro(SpaceDimension, unsigned int, NDimensions);
itkStaticConstMacro( ParametersDimension, unsigned int,
NDimensions *( NDimensions + 1 ) );
/** Override this. See test below. */
virtual bool IsLinear() const { return false; }
};
}
int itkResampleImageTest2(int argc, char * argv [] )
{
if( argc < 5 )
{
std::cerr << "Missing arguments ! " << std::endl;
std::cerr << "Usage : " << std::endl;
std::cerr << argv[0] << "inputImage referenceImage "
<< "resampledImageLinear resampledImageNonLinear "
<< "resampledImageLinearNearestExtrapolate"
<< "resampledImageNonLinearNearestExtrapolate";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const unsigned int NDimensions = 2;
typedef unsigned char PixelType;
typedef itk::Image<PixelType, NDimensions> ImageType;
typedef ImageType::IndexType ImageIndexType;
typedef ImageType::Pointer ImagePointerType;
typedef ImageType::RegionType ImageRegionType;
typedef ImageType::SizeType ImageSizeType;
typedef double CoordRepType;
typedef itk::AffineTransform<CoordRepType,NDimensions>
AffineTransformType;
typedef NonlinearAffineTransform<CoordRepType,NDimensions>
NonlinearAffineTransformType;
typedef itk::LinearInterpolateImageFunction<ImageType,CoordRepType>
InterpolatorType;
typedef itk::NearestNeighborExtrapolateImageFunction<ImageType,CoordRepType>
ExtrapolatorType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
ReaderType::Pointer reader1 = ReaderType::New();
ReaderType::Pointer reader2 = ReaderType::New();
ReaderType::Pointer reader3 = ReaderType::New();
ReaderType::Pointer reader4 = ReaderType::New();
WriterType::Pointer writer1 = WriterType::New();
WriterType::Pointer writer2 = WriterType::New();
WriterType::Pointer writer3 = WriterType::New();
WriterType::Pointer writer4 = WriterType::New();
reader1->SetFileName( argv[1] );
reader2->SetFileName( argv[2] );
reader3->SetFileName( argv[3] );
reader4->SetFileName( argv[4] );
writer1->SetFileName( argv[3] );
writer2->SetFileName( argv[4] );
writer3->SetFileName( argv[5] );
writer4->SetFileName( argv[6] );
// Create an affine transformation
AffineTransformType::Pointer affineTransform = AffineTransformType::New();
affineTransform->Scale(2.0);
// Create a linear interpolation image function
InterpolatorType::Pointer interpolator = InterpolatorType::New();
// Create a nearest neighbor extrapolate image function
ExtrapolatorType::Pointer extrapolator = ExtrapolatorType::New();
// Create and configure a resampling filter
typedef itk::ResampleImageFilter< ImageType, ImageType > ResampleFilterType;
ResampleFilterType::Pointer resample = ResampleFilterType::New();
resample->SetInput( reader1->GetOutput() );
resample->SetReferenceImage( reader2->GetOutput() );
resample->UseReferenceImageOn();
resample->SetTransform( affineTransform );
resample->SetInterpolator( interpolator );
writer1->SetInput( resample->GetOutput() );
// Check GetReferenceImage
if( resample->GetReferenceImage() != reader2->GetOutput() )
{
std::cerr << "GetReferenceImage() failed ! " << std::endl;
return EXIT_FAILURE;
}
// Run the resampling filter with the normal, linear, affine transform.
// This will use ResampleImageFilter::LinearThreadedGenerateData().
std::cout << "Test with normal AffineTransform." << std::endl;
try
{
writer1->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Assign an affine transform that returns
// false for IsLinear() instead of true, to force
// the filter to use the NonlinearThreadedGenerateData method
// instead of LinearThreadedGenerateData. This will test that
// we get the same results for both methods.
std::cout << "Test with NonlinearAffineTransform." << std::endl;
NonlinearAffineTransformType::Pointer nonlinearAffineTransform =
NonlinearAffineTransformType::New();
nonlinearAffineTransform->Scale(2.0);
resample->SetTransform( nonlinearAffineTransform );
writer2->SetInput( resample->GetOutput() );
try
{
writer2->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Instead of using the default pixel when sampling outside the input image,
// we use a nearest neighbor extrapolator.
resample->SetTransform( affineTransform );
resample->SetExtrapolator( extrapolator );
writer3->SetInput( resample->GetOutput() );
std::cout << "Test with nearest neighbor extrapolator, affine transform." << std::endl;
try
{
writer3->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Instead of using the default pixel when sampling outside the input image,
// we use a nearest neighbor extrapolator.
resample->SetTransform( nonlinearAffineTransform );
writer4->SetInput( resample->GetOutput() );
std::cout << "Test with nearest neighbor extrapolator, nonlinear transform." << std::endl;
try
{
writer4->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Check UseReferenceImage methods
resample->UseReferenceImageOff();
if( resample->GetUseReferenceImage() )
{
std::cerr << "GetUseReferenceImage() or UseReferenceImageOff() failed ! ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
// Check UseReferenceImage methods
resample->UseReferenceImageOn();
if( !resample->GetUseReferenceImage() )
{
std::cerr << "GetUseReferenceImage() or UseReferenceImageOn() failed ! ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
// Check UseReferenceImage methods
resample->SetUseReferenceImage( false );
if( resample->GetUseReferenceImage() )
{
std::cerr << "GetUseReferenceImage() or SetUseReferenceImage() failed ! ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>COMP: Use SimpleNew macro to avoid Clone method<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkAffineTransform.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkNearestNeighborExtrapolateImageFunction.h"
/* Further testing of itkResampleImageFilter
* Output is compared with baseline image using the cmake itk_add_test
* '--compare' option.
*/
namespace {
template<typename TCoordRepType, unsigned int NDimensions>
class NonlinearAffineTransform:
public itk::AffineTransform<TCoordRepType,NDimensions>
{
public:
/** Standard class typedefs. */
typedef NonlinearAffineTransform Self;
typedef itk::AffineTransform< TCoordRepType, NDimensions > Superclass;
typedef itk::SmartPointer< Self > Pointer;
typedef itk::SmartPointer< const Self > ConstPointer;
/** New macro for creation of through a smart pointer. */
itkSimpleNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(NonlinearAffineTransform, AffineTransform);
/** Dimension of the domain space. */
itkStaticConstMacro(InputSpaceDimension, unsigned int, NDimensions);
itkStaticConstMacro(OutputSpaceDimension, unsigned int, NDimensions);
itkStaticConstMacro(SpaceDimension, unsigned int, NDimensions);
itkStaticConstMacro( ParametersDimension, unsigned int,
NDimensions *( NDimensions + 1 ) );
/** Override this. See test below. */
virtual bool IsLinear() const { return false; }
};
}
int itkResampleImageTest2(int argc, char * argv [] )
{
if( argc < 5 )
{
std::cerr << "Missing arguments ! " << std::endl;
std::cerr << "Usage : " << std::endl;
std::cerr << argv[0] << "inputImage referenceImage "
<< "resampledImageLinear resampledImageNonLinear "
<< "resampledImageLinearNearestExtrapolate"
<< "resampledImageNonLinearNearestExtrapolate";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const unsigned int NDimensions = 2;
typedef unsigned char PixelType;
typedef itk::Image<PixelType, NDimensions> ImageType;
typedef ImageType::IndexType ImageIndexType;
typedef ImageType::Pointer ImagePointerType;
typedef ImageType::RegionType ImageRegionType;
typedef ImageType::SizeType ImageSizeType;
typedef double CoordRepType;
typedef itk::AffineTransform<CoordRepType,NDimensions>
AffineTransformType;
typedef NonlinearAffineTransform<CoordRepType,NDimensions>
NonlinearAffineTransformType;
typedef itk::LinearInterpolateImageFunction<ImageType,CoordRepType>
InterpolatorType;
typedef itk::NearestNeighborExtrapolateImageFunction<ImageType,CoordRepType>
ExtrapolatorType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::ImageFileWriter< ImageType > WriterType;
ReaderType::Pointer reader1 = ReaderType::New();
ReaderType::Pointer reader2 = ReaderType::New();
ReaderType::Pointer reader3 = ReaderType::New();
ReaderType::Pointer reader4 = ReaderType::New();
WriterType::Pointer writer1 = WriterType::New();
WriterType::Pointer writer2 = WriterType::New();
WriterType::Pointer writer3 = WriterType::New();
WriterType::Pointer writer4 = WriterType::New();
reader1->SetFileName( argv[1] );
reader2->SetFileName( argv[2] );
reader3->SetFileName( argv[3] );
reader4->SetFileName( argv[4] );
writer1->SetFileName( argv[3] );
writer2->SetFileName( argv[4] );
writer3->SetFileName( argv[5] );
writer4->SetFileName( argv[6] );
// Create an affine transformation
AffineTransformType::Pointer affineTransform = AffineTransformType::New();
affineTransform->Scale(2.0);
// Create a linear interpolation image function
InterpolatorType::Pointer interpolator = InterpolatorType::New();
// Create a nearest neighbor extrapolate image function
ExtrapolatorType::Pointer extrapolator = ExtrapolatorType::New();
// Create and configure a resampling filter
typedef itk::ResampleImageFilter< ImageType, ImageType > ResampleFilterType;
ResampleFilterType::Pointer resample = ResampleFilterType::New();
resample->SetInput( reader1->GetOutput() );
resample->SetReferenceImage( reader2->GetOutput() );
resample->UseReferenceImageOn();
resample->SetTransform( affineTransform );
resample->SetInterpolator( interpolator );
writer1->SetInput( resample->GetOutput() );
// Check GetReferenceImage
if( resample->GetReferenceImage() != reader2->GetOutput() )
{
std::cerr << "GetReferenceImage() failed ! " << std::endl;
return EXIT_FAILURE;
}
// Run the resampling filter with the normal, linear, affine transform.
// This will use ResampleImageFilter::LinearThreadedGenerateData().
std::cout << "Test with normal AffineTransform." << std::endl;
try
{
writer1->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Assign an affine transform that returns
// false for IsLinear() instead of true, to force
// the filter to use the NonlinearThreadedGenerateData method
// instead of LinearThreadedGenerateData. This will test that
// we get the same results for both methods.
std::cout << "Test with NonlinearAffineTransform." << std::endl;
NonlinearAffineTransformType::Pointer nonlinearAffineTransform =
NonlinearAffineTransformType::New();
nonlinearAffineTransform->Scale(2.0);
resample->SetTransform( nonlinearAffineTransform );
writer2->SetInput( resample->GetOutput() );
try
{
writer2->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Instead of using the default pixel when sampling outside the input image,
// we use a nearest neighbor extrapolator.
resample->SetTransform( affineTransform );
resample->SetExtrapolator( extrapolator );
writer3->SetInput( resample->GetOutput() );
std::cout << "Test with nearest neighbor extrapolator, affine transform." << std::endl;
try
{
writer3->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Instead of using the default pixel when sampling outside the input image,
// we use a nearest neighbor extrapolator.
resample->SetTransform( nonlinearAffineTransform );
writer4->SetInput( resample->GetOutput() );
std::cout << "Test with nearest neighbor extrapolator, nonlinear transform." << std::endl;
try
{
writer4->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
// Check UseReferenceImage methods
resample->UseReferenceImageOff();
if( resample->GetUseReferenceImage() )
{
std::cerr << "GetUseReferenceImage() or UseReferenceImageOff() failed ! ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
// Check UseReferenceImage methods
resample->UseReferenceImageOn();
if( !resample->GetUseReferenceImage() )
{
std::cerr << "GetUseReferenceImage() or UseReferenceImageOn() failed ! ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
// Check UseReferenceImage methods
resample->SetUseReferenceImage( false );
if( resample->GetUseReferenceImage() )
{
std::cerr << "GetUseReferenceImage() or SetUseReferenceImage() failed ! ";
std::cerr << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <iostream>
#include <ostream>
#include "arcball.h"
using namespace visionaray;
arcball::arcball()
: radius(1.0f)
, down_pos(0.0f)
, rotation(quat::identity())
, down_rotation(quat::identity())
{
}
arcball::arcball(float r)
: radius(r)
, down_pos(0.0f)
, rotation(quat::identity())
, down_rotation(quat::identity())
{
}
//-------------------------------------------------------------------------------------------------
// Project x/y screen space position to ball coordinates
//
vec3 arcball::project(int x, int y, recti const& viewport)
{
vec3 v(0.0f);
x -= viewport.x;
y -= viewport.y;
auto width = viewport.w;
auto height = viewport.h;
#if 0
// trackball
v[0] = (x - 0.5f * width ) / width;
v[1] = -(y - 0.5f * height) / height;
vec2 tmp(v[0], v[1]);
float d = normh2(tmp);
float r2 = radius * radius;
if (d < radius * (1.0f / sqrt(2.0)))
{
v[2] = sqrt(r2 - d * d);
}
else
{
v[2] = r2 / (2.0f * d);
}
#else
// arcball
v[0] = (x - 0.5f * width ) / (radius * 0.5f * width );
v[1] = -(y - 0.5f * height) / (radius * 0.5f * height);
vec2 tmp(v[0], v[1]);
float d = norm2(tmp);
if (d > 1.0f)
{
float length = sqrt(d);
v[0] /= length;
v[1] /= length;
}
else
{
v[2] = sqrt(1.0f - d);
}
#endif
return v;
}
<commit_msg>Unnecessary includes<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include "arcball.h"
using namespace visionaray;
arcball::arcball()
: radius(1.0f)
, down_pos(0.0f)
, rotation(quat::identity())
, down_rotation(quat::identity())
{
}
arcball::arcball(float r)
: radius(r)
, down_pos(0.0f)
, rotation(quat::identity())
, down_rotation(quat::identity())
{
}
//-------------------------------------------------------------------------------------------------
// Project x/y screen space position to ball coordinates
//
vec3 arcball::project(int x, int y, recti const& viewport)
{
vec3 v(0.0f);
x -= viewport.x;
y -= viewport.y;
auto width = viewport.w;
auto height = viewport.h;
#if 0
// trackball
v[0] = (x - 0.5f * width ) / width;
v[1] = -(y - 0.5f * height) / height;
vec2 tmp(v[0], v[1]);
float d = normh2(tmp);
float r2 = radius * radius;
if (d < radius * (1.0f / sqrt(2.0)))
{
v[2] = sqrt(r2 - d * d);
}
else
{
v[2] = r2 / (2.0f * d);
}
#else
// arcball
v[0] = (x - 0.5f * width ) / (radius * 0.5f * width );
v[1] = -(y - 0.5f * height) / (radius * 0.5f * height);
vec2 tmp(v[0], v[1]);
float d = norm2(tmp);
if (d > 1.0f)
{
float length = sqrt(d);
v[0] /= length;
v[1] /= length;
}
else
{
v[2] = sqrt(1.0f - d);
}
#endif
return v;
}
<|endoftext|> |
<commit_before>#include <primitives/log.h>
#include <boost/format.hpp>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
DECLARE_STATIC_LOGGER(logger, "logger");
BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime)
BOOST_LOG_ATTRIBUTE_KEYWORD(thread_id, "ThreadID", boost::log::attributes::current_thread_id::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", boost::log::trivial::severity_level)
typedef boost::log::sinks::text_file_backend tfb;
typedef boost::log::sinks::synchronous_sink<tfb> sfs;
boost::shared_ptr<tfb> backend;
boost::shared_ptr<tfb> backend_debug;
boost::shared_ptr<tfb> backend_trace;
boost::shared_ptr<
boost::log::sinks::synchronous_sink<
boost::log::sinks::text_ostream_backend
>> c_log;
void logFormatter(boost::log::record_view const& rec, boost::log::formatting_ostream& strm)
{
static boost::thread_specific_ptr<boost::posix_time::time_facet> tss(0);
if (!tss.get())
{
tss.reset(new boost::posix_time::time_facet);
tss->set_iso_extended_format();
}
strm.imbue(std::locale(strm.getloc(), tss.get()));
std::string s;
boost::log::formatting_ostream ss(s);
ss << "[" << rec[severity] << "]";
strm << "[" << rec[timestamp] << "] " <<
boost::format("[%08x] %-9s %s")
% rec[thread_id]
% s
% rec[boost::log::expressions::smessage];
}
void logFormatterSimple(boost::log::record_view const& rec, boost::log::formatting_ostream& strm)
{
strm << boost::format("%s")
% rec[boost::log::expressions::smessage];
}
void initLogger(LoggerSettings &s)
{
try
{
bool disable_log = s.log_level == "";
boost::algorithm::to_lower(s.log_level);
boost::log::trivial::severity_level level;
std::stringstream(s.log_level) >> level;
boost::log::trivial::severity_level trace;
std::stringstream("trace") >> trace;
if (!disable_log)
{
auto c_log = boost::log::add_console_log();
::c_log = c_log;
if (s.simple_logger)
c_log->set_formatter(&logFormatterSimple);
else
c_log->set_formatter(&logFormatter);
c_log->set_filter(boost::log::trivial::severity >= level);
}
if (s.log_file != "")
{
#ifdef _WIN32
auto out_mode = 0x02;
auto app_mode = 0x08;
#else
auto out_mode = std::ios_base::out;
auto app_mode = std::ios_base::app;
#endif
auto open_mode = out_mode;
if (s.append)
open_mode = app_mode;
// input
if (level > boost::log::trivial::severity_level::trace)
{
auto backend = boost::make_shared<tfb>
(
boost::log::keywords::file_name = s.log_file + ".log." + s.log_level,
boost::log::keywords::rotation_size = 10 * 1024 * 1024,
boost::log::keywords::open_mode = open_mode//,
//boost::log::keywords::auto_flush = true
);
::backend = backend;
auto sink = boost::make_shared<sfs>(backend);
if (s.simple_logger)
sink->set_formatter(&logFormatterSimple);
else
sink->set_formatter(&logFormatter);
sink->set_filter(boost::log::trivial::severity >= level);
boost::log::core::get()->add_sink(sink);
}
if (level == boost::log::trivial::severity_level::trace || s.print_trace)
{
auto add_logger = [&s](auto severity, const auto &name, auto &g_backend)
{
auto backend = boost::make_shared<tfb>
(
boost::log::keywords::file_name = s.log_file + ".log." + name,
boost::log::keywords::rotation_size = 10 * 1024 * 1024,
// always append to trace, do not recreate
boost::log::keywords::open_mode = app_mode//,
//boost::log::keywords::auto_flush = true
);
g_backend = backend;
auto sink_trace = boost::make_shared<sfs>(backend);
// trace to file always has complex format
sink_trace->set_formatter(&logFormatter);
sink_trace->set_filter(boost::log::trivial::severity >= severity);
boost::log::core::get()->add_sink(sink_trace);
};
add_logger(boost::log::trivial::severity_level::debug, "debug", ::backend_debug);
add_logger(boost::log::trivial::severity_level::trace, "trace", ::backend_trace);
}
}
boost::log::add_common_attributes();
}
catch (const std::exception &e)
{
LOG_ERROR(logger, "logger initialization failed with exception " << e.what() << ", will use default logger settings");
}
}
void loggerFlush()
{
if (c_log)
c_log->flush();
if (backend)
backend->flush();
if (backend_trace)
backend_trace->flush();
}
<commit_msg>Fix build issues with clang and vs15.3.<commit_after>#include <primitives/log.h>
#include <boost/format.hpp>
#include <boost/log/common.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
DECLARE_STATIC_LOGGER(logger, "logger");
BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime)
BOOST_LOG_ATTRIBUTE_KEYWORD(thread_id, "ThreadID", boost::log::attributes::current_thread_id::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", boost::log::trivial::severity_level)
typedef boost::log::sinks::text_file_backend tfb;
typedef boost::log::sinks::synchronous_sink<tfb> sfs;
boost::shared_ptr<tfb> backend;
boost::shared_ptr<tfb> backend_debug;
boost::shared_ptr<tfb> backend_trace;
boost::shared_ptr<
boost::log::sinks::synchronous_sink<
boost::log::sinks::text_ostream_backend
>> c_log;
void logFormatter(boost::log::record_view const& rec, boost::log::formatting_ostream& strm)
{
static boost::thread_specific_ptr<boost::posix_time::time_facet> tss(0);
if (!tss.get())
{
tss.reset(new boost::posix_time::time_facet);
tss->set_iso_extended_format();
}
strm.imbue(std::locale(strm.getloc(), tss.get()));
std::string s;
boost::log::formatting_ostream ss(s);
ss << "[" << rec[severity] << "]";
strm << "[" << rec[timestamp] << "] " <<
boost::format("[%08x] %-9s %s")
% rec[thread_id]
% s
% rec[boost::log::expressions::smessage];
}
void logFormatterSimple(boost::log::record_view const& rec, boost::log::formatting_ostream& strm)
{
strm << boost::format("%s")
% rec[boost::log::expressions::smessage];
}
void initLogger(LoggerSettings &s)
{
try
{
bool disable_log = s.log_level == "";
boost::algorithm::to_lower(s.log_level);
boost::log::trivial::severity_level level;
std::stringstream(s.log_level) >> level;
boost::log::trivial::severity_level trace;
std::stringstream("trace") >> trace;
if (!disable_log)
{
auto c_log = boost::log::add_console_log();
::c_log = c_log;
if (s.simple_logger)
c_log->set_formatter(&logFormatterSimple);
else
c_log->set_formatter(&logFormatter);
c_log->set_filter(boost::log::trivial::severity >= level);
}
if (s.log_file != "")
{
#ifdef _WIN32
auto out_mode = 0x02;
auto app_mode = 0x08;
#else
auto out_mode = std::ios_base::out;
auto app_mode = std::ios_base::app;
#endif
auto open_mode = out_mode;
if (s.append)
open_mode = app_mode;
// input
if (level > boost::log::trivial::severity_level::trace)
{
auto backend = boost::make_shared<tfb>
(
boost::log::keywords::file_name = s.log_file + ".log." + s.log_level,
boost::log::keywords::rotation_size = 10 * 1024 * 1024,
boost::log::keywords::open_mode = open_mode//,
//boost::log::keywords::auto_flush = true
);
::backend = backend;
auto sink = boost::make_shared<sfs>(backend);
if (s.simple_logger)
sink->set_formatter(&logFormatterSimple);
else
sink->set_formatter(&logFormatter);
sink->set_filter(boost::log::trivial::severity >= level);
boost::log::core::get()->add_sink(sink);
}
if (level == boost::log::trivial::severity_level::trace || s.print_trace)
{
auto add_logger = [&s, &app_mode](auto severity, const auto &name, auto &g_backend)
{
auto backend = boost::make_shared<tfb>
(
boost::log::keywords::file_name = s.log_file + ".log." + name,
boost::log::keywords::rotation_size = 10 * 1024 * 1024,
// always append to trace, do not recreate
boost::log::keywords::open_mode = app_mode//,
//boost::log::keywords::auto_flush = true
);
g_backend = backend;
auto sink_trace = boost::make_shared<sfs>(backend);
// trace to file always has complex format
sink_trace->set_formatter(&logFormatter);
sink_trace->set_filter(boost::log::trivial::severity >= severity);
boost::log::core::get()->add_sink(sink_trace);
};
add_logger(boost::log::trivial::severity_level::debug, "debug", ::backend_debug);
add_logger(boost::log::trivial::severity_level::trace, "trace", ::backend_trace);
}
}
boost::log::add_common_attributes();
}
catch (const std::exception &e)
{
LOG_ERROR(logger, "logger initialization failed with exception " << e.what() << ", will use default logger settings");
}
}
void loggerFlush()
{
if (c_log)
c_log->flush();
if (backend)
backend->flush();
if (backend_trace)
backend_trace->flush();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 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-CHROMIUM file.
#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "ui/base/models/image_model.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace electron {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget, view),
shell_(shell),
view_(view),
widget_(widget) {
SetOwnedByWidget(true);
set_owned_by_client();
if (shell->GetDelegate())
icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
}
~DevToolsWindowDelegate() override = default;
// disable copy
DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override { return view_; }
std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
ui::ImageModel GetWindowIcon() override { return icon_; }
views::Widget* GetWidget() override { return widget_; }
const views::Widget* GetWidget() const override { return widget_; }
views::View* GetContentsView() override { return view_; }
views::ClientView* CreateClientView(views::Widget* widget) override {
return this;
}
// views::ClientView:
views::CloseRequestResult OnWindowCloseRequested() override {
shell_->inspectable_web_contents()->CloseDevTools();
return views::CloseRequestResult::kCannotClose;
}
private:
InspectableWebContentsViewViews* shell_;
views::View* view_;
views::Widget* widget_;
ui::ImageModel icon_;
};
} // namespace
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents) {
return new InspectableWebContentsViewViews(inspectable_web_contents);
}
InspectableWebContentsViewViews::InspectableWebContentsViewViews(
InspectableWebContents* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents),
devtools_web_view_(new views::WebView(nullptr)),
title_(u"Developer Tools") {
if (!inspectable_web_contents_->IsGuest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
auto* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());
contents_web_view_ = contents_web_view;
} else {
contents_web_view_ = new views::Label(u"No content under offscreen mode");
}
devtools_web_view_->SetVisible(false);
AddChildView(devtools_web_view_);
AddChildView(contents_web_view_);
}
InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
}
views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
views::View* InspectableWebContentsViewViews::GetWebView() {
return contents_web_view_;
}
void InspectableWebContentsViewViews::ShowDevTools(bool activate) {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_window_->SetBounds(
inspectable_web_contents()->GetDevToolsBounds());
if (activate) {
devtools_window_->Show();
} else {
devtools_window_->ShowInactive();
}
// Update draggable regions to account for the new dock position.
if (GetDelegate())
GetDelegate()->DevToolsResized();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_view_->RequestFocus();
Layout();
}
}
void InspectableWebContentsViewViews::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
devtools_window_.reset();
devtools_window_web_view_ = nullptr;
devtools_window_delegate_ = nullptr;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(nullptr);
Layout();
}
}
bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
return devtools_visible_;
}
bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
if (devtools_window_web_view_)
return devtools_window_web_view_->HasFocus();
else if (devtools_web_view_)
return devtools_web_view_->HasFocus();
else
return false;
}
void InspectableWebContentsViewViews::SetIsDocked(bool docked, bool activate) {
CloseDevTools();
if (!docked) {
devtools_window_ = std::make_unique<views::Widget>();
devtools_window_web_view_ = new views::WebView(nullptr);
devtools_window_delegate_ = new DevToolsWindowDelegate(
this, devtools_window_web_view_, devtools_window_.get());
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.delegate = devtools_window_delegate_;
params.bounds = inspectable_web_contents()->GetDevToolsBounds();
#if BUILDFLAG(IS_LINUX)
params.wm_role_name = "devtools";
if (GetDelegate())
GetDelegate()->GetDevToolsWindowWMClass(¶ms.wm_class_name,
¶ms.wm_class_class);
#endif
devtools_window_->Init(std::move(params));
devtools_window_->UpdateWindowIcon();
devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
}
ShowDevTools(activate);
}
void InspectableWebContentsViewViews::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
Layout();
}
void InspectableWebContentsViewViews::SetTitle(const std::u16string& title) {
if (devtools_window_) {
title_ = title;
devtools_window_->UpdateWindowTitle();
}
}
void InspectableWebContentsViewViews::Layout() {
if (!devtools_web_view_->GetVisible()) {
contents_web_view_->SetBoundsRect(GetVisibleBounds());
return;
}
gfx::Size container_size(width(), height());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(
strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
contents_web_view_->SetBoundsRect(new_contents_bounds);
if (GetDelegate())
GetDelegate()->DevToolsResized();
}
} // namespace electron
<commit_msg>fix: persist BrowserView content bounds when calculating layout (#32747)<commit_after>// Copyright (c) 2014 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-CHROMIUM file.
#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
#include "ui/base/models/image_model.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace electron {
namespace {
class DevToolsWindowDelegate : public views::ClientView,
public views::WidgetDelegate {
public:
DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
views::View* view,
views::Widget* widget)
: views::ClientView(widget, view),
shell_(shell),
view_(view),
widget_(widget) {
SetOwnedByWidget(true);
set_owned_by_client();
if (shell->GetDelegate())
icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
}
~DevToolsWindowDelegate() override = default;
// disable copy
DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override { return view_; }
std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
ui::ImageModel GetWindowIcon() override { return icon_; }
views::Widget* GetWidget() override { return widget_; }
const views::Widget* GetWidget() const override { return widget_; }
views::View* GetContentsView() override { return view_; }
views::ClientView* CreateClientView(views::Widget* widget) override {
return this;
}
// views::ClientView:
views::CloseRequestResult OnWindowCloseRequested() override {
shell_->inspectable_web_contents()->CloseDevTools();
return views::CloseRequestResult::kCannotClose;
}
private:
InspectableWebContentsViewViews* shell_;
views::View* view_;
views::Widget* widget_;
ui::ImageModel icon_;
};
} // namespace
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContents* inspectable_web_contents) {
return new InspectableWebContentsViewViews(inspectable_web_contents);
}
InspectableWebContentsViewViews::InspectableWebContentsViewViews(
InspectableWebContents* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents),
devtools_web_view_(new views::WebView(nullptr)),
title_(u"Developer Tools") {
if (!inspectable_web_contents_->IsGuest() &&
inspectable_web_contents_->GetWebContents()->GetNativeView()) {
auto* contents_web_view = new views::WebView(nullptr);
contents_web_view->SetWebContents(
inspectable_web_contents_->GetWebContents());
contents_web_view_ = contents_web_view;
} else {
contents_web_view_ = new views::Label(u"No content under offscreen mode");
}
devtools_web_view_->SetVisible(false);
AddChildView(devtools_web_view_);
AddChildView(contents_web_view_);
}
InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
if (devtools_window_)
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
}
views::View* InspectableWebContentsViewViews::GetView() {
return this;
}
views::View* InspectableWebContentsViewViews::GetWebView() {
return contents_web_view_;
}
void InspectableWebContentsViewViews::ShowDevTools(bool activate) {
if (devtools_visible_)
return;
devtools_visible_ = true;
if (devtools_window_) {
devtools_window_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_window_->SetBounds(
inspectable_web_contents()->GetDevToolsBounds());
if (activate) {
devtools_window_->Show();
} else {
devtools_window_->ShowInactive();
}
// Update draggable regions to account for the new dock position.
if (GetDelegate())
GetDelegate()->DevToolsResized();
} else {
devtools_web_view_->SetVisible(true);
devtools_web_view_->SetWebContents(
inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_view_->RequestFocus();
Layout();
}
}
void InspectableWebContentsViewViews::CloseDevTools() {
if (!devtools_visible_)
return;
devtools_visible_ = false;
if (devtools_window_) {
inspectable_web_contents()->SaveDevToolsBounds(
devtools_window_->GetWindowBoundsInScreen());
devtools_window_.reset();
devtools_window_web_view_ = nullptr;
devtools_window_delegate_ = nullptr;
} else {
devtools_web_view_->SetVisible(false);
devtools_web_view_->SetWebContents(nullptr);
Layout();
}
}
bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
return devtools_visible_;
}
bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
if (devtools_window_web_view_)
return devtools_window_web_view_->HasFocus();
else if (devtools_web_view_)
return devtools_web_view_->HasFocus();
else
return false;
}
void InspectableWebContentsViewViews::SetIsDocked(bool docked, bool activate) {
CloseDevTools();
if (!docked) {
devtools_window_ = std::make_unique<views::Widget>();
devtools_window_web_view_ = new views::WebView(nullptr);
devtools_window_delegate_ = new DevToolsWindowDelegate(
this, devtools_window_web_view_, devtools_window_.get());
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.delegate = devtools_window_delegate_;
params.bounds = inspectable_web_contents()->GetDevToolsBounds();
#if BUILDFLAG(IS_LINUX)
params.wm_role_name = "devtools";
if (GetDelegate())
GetDelegate()->GetDevToolsWindowWMClass(¶ms.wm_class_name,
¶ms.wm_class_class);
#endif
devtools_window_->Init(std::move(params));
devtools_window_->UpdateWindowIcon();
devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
}
ShowDevTools(activate);
}
void InspectableWebContentsViewViews::SetContentsResizingStrategy(
const DevToolsContentsResizingStrategy& strategy) {
strategy_.CopyFrom(strategy);
Layout();
}
void InspectableWebContentsViewViews::SetTitle(const std::u16string& title) {
if (devtools_window_) {
title_ = title;
devtools_window_->UpdateWindowTitle();
}
}
void InspectableWebContentsViewViews::Layout() {
if (!devtools_web_view_->GetVisible()) {
contents_web_view_->SetBoundsRect(GetContentsBounds());
return;
}
gfx::Size container_size(width(), height());
gfx::Rect new_devtools_bounds;
gfx::Rect new_contents_bounds;
ApplyDevToolsContentsResizingStrategy(
strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
// DevTools cares about the specific position, so we have to compensate RTL
// layout here.
new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
devtools_web_view_->SetBoundsRect(new_devtools_bounds);
contents_web_view_->SetBoundsRect(new_contents_bounds);
if (GetDelegate())
GetDelegate()->DevToolsResized();
}
} // namespace electron
<|endoftext|> |
<commit_before>#include "common/cli_wrapper.h"
#include "common/cli_helper.h"
#include "common/logging.h"
#include "common/options.h"
#include "common/timer.h"
#include "common/version.h"
namespace marian {
namespace cli {
/*
static uint16_t guess_terminal_width(uint16_t max_width, uint16_t default_width) {
uint16_t cols = 0;
#ifdef TIOCGSIZE
struct ttysize ts;
ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
if(ts.ts_cols != 0)
cols = ts.ts_cols;
#elif defined(TIOCGWINSZ)
struct winsize ts;
ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
if(ts.ws_col != 0)
cols = ts.ws_col;
#endif
// couldn't determine terminal width
if(cols == 0)
cols = default_width;
return max_width ? std::min(cols, max_width) : cols;
}
*/
CLIFormatter::CLIFormatter(size_t columnWidth, size_t screenWidth)
: CLI::Formatter(), screenWidth_(screenWidth) {
column_width(columnWidth);
}
std::string CLIFormatter::make_option_desc(const CLI::Option *opt) const {
auto desc = opt->get_description();
// TODO: restore guessing terminal width
// wrap lines in the option description
if(screenWidth_ > 0 && screenWidth_ < desc.size() + get_column_width()) {
size_t maxWidth = screenWidth_ - get_column_width();
std::istringstream descIn(desc);
std::ostringstream descOut;
size_t len = 0;
std::string word;
while(descIn >> word) {
if(len > 0)
descOut << " ";
if(len + word.length() > maxWidth) {
descOut << '\n' << std::string(get_column_width(), ' ');
len = 0;
}
descOut << word;
len += word.length() + 1;
}
desc = descOut.str();
}
return desc;
}
CLIWrapper::CLIWrapper(YAML::Node &config,
const std::string &description,
const std::string &header,
const std::string &footer,
size_t columnWidth,
size_t screenWidth)
: app_(std::make_shared<CLI::App>(description)),
defaultGroup_(header),
currentGroup_(header),
config_(config) {
// set footer
if(!footer.empty())
app_->footer("\n" + footer);
// set group name for the automatically added --help option
app_->get_help_ptr()->group(defaultGroup_);
// set custom failure message
app_->failure_message(failureMessage);
// set custom formatter for help message
auto fmt = std::make_shared<CLIFormatter>(columnWidth, screenWidth);
app_->formatter(fmt);
// add --version option
optVersion_ = app_->add_flag("--version", "Print the version number and exit");
optVersion_->group(defaultGroup_);
}
CLIWrapper::CLIWrapper(Ptr<marian::Options> options,
const std::string &description,
const std::string &header,
const std::string &footer,
size_t columnWidth,
size_t screenWidth)
: CLIWrapper(options->getYaml(), description, header, footer, columnWidth, screenWidth) {}
CLIWrapper::~CLIWrapper() {}
void CLIWrapper::switchGroup(const std::string &name) {
currentGroup_ = name.empty() ? defaultGroup_ : name;
}
void CLIWrapper::parse(int argc, char **argv) {
try {
app_->parse(argc, argv);
} catch(const CLI::ParseError &e) {
exit(app_->exit(e));
}
// handle --version flag
if(optVersion_->count()) {
std::cerr << buildVersion() << std::endl;
exit(0);
}
}
std::string CLIWrapper::failureMessage(const CLI::App *app, const CLI::Error &e) {
std::string header = "Error: " + std::string(e.what()) + "\n";
if(app->get_help_ptr() != nullptr)
header += "Run with " + app->get_help_ptr()->get_name() + " for more information.\n";
return header;
}
bool CLIWrapper::updateConfig(const YAML::Node &config) {
bool success = true;
auto cmdOptions = getParsedOptionNames();
for(auto it : config) {
auto key = it.first.as<std::string>();
// skip options specified via command-line to allow overwriting them
if(cmdOptions.count(key))
continue;
if(options_.count(key)) {
config_[key] = YAML::Clone(it.second);
options_[key].modified = true;
} else {
success = false;
}
}
return success;
}
std::string CLIWrapper::dumpConfig(bool skipDefault /*= false*/) const {
YAML::Emitter out;
out << YAML::Comment("Marian configuration file generated at " + timer::currentDate()
+ " with version " + buildVersion());
out << YAML::BeginMap;
std::string comment;
for(const auto &key : getOrderedOptionNames()) {
// do not proceed keys that are removed from config_
if(!config_[key])
continue;
if(skipDefault && !options_.at(key).modified)
continue;
auto group = options_.at(key).opt->get_group();
if(comment != group) {
if(!comment.empty())
out << YAML::Newline;
comment = group;
out << YAML::Comment(group);
}
out << YAML::Key;
out << key;
out << YAML::Value;
cli::OutputYaml(config_[key], out);
}
out << YAML::EndMap;
return out.c_str();
}
std::unordered_set<std::string> CLIWrapper::getParsedOptionNames() const {
std::unordered_set<std::string> keys;
for(const auto &it : options_)
if(!it.second.opt->empty())
keys.emplace(it.first);
return keys;
}
std::vector<std::string> CLIWrapper::getOrderedOptionNames() const {
std::vector<std::string> keys;
// extract all option names
for(auto const &it : options_)
keys.push_back(it.first);
// sort option names by creation index
sort(keys.begin(), keys.end(), [this](const std::string &a, const std::string &b) {
return options_.at(a).idx < options_.at(b).idx;
});
return keys;
}
} // namespace cli
} // namespace marian
<commit_msg>upcast single element to single element sequence in config if vector is expected<commit_after>#include "common/cli_wrapper.h"
#include "common/cli_helper.h"
#include "common/logging.h"
#include "common/options.h"
#include "common/timer.h"
#include "common/version.h"
namespace marian {
namespace cli {
/*
static uint16_t guess_terminal_width(uint16_t max_width, uint16_t default_width) {
uint16_t cols = 0;
#ifdef TIOCGSIZE
struct ttysize ts;
ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
if(ts.ts_cols != 0)
cols = ts.ts_cols;
#elif defined(TIOCGWINSZ)
struct winsize ts;
ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
if(ts.ws_col != 0)
cols = ts.ws_col;
#endif
// couldn't determine terminal width
if(cols == 0)
cols = default_width;
return max_width ? std::min(cols, max_width) : cols;
}
*/
CLIFormatter::CLIFormatter(size_t columnWidth, size_t screenWidth)
: CLI::Formatter(), screenWidth_(screenWidth) {
column_width(columnWidth);
}
std::string CLIFormatter::make_option_desc(const CLI::Option *opt) const {
auto desc = opt->get_description();
// TODO: restore guessing terminal width
// wrap lines in the option description
if(screenWidth_ > 0 && screenWidth_ < desc.size() + get_column_width()) {
size_t maxWidth = screenWidth_ - get_column_width();
std::istringstream descIn(desc);
std::ostringstream descOut;
size_t len = 0;
std::string word;
while(descIn >> word) {
if(len > 0)
descOut << " ";
if(len + word.length() > maxWidth) {
descOut << '\n' << std::string(get_column_width(), ' ');
len = 0;
}
descOut << word;
len += word.length() + 1;
}
desc = descOut.str();
}
return desc;
}
CLIWrapper::CLIWrapper(YAML::Node &config,
const std::string &description,
const std::string &header,
const std::string &footer,
size_t columnWidth,
size_t screenWidth)
: app_(std::make_shared<CLI::App>(description)),
defaultGroup_(header),
currentGroup_(header),
config_(config) {
// set footer
if(!footer.empty())
app_->footer("\n" + footer);
// set group name for the automatically added --help option
app_->get_help_ptr()->group(defaultGroup_);
// set custom failure message
app_->failure_message(failureMessage);
// set custom formatter for help message
auto fmt = std::make_shared<CLIFormatter>(columnWidth, screenWidth);
app_->formatter(fmt);
// add --version option
optVersion_ = app_->add_flag("--version", "Print the version number and exit");
optVersion_->group(defaultGroup_);
}
CLIWrapper::CLIWrapper(Ptr<marian::Options> options,
const std::string &description,
const std::string &header,
const std::string &footer,
size_t columnWidth,
size_t screenWidth)
: CLIWrapper(options->getYaml(), description, header, footer, columnWidth, screenWidth) {}
CLIWrapper::~CLIWrapper() {}
void CLIWrapper::switchGroup(const std::string &name) {
currentGroup_ = name.empty() ? defaultGroup_ : name;
}
void CLIWrapper::parse(int argc, char **argv) {
try {
app_->parse(argc, argv);
} catch(const CLI::ParseError &e) {
exit(app_->exit(e));
}
// handle --version flag
if(optVersion_->count()) {
std::cerr << buildVersion() << std::endl;
exit(0);
}
}
std::string CLIWrapper::failureMessage(const CLI::App *app, const CLI::Error &e) {
std::string header = "Error: " + std::string(e.what()) + "\n";
if(app->get_help_ptr() != nullptr)
header += "Run with " + app->get_help_ptr()->get_name() + " for more information.\n";
return header;
}
bool CLIWrapper::updateConfig(const YAML::Node &config) {
bool success = true;
auto cmdOptions = getParsedOptionNames();
for(auto it : config) {
auto key = it.first.as<std::string>();
// skip options specified via command-line to allow overwriting them
if(cmdOptions.count(key))
continue;
if(options_.count(key)) {
// this is a default value, so it has a node type
if(config_[key]) { // types don't match, handle this
if(config_[key].Type() != it.second.Type()) {
// default value is a sequence and incoming node is a scalar, hence we can upcast to single element sequence
if(config_[key].Type() == YAML::NodeType::Sequence && it.second.Type() == YAML::NodeType::Scalar) {
YAML::Node sequence;
sequence.push_back(YAML::Clone(it.second));
// overwrite so default values are replaced too
config_[key] = sequence;
options_[key].modified = true;
} else { // Cannot convert other non-matching types, e.g. scalar <- list should fail
success = false;
}
} else { // types match, go ahead
config_[key] = YAML::Clone(it.second);
options_[key].modified = true;
}
} else {
config_[key] = YAML::Clone(it.second);
options_[key].modified = true;
}
} else {
success = false;
}
}
return success;
}
std::string CLIWrapper::dumpConfig(bool skipDefault /*= false*/) const {
YAML::Emitter out;
out << YAML::Comment("Marian configuration file generated at " + timer::currentDate()
+ " with version " + buildVersion());
out << YAML::BeginMap;
std::string comment;
for(const auto &key : getOrderedOptionNames()) {
// do not proceed keys that are removed from config_
if(!config_[key])
continue;
if(skipDefault && !options_.at(key).modified)
continue;
auto group = options_.at(key).opt->get_group();
if(comment != group) {
if(!comment.empty())
out << YAML::Newline;
comment = group;
out << YAML::Comment(group);
}
out << YAML::Key;
out << key;
out << YAML::Value;
cli::OutputYaml(config_[key], out);
}
out << YAML::EndMap;
return out.c_str();
}
std::unordered_set<std::string> CLIWrapper::getParsedOptionNames() const {
std::unordered_set<std::string> keys;
for(const auto &it : options_)
if(!it.second.opt->empty())
keys.emplace(it.first);
return keys;
}
std::vector<std::string> CLIWrapper::getOrderedOptionNames() const {
std::vector<std::string> keys;
// extract all option names
for(auto const &it : options_)
keys.push_back(it.first);
// sort option names by creation index
sort(keys.begin(), keys.end(), [this](const std::string &a, const std::string &b) {
return options_.at(a).idx < options_.at(b).idx;
});
return keys;
}
} // namespace cli
} // namespace marian
<|endoftext|> |
<commit_before>#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
void ncopy(const vector<int> &nums, int k, int m, long long &x, int &y)
{
for (int i = 0; i < k; ++i) {
for (auto num : nums) {
if (y == m)
y = 0, ++x;
++y;
if (y + num > m)
y = 0, ++x;
y += num;
}
}
}
int main(void)
{
int n, m;
cin >> n >> m;
vector<int> nums;
string s;
while(cin >> s)
nums.push_back(s.size());
unordered_map<int, pair<int, long long>> dict;
long long x = 1;
int y = -1;
ncopy(nums, 1, m, x, y);
dict.emplace(y, make_pair(1, x));
for (int i = 2; i <= n; ++i) {
ncopy(nums, 1, m, x, y);
if (dict.find(y) != dict.end()) {
long long remain = (n - i) % (i - dict[y].first);
x += (n - i) / (i - dict[y].first) * (x - dict[y].second);
ncopy(nums, remain, m, x, y);
break;
}
dict.emplace(y, make_pair(1, x));
}
cout << x << ' ' << y << endl;
return 0;
}
<commit_msg>fix a bug in 1355<commit_after>#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
void ncopy(const vector<int> &nums, int k, int m, long long &x, int &y)
{
for (int i = 0; i < k; ++i) {
for (auto num : nums) {
if (y == m)
y = 0, ++x;
++y;
if (y + num > m)
y = 0, ++x;
y += num;
}
}
}
int main(void)
{
int n, m;
cin >> n >> m;
vector<int> nums;
string s;
while(cin >> s)
nums.push_back(s.size());
unordered_map<int, pair<int, long long>> dict;
long long x = 1;
int y = -1;
for (int i = 1; i <= n; ++i) {
ncopy(nums, 1, m, x, y);
if (dict.find(y) != dict.end()) {
long long remain = (n - i) % (i - dict[y].first);
x += (n - i) / (i - dict[y].first) * (x - dict[y].second);
ncopy(nums, remain, m, x, y);
break;
}
dict.emplace(y, make_pair(i, x));
}
cout << x << ' ' << y << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// clang-format off
// This must be here to prevent a WinSock.h exists error
#include "osquery/remote/transports/tls.h"
// clang-format on
#include <boost/filesystem.hpp>
#include <osquery/core.h>
#include <osquery/filesystem.h>
namespace fs = boost::filesystem;
namespace http = boost::network::http;
namespace osquery {
const std::string kTLSCiphers =
"ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:"
"DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5";
const std::string kTLSUserAgentBase = "osquery/";
/// TLS server hostname.
CLI_FLAG(string,
tls_hostname,
"",
"TLS/HTTPS hostname for Config, Logger, and Enroll plugins");
/// Path to optional TLS server/CA certificate(s), used for pinning.
CLI_FLAG(string,
tls_server_certs,
"",
"Optional path to a TLS server PEM certificate(s) bundle");
/// Path to optional TLS client certificate, used for enrollment/requests.
CLI_FLAG(string,
tls_client_cert,
"",
"Optional path to a TLS client-auth PEM certificate");
/// Path to optional TLS client secret key, used for enrollment/requests.
CLI_FLAG(string,
tls_client_key,
"",
"Optional path to a TLS client-auth PEM private key");
#if defined(DEBUG)
HIDDEN_FLAG(bool,
tls_allow_unsafe,
false,
"Allow TLS server certificate trust failures");
#endif
HIDDEN_FLAG(bool, tls_dump, false, "Print remote requests and responses");
/// Undocumented feature to override TLS endpoints.
HIDDEN_FLAG(bool, tls_node_api, false, "Use node key as TLS endpoints");
DECLARE_bool(verbose);
TLSTransport::TLSTransport() : verify_peer_(true) {
if (FLAGS_tls_server_certs.size() > 0) {
server_certificate_file_ = FLAGS_tls_server_certs;
}
if (FLAGS_tls_client_cert.size() > 0 && FLAGS_tls_client_key.size() > 0) {
client_certificate_file_ = FLAGS_tls_client_cert;
client_private_key_file_ = FLAGS_tls_client_key;
}
}
void TLSTransport::decorateRequest(http::client::request& r) {
r << boost::network::header("Connection", "close");
r << boost::network::header("Content-Type", serializer_->getContentType());
r << boost::network::header("Accept", serializer_->getContentType());
r << boost::network::header("Host", FLAGS_tls_hostname);
r << boost::network::header("User-Agent", kTLSUserAgentBase + kVersion);
}
http::client TLSTransport::getClient() {
http::client::options options;
options.follow_redirects(true).always_verify_peer(verify_peer_).timeout(16);
std::string ciphers = kTLSCiphers;
if (!isPlatform(PlatformType::TYPE_OSX)) {
// Otherwise we prefer GCM and SHA256+
ciphers += ":!CBC:!SHA";
}
#if defined(DEBUG)
// Configuration may allow unsafe TLS testing if compiled as a debug target.
if (FLAGS_tls_allow_unsafe) {
options.always_verify_peer(false);
}
#endif
options.openssl_ciphers(ciphers);
options.openssl_options(SSL_OP_NO_SSLv3 | SSL_OP_NO_SSLv2 | SSL_OP_ALL);
if (server_certificate_file_.size() > 0) {
if (!osquery::isReadable(server_certificate_file_).ok()) {
LOG(WARNING) << "Cannot read TLS server certificate(s): "
<< server_certificate_file_;
} else {
// There is a non-default server certificate set.
boost::system::error_code ec;
auto status = fs::status(server_certificate_file_, ec);
options.openssl_verify_path(server_certificate_file_);
// On Windows, we cannot set openssl_certificate to a directory
if (status.type() == fs::regular_file) {
options.openssl_certificate(server_certificate_file_);
} else {
LOG(WARNING) << "Cannot set a non-regular file as a certificate: "
<< server_certificate_file_;
}
}
}
if (client_certificate_file_.size() > 0) {
if (!osquery::isReadable(client_certificate_file_).ok()) {
LOG(WARNING) << "Cannot read TLS client certificate: "
<< client_certificate_file_;
} else if (!osquery::isReadable(client_private_key_file_).ok()) {
LOG(WARNING) << "Cannot read TLS client private key: "
<< client_private_key_file_;
} else {
options.openssl_certificate_file(client_certificate_file_);
options.openssl_private_key_file(client_private_key_file_);
}
}
// 'Optionally', though all TLS plugins should set a hostname, supply an SNI
// hostname. This will reveal the requested domain.
if (options_.count("hostname")) {
// Boost cpp-netlib will only support SNI in versions >= 0.12
options.openssl_sni_hostname(options_.get<std::string>("hostname"));
}
http::client client(options);
return client;
}
inline bool tlsFailure(const std::string& what) {
if (what.find("Error") == 0 || what.find("refused") != std::string::npos) {
return false;
}
return true;
}
Status TLSTransport::sendRequest() {
if (destination_.find("https://") == std::string::npos) {
return Status(1, "Cannot create TLS request for non-HTTPS protocol URI");
}
auto client = getClient();
http::client::request r(destination_);
decorateRequest(r);
VLOG(1) << "TLS/HTTPS GET request to URI: " << destination_;
try {
response_ = client.get(r);
const auto& response_body = body(response_);
if (FLAGS_verbose && FLAGS_tls_dump) {
fprintf(stdout, "%s\n", std::string(response_body).c_str());
}
response_status_ =
serializer_->deserialize(response_body, response_params_);
} catch (const std::exception& e) {
return Status((tlsFailure(e.what())) ? 2 : 1,
std::string("Request error: ") + e.what());
}
return response_status_;
}
Status TLSTransport::sendRequest(const std::string& params, bool compress) {
if (destination_.find("https://") == std::string::npos) {
return Status(1, "Cannot create TLS request for non-HTTPS protocol URI");
}
auto client = getClient();
http::client::request r(destination_);
decorateRequest(r);
if (compress) {
// Later, when posting/putting, the data will be optionally compressed.
r << boost::network::header("Content-Encoding", "gzip");
}
// Allow request calls to override the default HTTP POST verb.
HTTPVerb verb = HTTP_POST;
if (options_.count("verb") > 0) {
verb = (HTTPVerb)options_.get<int>("verb", HTTP_POST);
}
VLOG(1) << "TLS/HTTPS " << ((verb == HTTP_POST) ? "POST" : "PUT")
<< " request to URI: " << destination_;
if (FLAGS_verbose && FLAGS_tls_dump) {
fprintf(stdout, "%s\n", params.c_str());
}
try {
if (verb == HTTP_POST) {
response_ = client.post(r, (compress) ? compressString(params) : params);
} else {
response_ = client.put(r, (compress) ? compressString(params) : params);
}
const auto& response_body = body(response_);
if (FLAGS_verbose && FLAGS_tls_dump) {
fprintf(stdout, "%s\n", std::string(response_body).c_str());
}
response_status_ =
serializer_->deserialize(response_body, response_params_);
} catch (const std::exception& e) {
return Status((tlsFailure(e.what())) ? 2 : 1,
std::string("Request error: ") + e.what());
}
return response_status_;
}
}
<commit_msg>Restrict regular file checking of TLS pinned cert to Windows (#2520)<commit_after>/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// clang-format off
// This must be here to prevent a WinSock.h exists error
#include "osquery/remote/transports/tls.h"
// clang-format on
#include <boost/filesystem.hpp>
#include <osquery/core.h>
#include <osquery/filesystem.h>
namespace fs = boost::filesystem;
namespace http = boost::network::http;
namespace osquery {
const std::string kTLSCiphers =
"ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:"
"DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5";
const std::string kTLSUserAgentBase = "osquery/";
/// TLS server hostname.
CLI_FLAG(string,
tls_hostname,
"",
"TLS/HTTPS hostname for Config, Logger, and Enroll plugins");
/// Path to optional TLS server/CA certificate(s), used for pinning.
CLI_FLAG(string,
tls_server_certs,
"",
"Optional path to a TLS server PEM certificate(s) bundle");
/// Path to optional TLS client certificate, used for enrollment/requests.
CLI_FLAG(string,
tls_client_cert,
"",
"Optional path to a TLS client-auth PEM certificate");
/// Path to optional TLS client secret key, used for enrollment/requests.
CLI_FLAG(string,
tls_client_key,
"",
"Optional path to a TLS client-auth PEM private key");
#if defined(DEBUG)
HIDDEN_FLAG(bool,
tls_allow_unsafe,
false,
"Allow TLS server certificate trust failures");
#endif
HIDDEN_FLAG(bool, tls_dump, false, "Print remote requests and responses");
/// Undocumented feature to override TLS endpoints.
HIDDEN_FLAG(bool, tls_node_api, false, "Use node key as TLS endpoints");
DECLARE_bool(verbose);
TLSTransport::TLSTransport() : verify_peer_(true) {
if (FLAGS_tls_server_certs.size() > 0) {
server_certificate_file_ = FLAGS_tls_server_certs;
}
if (FLAGS_tls_client_cert.size() > 0 && FLAGS_tls_client_key.size() > 0) {
client_certificate_file_ = FLAGS_tls_client_cert;
client_private_key_file_ = FLAGS_tls_client_key;
}
}
void TLSTransport::decorateRequest(http::client::request& r) {
r << boost::network::header("Connection", "close");
r << boost::network::header("Content-Type", serializer_->getContentType());
r << boost::network::header("Accept", serializer_->getContentType());
r << boost::network::header("Host", FLAGS_tls_hostname);
r << boost::network::header("User-Agent", kTLSUserAgentBase + kVersion);
}
http::client TLSTransport::getClient() {
http::client::options options;
options.follow_redirects(true).always_verify_peer(verify_peer_).timeout(16);
std::string ciphers = kTLSCiphers;
if (!isPlatform(PlatformType::TYPE_OSX)) {
// Otherwise we prefer GCM and SHA256+
ciphers += ":!CBC:!SHA";
}
#if defined(DEBUG)
// Configuration may allow unsafe TLS testing if compiled as a debug target.
if (FLAGS_tls_allow_unsafe) {
options.always_verify_peer(false);
}
#endif
options.openssl_ciphers(ciphers);
options.openssl_options(SSL_OP_NO_SSLv3 | SSL_OP_NO_SSLv2 | SSL_OP_ALL);
if (server_certificate_file_.size() > 0) {
if (!osquery::isReadable(server_certificate_file_).ok()) {
LOG(WARNING) << "Cannot read TLS server certificate(s): "
<< server_certificate_file_;
} else {
// There is a non-default server certificate set.
boost::system::error_code ec;
auto status = fs::status(server_certificate_file_, ec);
options.openssl_verify_path(server_certificate_file_);
// On Windows, we cannot set openssl_certificate to a directory
if (isPlatform(PlatformType::TYPE_WINDOWS) &&
status.type() != fs::regular_file) {
LOG(WARNING) << "Cannot set a non-regular file as a certificate: "
<< server_certificate_file_;
} else {
options.openssl_certificate(server_certificate_file_);
}
}
}
if (client_certificate_file_.size() > 0) {
if (!osquery::isReadable(client_certificate_file_).ok()) {
LOG(WARNING) << "Cannot read TLS client certificate: "
<< client_certificate_file_;
} else if (!osquery::isReadable(client_private_key_file_).ok()) {
LOG(WARNING) << "Cannot read TLS client private key: "
<< client_private_key_file_;
} else {
options.openssl_certificate_file(client_certificate_file_);
options.openssl_private_key_file(client_private_key_file_);
}
}
// 'Optionally', though all TLS plugins should set a hostname, supply an SNI
// hostname. This will reveal the requested domain.
if (options_.count("hostname")) {
// Boost cpp-netlib will only support SNI in versions >= 0.12
options.openssl_sni_hostname(options_.get<std::string>("hostname"));
}
http::client client(options);
return client;
}
inline bool tlsFailure(const std::string& what) {
if (what.find("Error") == 0 || what.find("refused") != std::string::npos) {
return false;
}
return true;
}
Status TLSTransport::sendRequest() {
if (destination_.find("https://") == std::string::npos) {
return Status(1, "Cannot create TLS request for non-HTTPS protocol URI");
}
auto client = getClient();
http::client::request r(destination_);
decorateRequest(r);
VLOG(1) << "TLS/HTTPS GET request to URI: " << destination_;
try {
response_ = client.get(r);
const auto& response_body = body(response_);
if (FLAGS_verbose && FLAGS_tls_dump) {
fprintf(stdout, "%s\n", std::string(response_body).c_str());
}
response_status_ =
serializer_->deserialize(response_body, response_params_);
} catch (const std::exception& e) {
return Status((tlsFailure(e.what())) ? 2 : 1,
std::string("Request error: ") + e.what());
}
return response_status_;
}
Status TLSTransport::sendRequest(const std::string& params, bool compress) {
if (destination_.find("https://") == std::string::npos) {
return Status(1, "Cannot create TLS request for non-HTTPS protocol URI");
}
auto client = getClient();
http::client::request r(destination_);
decorateRequest(r);
if (compress) {
// Later, when posting/putting, the data will be optionally compressed.
r << boost::network::header("Content-Encoding", "gzip");
}
// Allow request calls to override the default HTTP POST verb.
HTTPVerb verb = HTTP_POST;
if (options_.count("verb") > 0) {
verb = (HTTPVerb)options_.get<int>("verb", HTTP_POST);
}
VLOG(1) << "TLS/HTTPS " << ((verb == HTTP_POST) ? "POST" : "PUT")
<< " request to URI: " << destination_;
if (FLAGS_verbose && FLAGS_tls_dump) {
fprintf(stdout, "%s\n", params.c_str());
}
try {
if (verb == HTTP_POST) {
response_ = client.post(r, (compress) ? compressString(params) : params);
} else {
response_ = client.put(r, (compress) ? compressString(params) : params);
}
const auto& response_body = body(response_);
if (FLAGS_verbose && FLAGS_tls_dump) {
fprintf(stdout, "%s\n", std::string(response_body).c_str());
}
response_status_ =
serializer_->deserialize(response_body, response_params_);
} catch (const std::exception& e) {
return Status((tlsFailure(e.what())) ? 2 : 1,
std::string("Request error: ") + e.what());
}
return response_status_;
}
}
<|endoftext|> |
<commit_before>
// .\Release\benchmarks.exe --benchmark_repetitions=5 --benchmark_min_time=30 --benchmark_filter=HarmonicOscillator // NOLINT(whitespace/line_length)
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include <algorithm>
#include <functional>
#include <type_traits>
#include <vector>
#include "base/not_null.hpp"
#include "geometry/frame.hpp"
#include "geometry/named_quantities.hpp"
#include "integrators/ordinary_differential_equations.hpp"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "glog/logging.h"
#include "quantities/elementary_functions.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/physics.pb.h"
#include "testing_utilities/integration.hpp"
// Must come last to avoid conflicts when defining the CHECK macros.
#include "benchmark/benchmark.h"
namespace principia {
using geometry::Displacement;
using geometry::Frame;
using geometry::Position;
using geometry::Velocity;
using integrators::CompositionMethod;
using integrators::IntegrationProblem;
using integrators::SpecialSecondOrderDifferentialEquation;
using quantities::Abs;
using quantities::AngularFrequency;
using quantities::Cos;
using quantities::Length;
using quantities::si::Metre;
using testing_utilities::ComputeHarmonicOscillatorAcceleration;
using ::std::placeholders::_1;
using ::std::placeholders::_2;
using ::std::placeholders::_3;
namespace benchmarks {
namespace {
using World = Frame<serialization::Frame::TestTag,
serialization::Frame::TEST, true>;
using ODE = SpecialSecondOrderDifferentialEquation<Position<World>>;
// TODO(egg): use the one from testing_utilities/integration again when everyone
// uses |Instant|s.
// Increments |*evaluations| if |evaluations| is not null.
void ComputeHarmonicOscillatorAcceleration(
Instant const& t,
std::vector<Position<World>> const& q,
std::vector<Vector<Acceleration, World>>* const result,
int* evaluations) {
(*result)[0] =
(World::origin - q[0]) * (SIUnit<Stiffness>() / SIUnit<Mass>());
if (evaluations != nullptr) {
++*evaluations;
}
}
} // namespace
template<typename Integrator>
void SolveHarmonicOscillatorAndComputeError(
not_null<benchmark::State*> const state,
not_null<Length*> const q_error,
not_null<Speed*> const v_error,
Integrator const& integrator) {
Displacement<World> const q_initial({1 * Metre, 0 * Metre, 0 * Metre});
Velocity<World> const v_initial;
Instant const t_initial;
#ifdef _DEBUG
Instant const t_final = t_initial + 100 * Second;
#else
Instant const t_final = t_initial + 1000 * Second;
#endif
Time const step = 3.0E-4 * Second;
int evaluations = 0;
std::vector<ODE::SystemState> solution;
ODE harmonic_oscillator;
harmonic_oscillator.compute_acceleration =
std::bind(ComputeHarmonicOscillatorAcceleration,
_1, _2, _3, &evaluations);
IntegrationProblem<ODE> problem;
problem.equation = harmonic_oscillator;
ODE::SystemState const initial_state = {{World::origin + q_initial},
{v_initial},
t_initial};
problem.initial_state = &initial_state;
problem.t_final = t_final;
problem.append_state = [&solution](ODE::SystemState const& state) {
solution.push_back(state);
};
integrator.Solve(problem, step);
state->PauseTiming();
int const steps = static_cast<int>(std::floor((t_final - t_initial) / step));
//CHECK_EQ(steps, solution.size());
*q_error = Length();
*v_error = Speed();
for (std::size_t i = 0; i < solution.size(); ++i) {
auto x = (solution[i].positions[0].value - World::origin);
*q_error = std::max(*q_error,
((solution[i].positions[0].value - World::origin) -
q_initial *
Cos((solution[i].time.value - t_initial) *
(Radian / Second))).Norm());
*v_error = std::max(*v_error,
(solution[i].velocities[0].value +
(q_initial / Second) *
Sin((solution[i].time.value - t_initial) *
(Radian / Second))).Norm());
}
state->ResumeTiming();
}
template<typename Integrator, Integrator const& (*integrator)()>
void BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator(
benchmark::State& state) { // NOLINT(runtime/references)
Length q_error;
Speed v_error;
while (state.KeepRunning()) {
SolveHarmonicOscillatorAndComputeError(&state, &q_error, &v_error,
integrator());
}
std::stringstream ss;
ss << q_error << ", " << v_error;
state.SetLabel(ss.str());
}
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlanAtela1992Order4Optimal<Position<World>>()),
&integrators::McLachlanAtela1992Order4Optimal<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlan1995SB3A4<Position<World>>()),
&integrators::McLachlan1995SB3A4<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlan1995SB3A5<Position<World>>()),
&integrators::McLachlan1995SB3A5<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::BlanesMoan2002SRKN6B<Position<World>>()),
&integrators::BlanesMoan2002SRKN6B<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlanAtela1992Order5Optimal<Position<World>>()),
&integrators::McLachlanAtela1992Order5Optimal<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::OkunborSkeel1994Order6Method13<Position<World>>()),
&integrators::OkunborSkeel1994Order6Method13<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::BlanesMoan2002SRKN11B<Position<World>>()),
&integrators::BlanesMoan2002SRKN11B<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::BlanesMoan2002SRKN14A<Position<World>>()),
&integrators::BlanesMoan2002SRKN14A<Position<World>>);
} // namespace benchmarks
} // namespace principia
<commit_msg>Cleanup.<commit_after>
// .\Release\benchmarks.exe --benchmark_repetitions=5 --benchmark_min_time=30 --benchmark_filter=SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator // NOLINT(whitespace/line_length)
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include <algorithm>
#include <functional>
#include <type_traits>
#include <vector>
#include "base/not_null.hpp"
#include "benchmark/benchmark.h"
#include "geometry/frame.hpp"
#include "geometry/named_quantities.hpp"
#include "integrators/ordinary_differential_equations.hpp"
#include "integrators/symplectic_runge_kutta_nyström_integrator.hpp"
#include "glog/logging.h"
#include "quantities/elementary_functions.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/si.hpp"
#include "serialization/physics.pb.h"
#include "testing_utilities/integration.hpp"
namespace principia {
using geometry::Displacement;
using geometry::Frame;
using geometry::Position;
using geometry::Velocity;
using integrators::CompositionMethod;
using integrators::IntegrationProblem;
using integrators::SpecialSecondOrderDifferentialEquation;
using quantities::Abs;
using quantities::AngularFrequency;
using quantities::Cos;
using quantities::Length;
using quantities::si::Metre;
using testing_utilities::ComputeHarmonicOscillatorAcceleration;
using ::std::placeholders::_1;
using ::std::placeholders::_2;
using ::std::placeholders::_3;
namespace benchmarks {
namespace {
using World = Frame<serialization::Frame::TestTag,
serialization::Frame::TEST, true>;
using ODE = SpecialSecondOrderDifferentialEquation<Position<World>>;
// TODO(egg): use the one from testing_utilities/integration again when everyone
// uses |Instant|s.
// Increments |*evaluations| if |evaluations| is not null.
void ComputeHarmonicOscillatorAcceleration(
Instant const& t,
std::vector<Position<World>> const& q,
std::vector<Vector<Acceleration, World>>* const result,
int* evaluations) {
(*result)[0] =
(World::origin - q[0]) * (SIUnit<Stiffness>() / SIUnit<Mass>());
if (evaluations != nullptr) {
++*evaluations;
}
}
} // namespace
template<typename Integrator>
void SolveHarmonicOscillatorAndComputeError(
not_null<benchmark::State*> const state,
not_null<Length*> const q_error,
not_null<Speed*> const v_error,
Integrator const& integrator) {
Displacement<World> const q_initial({1 * Metre, 0 * Metre, 0 * Metre});
Velocity<World> const v_initial;
Instant const t_initial;
#ifdef _DEBUG
Instant const t_final = t_initial + 100 * Second;
#else
Instant const t_final = t_initial + 1000 * Second;
#endif
Time const step = 3.0E-4 * Second;
int evaluations = 0;
std::vector<ODE::SystemState> solution;
ODE harmonic_oscillator;
harmonic_oscillator.compute_acceleration =
std::bind(ComputeHarmonicOscillatorAcceleration,
_1, _2, _3, &evaluations);
IntegrationProblem<ODE> problem;
problem.equation = harmonic_oscillator;
ODE::SystemState const initial_state = {{World::origin + q_initial},
{v_initial},
t_initial};
problem.initial_state = &initial_state;
problem.t_final = t_final;
problem.append_state = [&solution](ODE::SystemState const& state) {
solution.push_back(state);
};
integrator.Solve(problem, step);
state->PauseTiming();
*q_error = Length();
*v_error = Speed();
for (std::size_t i = 0; i < solution.size(); ++i) {
auto x = (solution[i].positions[0].value - World::origin);
*q_error = std::max(*q_error,
((solution[i].positions[0].value - World::origin) -
q_initial *
Cos((solution[i].time.value - t_initial) *
(Radian / Second))).Norm());
*v_error = std::max(*v_error,
(solution[i].velocities[0].value +
(q_initial / Second) *
Sin((solution[i].time.value - t_initial) *
(Radian / Second))).Norm());
}
state->ResumeTiming();
}
template<typename Integrator, Integrator const& (*integrator)()>
void BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator(
benchmark::State& state) { // NOLINT(runtime/references)
Length q_error;
Speed v_error;
while (state.KeepRunning()) {
SolveHarmonicOscillatorAndComputeError(&state, &q_error, &v_error,
integrator());
}
std::stringstream ss;
ss << q_error << ", " << v_error;
state.SetLabel(ss.str());
}
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlanAtela1992Order4Optimal<Position<World>>()),
&integrators::McLachlanAtela1992Order4Optimal<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlan1995SB3A4<Position<World>>()),
&integrators::McLachlan1995SB3A4<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlan1995SB3A5<Position<World>>()),
&integrators::McLachlan1995SB3A5<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::BlanesMoan2002SRKN6B<Position<World>>()),
&integrators::BlanesMoan2002SRKN6B<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::McLachlanAtela1992Order5Optimal<Position<World>>()),
&integrators::McLachlanAtela1992Order5Optimal<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::OkunborSkeel1994Order6Method13<Position<World>>()),
&integrators::OkunborSkeel1994Order6Method13<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::BlanesMoan2002SRKN11B<Position<World>>()),
&integrators::BlanesMoan2002SRKN11B<Position<World>>);
BENCHMARK_TEMPLATE2(
BM_SymplecticRungeKuttaNyströmIntegratorSolveHarmonicOscillator,
decltype(integrators::BlanesMoan2002SRKN14A<Position<World>>()),
&integrators::BlanesMoan2002SRKN14A<Position<World>>);
} // namespace benchmarks
} // namespace principia
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/visualization/software-license/
*
* 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 <cassert> // assert
#include <cstdlib> // std::atof
#include <cmath> // std::sqrt, std::pow
#include <iostream> // std::cout
#include <fstream> // std::ifstream
#include <vector> // std::vector
#include <string> // std::string
#include <sstream> // std::stringstream
#include <iomanip> // std::setw
#include <limits> // inifity
#include "ApplicationUtilities.h"
#include "GaussianProcessEmulatorDirectoryFormatIO.h"
#include "Paths.h"
#include "System.h"
int main(int argc, char ** argv) {
if (argc < 3) {
std::cerr
<< "Usage\n " << argv[0]
<< " statistics_directory trace_file\n\n";
return EXIT_FAILURE;
}
std::string statisticsDirectory( argv[1] );
madai::EnsurePathSeparatorAtEnd( statisticsDirectory );
std::vector< madai::Parameter > parameters;
int numberOfParameters = 0;
if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseParameters(
parameters, numberOfParameters, statisticsDirectory, false )) {
std::cerr
<< "Could not read parameters from prior file '"
<< statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << "'\n";
return EXIT_FAILURE;
}
assert (numberOfParameters = parameters.size());
std::vector< std::string > outputNames;
int numberOfOutputs = 0;
if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseOutputs(
outputNames, numberOfOutputs, statisticsDirectory, false )) {
std::cerr
<< "Could not read outputs from prior file '"
<< statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << "'\n";
return EXIT_FAILURE;
}
assert (numberOfOutputs = outputNames.size());
std::string traceFile( statisticsDirectory );
traceFile.append( argv[2] );
if ( !madai::System::IsFile( traceFile ) ) {
std::cerr << "Trace file '" << traceFile << "' does not exist or is a directory.\n";
return EXIT_FAILURE;
}
std::ifstream trace(traceFile.c_str());
if ( !trace.good() ) {
std::cerr << "Error reading trace file '" << traceFile << "'.\n";
return EXIT_FAILURE;
}
std::string header;
std::getline(trace,header);
std::vector<std::string> headers = madai::SplitString(header, ',');
int numberOfFields = headers.size();
assert(numberOfFields == numberOfParameters + numberOfOutputs + 1);
std::string line;
size_t lineCount = 0, bestIndex = 0;
std::vector< double > sums(numberOfFields - 1, 0.0);
std::vector< std::vector< double > > values(numberOfFields - 1);
double bestLogLikelihood = -std::numeric_limits< double >::infinity();
while (std::getline(trace,line)) {
std::vector<std::string> fields = madai::SplitString(line, ',');
assert(numberOfFields == (int) fields.size());
for (int i = 0; i < numberOfFields - 1; ++i) {
double value = std::atof(fields[i].c_str());
values[i].push_back(value);
sums[i] += value;
}
double logLikelihood = std::atof(fields[numberOfFields - 1].c_str());
if (logLikelihood > bestLogLikelihood) {
bestLogLikelihood = logLikelihood;
bestIndex = lineCount;
}
++lineCount;
}
trace.close();
std::vector< double > means(numberOfFields - 1,0.0);
std::vector< double > priorStdDev(numberOfFields - 1,0.0);
for (int i = 0; i < numberOfParameters; ++i) {
priorStdDev[i] =
parameters[i].GetPriorDistribution()->GetStandardDeviation();
}
std::cout << std::setw(14) << "parameter";
std::cout << std::setw(14) << "mean";
std::cout << std::setw(14) << "std.dev.";
std::cout << std::setw(14) << "scaled dev.";
std::cout << std::setw(14) << "best value";
std::cout << '\n';
for (int i = 0; i < numberOfFields - 1; ++i) {
means[i] = sums[i] / lineCount;
}
for (int i = 0; i < numberOfParameters; ++i) {
double variance = 0.0;
for (size_t k = 0; k < lineCount; ++k) {
variance += std::pow(values[i][k] - means[i], 2);
}
variance /= lineCount;
std::cout
<< std::setw(14) << parameters[i].m_Name
<< std::setw(14) << means[i]
<< std::setw(14) << std::sqrt(variance)
<< std::setw(14) << std::sqrt(variance) / priorStdDev[i]
<< std::setw(14) << values[i][bestIndex]
<< '\n';
}
// Print the relative log-likelihood from the best point
std::cout << "\nbest log likelihood\n";
std::cout << std::setw(14) << bestLogLikelihood << "\n";
std::vector< std::vector< double > > covariancematrix;
for (int i = 0; i < numberOfFields - 1; ++i)
covariancematrix.push_back(std::vector< double >(numberOfFields - 1, 0.0));
for (int i = 0; i < numberOfFields - 1; ++i) {
for (int j = 0; j <= i; ++j) {
double covariance = 0.0;
for (size_t k = 0; k < lineCount; ++k) {
covariance += (values[i][k] - means[i]) * (values[j][k] - means[j]);
}
covariancematrix[i][j] = covariance /= lineCount;
if (i != j)
covariancematrix[j][i] = covariancematrix[i][j];
}
}
std::cout << "\ncovariance:\n";
std::cout << std::setw(14) << "";
for (int j = 0; j < numberOfParameters; ++j)
std::cout << std::setw(14) << parameters[j].m_Name;
std::cout << "\n";
for (int i = 0; i < numberOfParameters; ++i) {
std::cout << std::setw(14) << parameters[i].m_Name;
for (int j = 0; j < numberOfParameters; ++j) {
std::cout << std::setw(14) << covariancematrix[i][j];
}
std::cout << "\n";
}
std::cout << "\nscaled covariance:\n";
std::cout << std::setw(14) << "";
for (int j = 0; j < numberOfParameters; ++j)
std::cout << std::setw(14) << parameters[j].m_Name;
std::cout << "\n";
for (int i = 0; i < numberOfParameters; ++i) {
std::cout << std::setw(14) << parameters[i].m_Name;
for (int j = 0; j < numberOfParameters; ++j) {
std::cout << std::setw(14) << covariancematrix[i][j] / (
priorStdDev[i] * priorStdDev[j]);
}
std::cout << "\n";
}
std::cout << "\nobservable-parameter correlation:\n";
std::cout << std::setw(14) << "";
for (int j = 0; j < numberOfParameters; ++j)
std::cout << std::setw(14) << parameters[j].m_Name;
std::cout << "\n";
for (int i = 0; i < numberOfOutputs; ++i) {
std::cout << std::setw(14) << outputNames[i];
for (int j = 0; j < numberOfParameters; ++j) {
std::cout << std::setw(14) << covariancematrix[numberOfParameters + i][j] / (
std::sqrt(covariancematrix[numberOfParameters + i][numberOfParameters + i]*
covariancematrix[j][j]));
}
std::cout << "\n";
}
return EXIT_SUCCESS;
}
<commit_msg>Changed assert statements to use either csv format.<commit_after>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/visualization/software-license/
*
* 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 <cassert> // assert
#include <cstdlib> // std::atof
#include <cmath> // std::sqrt, std::pow
#include <iostream> // std::cout
#include <fstream> // std::ifstream
#include <vector> // std::vector
#include <string> // std::string
#include <sstream> // std::stringstream
#include <iomanip> // std::setw
#include <limits> // inifity
#include "ApplicationUtilities.h"
#include "GaussianProcessEmulatorDirectoryFormatIO.h"
#include "Paths.h"
#include "System.h"
int main(int argc, char ** argv) {
if (argc < 3) {
std::cerr
<< "Usage\n " << argv[0]
<< " statistics_directory trace_file\n\n";
return EXIT_FAILURE;
}
std::string statisticsDirectory( argv[1] );
madai::EnsurePathSeparatorAtEnd( statisticsDirectory );
std::vector< madai::Parameter > parameters;
int numberOfParameters = 0;
if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseParameters(
parameters, numberOfParameters, statisticsDirectory, false )) {
std::cerr
<< "Could not read parameters from prior file '"
<< statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << "'\n";
return EXIT_FAILURE;
}
assert (numberOfParameters = parameters.size());
std::vector< std::string > outputNames;
int numberOfOutputs = 0;
if ( ! madai::GaussianProcessEmulatorDirectoryFormatIO::ParseOutputs(
outputNames, numberOfOutputs, statisticsDirectory, false )) {
std::cerr
<< "Could not read outputs from prior file '"
<< statisticsDirectory << madai::Paths::PARAMETER_PRIORS_FILE << "'\n";
return EXIT_FAILURE;
}
assert (numberOfOutputs = outputNames.size());
std::string traceFile( statisticsDirectory );
traceFile.append( argv[2] );
if ( !madai::System::IsFile( traceFile ) ) {
std::cerr << "Trace file '" << traceFile << "' does not exist or is a directory.\n";
return EXIT_FAILURE;
}
std::ifstream trace(traceFile.c_str());
if ( !trace.good() ) {
std::cerr << "Error reading trace file '" << traceFile << "'.\n";
return EXIT_FAILURE;
}
std::string header;
std::getline(trace,header);
std::vector<std::string> headers = madai::SplitString(header, ',');
int numberOfFields = headers.size();
bool gradientsPresent = false;
if( numberOfFields == numberOfParameters + 2*numberOfOutputs + 1 ) {
numberOfFields -= numberOfOutputs;
gradientsPresent = true;
}
assert(numberOfFields == numberOfParameters + numberOfOutputs + 1);
std::string line;
size_t lineCount = 0, bestIndex = 0;
std::vector< double > sums(numberOfFields - 1, 0.0);
std::vector< std::vector< double > > values(numberOfFields - 1);
double bestLogLikelihood = -std::numeric_limits< double >::infinity();
while (std::getline(trace,line)) {
std::vector<std::string> fields = madai::SplitString(line, ',');
assert(numberOfFields == (int) fields.size() - (gradientsPresent?numberOfOutputs:0));
for (int i = 0; i < numberOfFields - 1; ++i) {
double value = std::atof(fields[i].c_str());
values[i].push_back(value);
sums[i] += value;
}
double logLikelihood = std::atof(fields[numberOfFields - 1].c_str());
if (logLikelihood > bestLogLikelihood) {
bestLogLikelihood = logLikelihood;
bestIndex = lineCount;
}
++lineCount;
}
trace.close();
std::vector< double > means(numberOfFields - 1,0.0);
std::vector< double > priorStdDev(numberOfFields - 1,0.0);
for (int i = 0; i < numberOfParameters; ++i) {
priorStdDev[i] =
parameters[i].GetPriorDistribution()->GetStandardDeviation();
}
std::cout << std::setw(14) << "parameter";
std::cout << std::setw(14) << "mean";
std::cout << std::setw(14) << "std.dev.";
std::cout << std::setw(14) << "scaled dev.";
std::cout << std::setw(14) << "best value";
std::cout << '\n';
for (int i = 0; i < numberOfFields - 1; ++i) {
means[i] = sums[i] / lineCount;
}
for (int i = 0; i < numberOfParameters; ++i) {
double variance = 0.0;
for (size_t k = 0; k < lineCount; ++k) {
variance += std::pow(values[i][k] - means[i], 2);
}
variance /= lineCount;
std::cout
<< std::setw(14) << parameters[i].m_Name
<< std::setw(14) << means[i]
<< std::setw(14) << std::sqrt(variance)
<< std::setw(14) << std::sqrt(variance) / priorStdDev[i]
<< std::setw(14) << values[i][bestIndex]
<< '\n';
}
// Print the relative log-likelihood from the best point
std::cout << "\nbest log likelihood\n";
std::cout << std::setw(14) << bestLogLikelihood << "\n";
std::vector< std::vector< double > > covariancematrix;
for (int i = 0; i < numberOfFields - 1; ++i)
covariancematrix.push_back(std::vector< double >(numberOfFields - 1, 0.0));
for (int i = 0; i < numberOfFields - 1; ++i) {
for (int j = 0; j <= i; ++j) {
double covariance = 0.0;
for (size_t k = 0; k < lineCount; ++k) {
covariance += (values[i][k] - means[i]) * (values[j][k] - means[j]);
}
covariancematrix[i][j] = covariance /= lineCount;
if (i != j)
covariancematrix[j][i] = covariancematrix[i][j];
}
}
std::cout << "\ncovariance:\n";
std::cout << std::setw(14) << "";
for (int j = 0; j < numberOfParameters; ++j)
std::cout << std::setw(14) << parameters[j].m_Name;
std::cout << "\n";
for (int i = 0; i < numberOfParameters; ++i) {
std::cout << std::setw(14) << parameters[i].m_Name;
for (int j = 0; j < numberOfParameters; ++j) {
std::cout << std::setw(14) << covariancematrix[i][j];
}
std::cout << "\n";
}
std::cout << "\nscaled covariance:\n";
std::cout << std::setw(14) << "";
for (int j = 0; j < numberOfParameters; ++j)
std::cout << std::setw(14) << parameters[j].m_Name;
std::cout << "\n";
for (int i = 0; i < numberOfParameters; ++i) {
std::cout << std::setw(14) << parameters[i].m_Name;
for (int j = 0; j < numberOfParameters; ++j) {
std::cout << std::setw(14) << covariancematrix[i][j] / (
priorStdDev[i] * priorStdDev[j]);
}
std::cout << "\n";
}
std::cout << "\nobservable-parameter correlation:\n";
std::cout << std::setw(14) << "";
for (int j = 0; j < numberOfParameters; ++j)
std::cout << std::setw(14) << parameters[j].m_Name;
std::cout << "\n";
for (int i = 0; i < numberOfOutputs; ++i) {
std::cout << std::setw(14) << outputNames[i];
for (int j = 0; j < numberOfParameters; ++j) {
std::cout << std::setw(14) << covariancematrix[numberOfParameters + i][j] / (
std::sqrt(covariancematrix[numberOfParameters + i][numberOfParameters + i]*
covariancematrix[j][j]));
}
std::cout << "\n";
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "common/file_stream.h"
#include <streambuf>
#include <string>
#include <vector>
#ifdef _MSC_VER
#include <windows.h>
#include <io.h>
#else
#include <sys/types.h>
#include <unistd.h>
#endif
<commit_msg>delete unused includes<commit_after>#include "common/file_stream.h"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cmdlinehelp.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: ihi $ $Date: 2007-04-19 09:30:41 $
*
* 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_desktop.hxx"
#include <stdlib.h>
#ifdef UNX
#include <stdio.h>
#endif
#include <sal/types.h>
#include <tools/string.hxx>
#include <vcl/msgbox.hxx>
#include <rtl/bootstrap.hxx>
#include <app.hxx>
#include "desktopresid.hxx"
#include "desktop.hrc"
#include "cmdlinehelp.hxx"
namespace desktop
{
// to be able to display the help nicely in a dialog box with propotional font,
// we need to split it in chunks...
// ___HEAD___
// LEFT RIGHT
// LEFT RIGHT
// LEFT RIGHT
// __BOTTOM__
// [OK]
const char *aCmdLineHelp_head =
"%PRODUCTNAME %PRODUCTVERSION %PRODUCTEXTENSION %BUILDID\n"\
"\n"\
"Usage: %CMDNAME [options] [documents...]\n"\
"\n"\
"Options:\n";
const char *aCmdLineHelp_left =
"-minimized \n"\
"-invisible \n"\
"-norestore \n"\
"-quickstart \n"\
"-nologo \n"\
"-nolockcheck \n"\
"-nodefault \n"\
"-headless \n"\
"-help/-h/-? \n"\
"-writer \n"\
"-calc \n"\
"-draw \n"\
"-impress \n"\
"-base \n"\
"-math \n"\
"-global \n"\
"-web \n"\
"-o \n"\
"-n \n";
const char *aCmdLineHelp_right =
"keep startup bitmap minimized.\n"\
"no startup screen, no default document and no UI.\n"\
"suppress restart/restore after fatal errors.\n"\
"starts the quickstart service (only available on windows platform)\n"\
"don't show startup screen.\n"\
"don't check for remote instances using the installation\n"\
"don't start with an empty document\n"\
"like invisible but no userinteraction at all.\n"\
"show this message and exit.\n"\
"create new text document.\n"\
"create new spreadsheet document.\n"\
"create new drawing.\n"\
"create new presentation.\n"\
"create new database.\n"\
"create new formula.\n"\
"create new global document.\n"\
"create new HTML document.\n"\
"open documents regardless whether they are templates or not.\n"\
"always open documents as new files (use as template).\n";
const char *aCmdLineHelp_bottom =
"-display <display>\n"\
" Specify X-Display to use in Unix/X11 versions.\n"
"-p <documents...>\n"\
" print the specified documents on the default printer.\n"\
"-pt <printer> <documents...>\n"\
" print the specified documents on the specified printer.\n"\
"-view <documents...>\n"\
" open the specified documents in viewer-(readonly-)mode.\n"\
"-show <presentation>\n"\
" open the specified presentation and start it immediately\n"\
"-accept=<accept-string>\n"\
" Specify an UNO connect-string to create an UNO acceptor through which\n"\
" other programs can connect to access the API\n"\
"-unaccept=<accept-string>\n"\
" Close an acceptor that was created with -accept=<accept-string>\n"\
" Use -unnaccept=all to close all open acceptors\n"\
"Remaining arguments will be treated as filenames or URLs of documents to open.\n";
void ReplaceStringHookProc( UniString& rStr );
void displayCmdlineHelp()
{
// if you put variables in other chunks don't forget to call the replace routines
// for those chunks...
String aHelpMessage_head(aCmdLineHelp_head, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_left(aCmdLineHelp_left, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_right(aCmdLineHelp_right, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_bottom(aCmdLineHelp_bottom, RTL_TEXTENCODING_ASCII_US);
ReplaceStringHookProc(aHelpMessage_head);
::rtl::OUString aDefault;
String aVerId( ::utl::Bootstrap::getBuildIdData( aDefault ));
aHelpMessage_head.SearchAndReplaceAscii( "%BUILDID", aVerId );
aHelpMessage_head.SearchAndReplaceAscii( "%CMDNAME", String( "soffice", RTL_TEXTENCODING_ASCII_US) );
#ifdef UNX
// on unix use console for output
fprintf(stderr, "%s\n", ByteString(aHelpMessage_head,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
// merge left and right column
int n = aHelpMessage_left.GetTokenCount ('\n');
ByteString bsLeft(aHelpMessage_left, RTL_TEXTENCODING_ASCII_US);
ByteString bsRight(aHelpMessage_right, RTL_TEXTENCODING_ASCII_US);
for ( int i = 0; i < n; i++ )
{
fprintf(stderr, "%s", bsLeft.GetToken(i, '\n').GetBuffer());
fprintf(stderr, "%s\n", bsRight.GetToken(i, '\n').GetBuffer());
}
fprintf(stderr, "%s", ByteString(aHelpMessage_bottom,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
#else
// rest gets a dialog box
CmdlineHelpDialog aDlg;
aDlg.m_ftHead.SetText(aHelpMessage_head);
aDlg.m_ftLeft.SetText(aHelpMessage_left);
aDlg.m_ftRight.SetText(aHelpMessage_right);
aDlg.m_ftBottom.SetText(aHelpMessage_bottom);
aDlg.Execute();
#endif
}
CmdlineHelpDialog::CmdlineHelpDialog (void)
: ModalDialog( NULL, DesktopResId( DLG_CMDLINEHELP ) )
, m_ftHead( this, DesktopResId( TXT_DLG_CMDLINEHELP_HEADER ) )
, m_ftLeft( this, DesktopResId( TXT_DLG_CMDLINEHELP_LEFT ) )
, m_ftRight( this, DesktopResId( TXT_DLG_CMDLINEHELP_RIGHT ) )
, m_ftBottom( this, DesktopResId( TXT_DLG_CMDLINEHELP_BOTTOM ) )
, m_btOk( this, DesktopResId( BTN_DLG_CMDLINEHELP_OK ) )
{
FreeResource();
}
}
<commit_msg>INTEGRATION: CWS os2port01 (1.8.14); FILE MERGED 2007/08/10 08:14:29 obr 1.8.14.2: RESYNC: (1.8-1.10); FILE MERGED 2006/12/28 14:54:19 ydario 1.8.14.1: OS/2 initial import.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cmdlinehelp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2007-09-20 15:35:55 $
*
* 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_desktop.hxx"
#include <stdlib.h>
#ifdef UNX
#include <stdio.h>
#endif
#include <sal/types.h>
#include <tools/string.hxx>
#include <vcl/msgbox.hxx>
#include <rtl/bootstrap.hxx>
#include <app.hxx>
#include "desktopresid.hxx"
#include "desktop.hrc"
#include "cmdlinehelp.hxx"
namespace desktop
{
// to be able to display the help nicely in a dialog box with propotional font,
// we need to split it in chunks...
// ___HEAD___
// LEFT RIGHT
// LEFT RIGHT
// LEFT RIGHT
// __BOTTOM__
// [OK]
const char *aCmdLineHelp_head =
"%PRODUCTNAME %PRODUCTVERSION %PRODUCTEXTENSION %BUILDID\n"\
"\n"\
"Usage: %CMDNAME [options] [documents...]\n"\
"\n"\
"Options:\n";
const char *aCmdLineHelp_left =
"-minimized \n"\
"-invisible \n"\
"-norestore \n"\
"-quickstart \n"\
"-nologo \n"\
"-nolockcheck \n"\
"-nodefault \n"\
"-headless \n"\
"-help/-h/-? \n"\
"-writer \n"\
"-calc \n"\
"-draw \n"\
"-impress \n"\
"-base \n"\
"-math \n"\
"-global \n"\
"-web \n"\
"-o \n"\
"-n \n";
const char *aCmdLineHelp_right =
"keep startup bitmap minimized.\n"\
"no startup screen, no default document and no UI.\n"\
"suppress restart/restore after fatal errors.\n"\
"starts the quickstart service (only available on windows and OS/2 platform)\n"\
"don't show startup screen.\n"\
"don't check for remote instances using the installation\n"\
"don't start with an empty document\n"\
"like invisible but no userinteraction at all.\n"\
"show this message and exit.\n"\
"create new text document.\n"\
"create new spreadsheet document.\n"\
"create new drawing.\n"\
"create new presentation.\n"\
"create new database.\n"\
"create new formula.\n"\
"create new global document.\n"\
"create new HTML document.\n"\
"open documents regardless whether they are templates or not.\n"\
"always open documents as new files (use as template).\n";
const char *aCmdLineHelp_bottom =
"-display <display>\n"\
" Specify X-Display to use in Unix/X11 versions.\n"
"-p <documents...>\n"\
" print the specified documents on the default printer.\n"\
"-pt <printer> <documents...>\n"\
" print the specified documents on the specified printer.\n"\
"-view <documents...>\n"\
" open the specified documents in viewer-(readonly-)mode.\n"\
"-show <presentation>\n"\
" open the specified presentation and start it immediately\n"\
"-accept=<accept-string>\n"\
" Specify an UNO connect-string to create an UNO acceptor through which\n"\
" other programs can connect to access the API\n"\
"-unaccept=<accept-string>\n"\
" Close an acceptor that was created with -accept=<accept-string>\n"\
" Use -unnaccept=all to close all open acceptors\n"\
"Remaining arguments will be treated as filenames or URLs of documents to open.\n";
void ReplaceStringHookProc( UniString& rStr );
void displayCmdlineHelp()
{
// if you put variables in other chunks don't forget to call the replace routines
// for those chunks...
String aHelpMessage_head(aCmdLineHelp_head, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_left(aCmdLineHelp_left, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_right(aCmdLineHelp_right, RTL_TEXTENCODING_ASCII_US);
String aHelpMessage_bottom(aCmdLineHelp_bottom, RTL_TEXTENCODING_ASCII_US);
ReplaceStringHookProc(aHelpMessage_head);
::rtl::OUString aDefault;
String aVerId( ::utl::Bootstrap::getBuildIdData( aDefault ));
aHelpMessage_head.SearchAndReplaceAscii( "%BUILDID", aVerId );
aHelpMessage_head.SearchAndReplaceAscii( "%CMDNAME", String( "soffice", RTL_TEXTENCODING_ASCII_US) );
#ifdef UNX
// on unix use console for output
fprintf(stderr, "%s\n", ByteString(aHelpMessage_head,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
// merge left and right column
int n = aHelpMessage_left.GetTokenCount ('\n');
ByteString bsLeft(aHelpMessage_left, RTL_TEXTENCODING_ASCII_US);
ByteString bsRight(aHelpMessage_right, RTL_TEXTENCODING_ASCII_US);
for ( int i = 0; i < n; i++ )
{
fprintf(stderr, "%s", bsLeft.GetToken(i, '\n').GetBuffer());
fprintf(stderr, "%s\n", bsRight.GetToken(i, '\n').GetBuffer());
}
fprintf(stderr, "%s", ByteString(aHelpMessage_bottom,
RTL_TEXTENCODING_ASCII_US).GetBuffer());
#else
// rest gets a dialog box
CmdlineHelpDialog aDlg;
aDlg.m_ftHead.SetText(aHelpMessage_head);
aDlg.m_ftLeft.SetText(aHelpMessage_left);
aDlg.m_ftRight.SetText(aHelpMessage_right);
aDlg.m_ftBottom.SetText(aHelpMessage_bottom);
aDlg.Execute();
#endif
}
CmdlineHelpDialog::CmdlineHelpDialog (void)
: ModalDialog( NULL, DesktopResId( DLG_CMDLINEHELP ) )
, m_ftHead( this, DesktopResId( TXT_DLG_CMDLINEHELP_HEADER ) )
, m_ftLeft( this, DesktopResId( TXT_DLG_CMDLINEHELP_LEFT ) )
, m_ftRight( this, DesktopResId( TXT_DLG_CMDLINEHELP_RIGHT ) )
, m_ftBottom( this, DesktopResId( TXT_DLG_CMDLINEHELP_BOTTOM ) )
, m_btOk( this, DesktopResId( BTN_DLG_CMDLINEHELP_OK ) )
{
FreeResource();
}
}
<|endoftext|> |
<commit_before>#include "GameComponent.h"
#include "Model.h"
#include "Game.h"
#include <iostream>
#include <cmath>
//#include <glm/gtx/constants.hpp>
#include <ctime>
#include "VectorDrawer.h"
using namespace BGE;
using namespace std;
float BGE::RandomFloat()
{
return (float)rand()/(float)RAND_MAX;
}
GameComponent::GameComponent(bool hasTransform)
{
speed = 10.0f;
parent = NULL;
tag = "Nothing";
if (hasTransform)
{
transform = make_shared<Transform>();
}
else
{
transform = nullptr;
}
transformOwner = hasTransform;
alive = true;
initialised = false;
isRelative = false;
}
GameComponent::~GameComponent()
{
}
int GameComponent::ClearChildrenWithTag(string tag)
{
int count = 0;
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = * it;
if (child->tag == tag)
{
shared_ptr<GameComponent> component = * it;
component->alive = false;
component->ClearAllChildren();
count++;
}
it++;
}
return count;
}
int GameComponent::ClearAllChildren()
{
int count = 0;
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> component = *it;
component->alive = false;
component->ClearAllChildren();
++it;
count++;
}
return count;
}
bool GameComponent::Initialise()
{
// Initialise all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
try
{
while (it != children.end())
{
(*it)->initialised = (*it)->Initialise();
*it++;
}
}
catch (BGE::Exception e)
{
fprintf(stdout, e.What());
}
return true;
}
void GameComponent::Draw()
{
// Draw all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
// This is necessary for models etc that are instanced
// As they may be attached to several different parents
(*it)->parent = This();
if (!(*it)->transformOwner)
{
(*it)->transform = transform;
}
(*it ++)->Draw();
}
}
void GameComponent::PreDraw()
{
// Draw all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
// This is necessary for models etc that are instanced
// As they may be attached to several different parents
(*it)->parent = This();
if (!(*it)->transformOwner)
{
(*it)->transform = transform;
}
(*it++)->PreDraw();
}
}
void GameComponent::PostDraw()
{
// Draw all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
// This is necessary for models etc that are instanced
// As they may be attached to several different parents
(*it)->parent = This();
if (!(*it)->transformOwner)
{
(*it)->transform = transform;
}
(*it++)->PostDraw();
}
}
void GameComponent::Cleanup()
{
// Cleanup all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
(*it ++)->Cleanup();
}
}
void GameComponent::SetAlive(bool alive)
{
this->alive = alive;
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
(*it)->alive = alive;
}
}
void GameComponent::Update(float timeDelta) {
// Update all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> current = *it;
if (!alive)
{
current->alive = false;
}
current->parent = This();
current->Update(timeDelta);
if (!current->alive)
{
current->parent = nullptr;
it = children.erase(it);
}
else
{
++it;
}
}
multimap<string, shared_ptr<GameComponent>>::iterator mit = childrenMap.begin();
while (mit != childrenMap.end())
{
if (!(*mit).second->alive)
{
shared_ptr<GameComponent> g = mit->second;
mit = childrenMap.erase(mit);
}
else
{
++mit;
}
}
// Only the transforms owner will calculate the transform. ALl the other components should
// just update the position and the quaternion
if (transformOwner)
{
transform->Calculate();
}
}
void GameComponent::Attach(shared_ptr<GameComponent> child)
{
child->parent = This();
// All my children share the same transform if they dont already have one...
if (child->transform == nullptr)
{
child->transform = transform;
}
// Set up transform parenting
if (transformOwner && child->transformOwner)
{
child->transform->parent = transform;
}
children.push_back(child);
childrenMap.insert(std::pair<std::string, shared_ptr<GameComponent>>(child->tag, child));
}
std::list<std::shared_ptr<GameComponent>> * GameComponent::GetChildren()
{
return & children;
}
shared_ptr<GameComponent> GameComponent::FindComponentByTag(std::string tag)
{
std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator it = childrenMap.find(tag);
if (it != childrenMap.end())
{
return it->second;
}
else
{
return nullptr;
}
/*std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
if ((*it)->tag == tag)
{
return *it;
}
it++;
}
return nullptr;*/
}
std::vector<std::shared_ptr<GameComponent>> GameComponent::FindComponentsByTag(std::string tag)
{
// This looks ugly, but hey thats C++ for ya
pair<std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator
, std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator> range = childrenMap.equal_range(tag);
std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator it = range.first;
std::vector<std::shared_ptr<GameComponent>> components;
while (it != range.second)
{
components.push_back((*it).second);
it++;
}
return components;
}
std::shared_ptr<GameComponent> GameComponent::This()
{
return shared_from_this();
}
void BGE::GameComponent::TransformChildren(shared_ptr<Transform> childTransform)
{
// Transform all the bones by the handTransform
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = *it;
child->transform->position = childTransform->TransformPosition(child->transform->position, false);
it++;
}
}
void BGE::GameComponent::TransformChildren(glm::mat4 mat)
{
// Transform all the bones by the handTransform
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = *it;
child->transform->position = glm::vec3(mat * glm::vec4(child->transform->position, 1.0f));
it++;
}
}
void BGE::GameComponent::InverseTransformChildren(shared_ptr<Transform> childTransform)
{
// Transform all the bones by the handTransform
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = *it;
child->transform->position = childTransform->InverseTransformPosition(child->transform->position, false);
child->transform->orientation = childTransform->InverseTransformOrientation(child->transform->orientation);
it++;
}
}
<commit_msg>Added git notes<commit_after>#include "GameComponent.h"
#include "Model.h"
#include "Game.h"
#include <iostream>
#include <cmath>
//#include <glm/gtx/constants.hpp>
#include <ctime>
#include "VectorDrawer.h"
using namespace BGE;
using namespace std;
float BGE::RandomFloat()
{
return (float)rand()/(float)RAND_MAX;
}
GameComponent::GameComponent(bool hasTransform)
{
speed = 10.0f;
parent = NULL;
tag = "Nothing";
if (hasTransform)
{
transform = make_shared<Transform>();
}
else
{
transform = nullptr;
}
transformOwner = hasTransform;
alive = true;
initialised = false;
isRelative = false;
}
GameComponent::~GameComponent()
{
}
int GameComponent::ClearChildrenWithTag(string tag)
{
int count = 0;
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = * it;
if (child->tag == tag)
{
shared_ptr<GameComponent> component = * it;
component->alive = false;
component->ClearAllChildren();
count++;
}
it++;
}
return count;
}
int GameComponent::ClearAllChildren()
{
int count = 0;
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> component = *it;
component->alive = false;
component->ClearAllChildren();
++it;
count++;
}
return count;
}
bool GameComponent::Initialise()
{
// Initialise all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
try
{
while (it != children.end())
{
(*it)->initialised = (*it)->Initialise();
*it++;
}
}
catch (BGE::Exception e)
{
fprintf(stdout, e.What());
}
return true;
}
void GameComponent::Draw()
{
// Draw all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
// This is necessary for models etc that are instanced
// As they may be attached to several different parents
(*it)->parent = This();
if (!(*it)->transformOwner)
{
(*it)->transform = transform;
}
(*it ++)->Draw();
}
}
void GameComponent::PreDraw()
{
// Draw all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
// This is necessary for models etc that are instanced
// As they may be attached to several different parents
(*it)->parent = This();
if (!(*it)->transformOwner)
{
(*it)->transform = transform;
}
(*it++)->PreDraw();
}
}
void GameComponent::PostDraw()
{
// Draw all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
// This is necessary for models etc that are instanced
// As they may be attached to several different parents
(*it)->parent = This();
if (!(*it)->transformOwner)
{
(*it)->transform = transform;
}
(*it++)->PostDraw();
}
}
void GameComponent::Cleanup()
{
// Cleanup all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
(*it ++)->Cleanup();
}
}
void GameComponent::SetAlive(bool alive)
{
this->alive = alive;
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
(*it)->alive = alive;
}
}
void GameComponent::Update(float timeDelta) {
// Update all the children
std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> current = *it;
if (!alive)
{
current->alive = false;
}
current->parent = This();
current->Update(timeDelta);
if (!current->alive)
{
current->parent = nullptr;
it = children.erase(it);
}
else
{
++it;
}
}
multimap<string, shared_ptr<GameComponent>>::iterator mit = childrenMap.begin();
while (mit != childrenMap.end())
{
if (!(*mit).second->alive)
{
shared_ptr<GameComponent> g = mit->second;
mit = childrenMap.erase(mit);
}
else
{
++mit;
}
}
// Only the transforms owner will calculate the transform. ALl the other components should
// just update the position and the quaternion
if (transformOwner)
{
transform->Calculate();
}
}
void GameComponent::Attach(shared_ptr<GameComponent> child)
{
child->parent = This();
// All my children share the same transform if they dont already have one...
if (child->transform == nullptr)
{
child->transform = transform;
}
// Set up transform parenting
if (transformOwner && child->transformOwner)
{
child->transform->parent = transform;
}
children.push_back(child);
childrenMap.insert(std::pair<std::string, shared_ptr<GameComponent>>(child->tag, child));
}
std::list<std::shared_ptr<GameComponent>> * GameComponent::GetChildren()
{
return & children;
}
shared_ptr<GameComponent> GameComponent::FindComponentByTag(std::string tag)
{
std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator it = childrenMap.find(tag);
if (it != childrenMap.end())
{
return it->second;
}
else
{
return nullptr;
}
/*std::list<std::shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
if ((*it)->tag == tag)
{
return *it;
}
it++;
}
return nullptr;*/
}
std::vector<std::shared_ptr<GameComponent>> GameComponent::FindComponentsByTag(std::string tag)
{
// This looks ugly, but hey thats C++ for ya
pair<std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator
, std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator> range = childrenMap.equal_range(tag);
std::multimap<std::string, std::shared_ptr<GameComponent>>::iterator it = range.first;
std::vector<std::shared_ptr<GameComponent>> components;
while (it != range.second)
{
components.push_back((*it).second);
it++;
}
return components;
}
std::shared_ptr<GameComponent> GameComponent::This()
{
return shared_from_this();
}
void BGE::GameComponent::TransformChildren(shared_ptr<Transform> childTransform)
{
// Transform all the bones by the handTransform
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = *it;
child->transform->position = childTransform->TransformPosition(child->transform->position, false);
it++;
}
}
void BGE::GameComponent::TransformChildren(glm::mat4 mat)
{
// Transform all the bones by the handTransform
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = *it;
child->transform->position = glm::vec3(mat * glm::vec4(child->transform->position, 1.0f));
it++;
}
}
void BGE::GameComponent::InverseTransformChildren(shared_ptr<Transform> childTransform)
{
// Transform all the bones by the handTransform
list<shared_ptr<GameComponent>>::iterator it = children.begin();
while (it != children.end())
{
shared_ptr<GameComponent> child = *it;
child->transform->position = childTransform->InverseTransformPosition(child->transform->position, false);
child->transform->orientation = childTransform->InverseTransformOrientation(child->transform->orientation);
it++;
}
}
<|endoftext|> |
<commit_before>/* Random.hpp
*
* Kubo Ryosuke
*/
#ifndef SUNFISH_COMMON_MATH_RANDOM_HPP__
#define SUNFISH_COMMON_MATH_RANDOM_HPP__
#include "common/Def.hpp"
#include <random>
#include <ctime>
#include <cstdint>
namespace sunfish {
template <class GenType>
class BaseRandom {
public:
BaseRandom() : rgen(static_cast<unsigned>(time(NULL))) {
}
BaseRandom(const BaseRandom&) = delete;
BaseRandom(BaseRandom&&) = delete;
uint16_t int16() {
std::uniform_int_distribution<uint16_t> dst16;
return dst16(rgen);
}
uint16_t int16(uint16_t num) {
std::uniform_int_distribution<uint16_t> dst16(0, num-1);
return dst16(rgen);
}
uint32_t int32() {
std::uniform_int_distribution<uint32_t> dst32;
return dst32(rgen);
}
uint32_t int32(uint32_t num) {
std::uniform_int_distribution<uint32_t> dst32(0, num-1);
return dst32(rgen);
}
uint64_t int64() {
std::uniform_int_distribution<uint64_t> dst64;
return dst64(rgen);
}
uint64_t int64(uint64_t num) {
std::uniform_int_distribution<uint64_t> dst64(0, num-1);
return dst64(rgen);
}
unsigned bit() {
std::uniform_int_distribution<unsigned> dstBit(0, 1);
return dstBit(rgen);
}
template <class T>
unsigned nonuniform(unsigned num, T&& weightFunc) {
uint64_t total = 0.0f;
for (unsigned i = 0; i < num; i++) {
total += weightFunc(i);
}
uint64_t r = int64(total);
for (unsigned i = 0; i < num - 1; i++) {
uint64_t w = weightFunc(i);
if (r < w) {
return i;
}
r -= w;
}
return num - 1;
}
template <class Iterator>
void shuffle(Iterator begin, Iterator end) {
size_t n = end - begin;
for (size_t i = 0; i + 1 < n; i++) {
size_t t = i + int64(n - i);
auto tmp = begin[i];
begin[i] = begin[t];
begin[t] = tmp;
}
}
private:
GenType rgen;
};
using Random = BaseRandom<std::mt19937>;
} // namespace sunfish
#endif //SUNFISH_COMMON_MATH_RANDOM_HPP__
<commit_msg>Fix literal value type<commit_after>/* Random.hpp
*
* Kubo Ryosuke
*/
#ifndef SUNFISH_COMMON_MATH_RANDOM_HPP__
#define SUNFISH_COMMON_MATH_RANDOM_HPP__
#include "common/Def.hpp"
#include <random>
#include <ctime>
#include <cstdint>
namespace sunfish {
template <class GenType>
class BaseRandom {
public:
BaseRandom() : rgen(static_cast<unsigned>(time(NULL))) {
}
BaseRandom(const BaseRandom&) = delete;
BaseRandom(BaseRandom&&) = delete;
uint16_t int16() {
std::uniform_int_distribution<uint16_t> dst16;
return dst16(rgen);
}
uint16_t int16(uint16_t num) {
std::uniform_int_distribution<uint16_t> dst16(0, num-1);
return dst16(rgen);
}
uint32_t int32() {
std::uniform_int_distribution<uint32_t> dst32;
return dst32(rgen);
}
uint32_t int32(uint32_t num) {
std::uniform_int_distribution<uint32_t> dst32(0, num-1);
return dst32(rgen);
}
uint64_t int64() {
std::uniform_int_distribution<uint64_t> dst64;
return dst64(rgen);
}
uint64_t int64(uint64_t num) {
std::uniform_int_distribution<uint64_t> dst64(0, num-1);
return dst64(rgen);
}
unsigned bit() {
std::uniform_int_distribution<unsigned> dstBit(0, 1);
return dstBit(rgen);
}
template <class T>
unsigned nonuniform(unsigned num, T&& weightFunc) {
uint64_t total = 0;
for (unsigned i = 0; i < num; i++) {
total += weightFunc(i);
}
uint64_t r = int64(total);
for (unsigned i = 0; i < num - 1; i++) {
uint64_t w = weightFunc(i);
if (r < w) {
return i;
}
r -= w;
}
return num - 1;
}
template <class Iterator>
void shuffle(Iterator begin, Iterator end) {
size_t n = end - begin;
for (size_t i = 0; i + 1 < n; i++) {
size_t t = i + int64(n - i);
auto tmp = begin[i];
begin[i] = begin[t];
begin[t] = tmp;
}
}
private:
GenType rgen;
};
using Random = BaseRandom<std::mt19937>;
} // namespace sunfish
#endif //SUNFISH_COMMON_MATH_RANDOM_HPP__
<|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "server_update.h"
#include "../urlplugin/IUrlFactory.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include "DataplanDb.h"
#include <stdlib.h>
#include <memory>
extern IUrlFactory *url_fak;
namespace
{
std::string urbackup_update_url = "http://update4.urbackup.org/";
std::string urbackup_update_url_alt;
struct SUpdatePlatform
{
SUpdatePlatform(std::string extension,
std::string basename, std::string versionname)
: extension(extension), basename(basename),
versionname(versionname)
{}
std::string extension;
std::string basename;
std::string versionname;
};
}
ServerUpdate::ServerUpdate(void)
{
}
void ServerUpdate::update_client()
{
if(url_fak==NULL)
{
Server->Log("Urlplugin not found. Cannot download client for autoupdate.", LL_ERROR);
return;
}
read_update_location();
std::string http_proxy = Server->getServerParameter("http_proxy");
std::vector<SUpdatePlatform> update_files;
update_files.push_back(SUpdatePlatform("exe", "UrBackupUpdate", "version.txt"));
update_files.push_back(SUpdatePlatform("sh", "UrBackupUpdateMac", "version_osx.txt"));
update_files.push_back(SUpdatePlatform("sh", "UrBackupUpdateLinux", "version_linux.txt"));
std::string curr_update_url = urbackup_update_url;
for (size_t i = 0; i < update_files.size(); ++i)
{
SUpdatePlatform& curr = update_files[i];
std::string errmsg;
Server->Log("Downloading version file...", LL_INFO);
std::string version = url_fak->downloadString(curr_update_url + curr.versionname, http_proxy, &errmsg);
if (version.empty())
{
if (curr_update_url == urbackup_update_url)
{
curr_update_url = urbackup_update_url_alt;
version = url_fak->downloadString(curr_update_url + curr.versionname, http_proxy, &errmsg);
}
if (version.empty())
{
Server->Log("Error while downloading version info from " + curr_update_url + curr.versionname + ": " + errmsg, LL_ERROR);
return;
}
}
std::string curr_version = getFile("urbackup/"+curr.versionname);
if (curr_version.empty()) curr_version = "0";
if (version!=curr_version)
{
Server->Log("Downloading signature...", LL_INFO);
IFile* sig_file = Server->openFile("urbackup/" + curr.basename + ".sig2", MODE_WRITE);
if (sig_file == NULL)
{
Server->Log("Error opening signature output file urbackup/" + curr.basename + ".sig2", LL_ERROR);
return;
}
ObjectScope sig_file_scope(sig_file);
bool b = url_fak->downloadFile(curr_update_url + curr.basename + ".sig2", sig_file, http_proxy, &errmsg);
if (!b)
{
Server->Log("Error while downloading update signature from " + curr_update_url + curr.basename + ".sig2: " + errmsg, LL_ERROR);
}
if (curr.extension == "exe")
{
Server->Log("Downloading old signature...", LL_INFO);
IFile* old_sig_file = Server->openFile("urbackup/" + curr.basename + ".sig", MODE_WRITE);
if (old_sig_file == NULL)
{
Server->Log("Error opening signature output file urbackup/" + curr.basename + ".sig", LL_ERROR);
return;
}
ObjectScope old_sig_file_scope(old_sig_file);
bool b = url_fak->downloadFile(curr_update_url + curr.basename + ".sig", old_sig_file, http_proxy, &errmsg);
if (!b)
{
Server->Log("Error while downloading old update signature from " + curr_update_url + curr.basename + ".sig: " + errmsg, LL_ERROR);
}
}
Server->Log("Getting update file URL...", LL_INFO);
std::string update_url = url_fak->downloadString(curr_update_url + curr.basename + ".url", http_proxy, &errmsg);
if (update_url.empty())
{
Server->Log("Error while downloading update url from " + curr_update_url + curr.basename + ".url: " + errmsg, LL_ERROR);
return;
}
IFile* update_file = Server->openFile("urbackup/" + curr.basename + "." + curr.extension, MODE_WRITE);
if (update_file == NULL)
{
Server->Log("Error opening update output file urbackup/" + curr.basename + "." + curr.extension, LL_ERROR);
return;
}
ObjectScope update_file_scope(update_file);
Server->Log("Downloading update file...", LL_INFO);
b = url_fak->downloadFile(update_url, update_file, http_proxy, &errmsg);
if (!b)
{
Server->Log("Error while downloading update file from " + update_url + ": " + errmsg, LL_ERROR);
return;
}
sig_file->Sync();
update_file->Sync();
Server->Log("Successfully downloaded update file.", LL_INFO);
writestring(version, "urbackup/"+curr.versionname);
}
}
}
void ServerUpdate::update_server_version_info()
{
if(url_fak==NULL)
{
Server->Log("Urlplugin not found. Cannot download server version info.", LL_ERROR);
return;
}
read_update_location();
std::string http_proxy = Server->getServerParameter("http_proxy");
std::string errmsg;
Server->Log("Downloading server version info...", LL_INFO);
std::auto_ptr<IFile> server_version_info(Server->openFile("urbackup/server_version_info.properties.new", MODE_WRITE));
if(!server_version_info.get())
{
Server->Log("Error opening urbackup/server_version_info.properties.new for writing", LL_ERROR);
}
else
{
if(!url_fak->downloadFile(urbackup_update_url+"server_version_info.properties",
server_version_info.get(), http_proxy, &errmsg) )
{
Server->Log("Error downloading server version information: " + errmsg, LL_ERROR);
}
else
{
server_version_info.reset();
if (!os_rename_file("urbackup/server_version_info.properties.new",
"urbackup/server_version_info.properties"))
{
Server->Log("Error renaming server_version_info.properties . " + os_last_error_str(), LL_ERROR);
}
}
}
}
void ServerUpdate::update_dataplan_db()
{
if (url_fak == NULL)
{
Server->Log("Urlplugin not found. Cannot download dataplan database.", LL_ERROR);
return;
}
read_update_location();
std::string http_proxy = Server->getServerParameter("http_proxy");
std::string errmsg;
Server->Log("Downloading dataplan database...", LL_INFO);
std::auto_ptr<IFile> dataplan_db(Server->openFile("urbackup/dataplan_db.txt.new", MODE_WRITE));
if (!dataplan_db.get())
{
Server->Log("Error opening urbackup/dataplan_db.txt.new for writing", LL_ERROR);
}
else
{
if (!url_fak->downloadFile(urbackup_update_url + "dataplan_db.txt",
dataplan_db.get(), http_proxy, &errmsg))
{
Server->Log("Error downloading dataplan database: " + errmsg, LL_ERROR);
}
else
{
dataplan_db.reset();
if (!os_rename_file("urbackup/dataplan_db.txt.new",
"urbackup/dataplan_db.txt"))
{
Server->Log("Error renaming urbackup/dataplan_db.txt. " + os_last_error_str(), LL_ERROR);
}
DataplanDb::getInstance()->read("urbackup/dataplan_db.txt");
}
}
}
void ServerUpdate::read_update_location()
{
std::string read_update_location = trim(getFile("urbackup/server_update_location.url"));
if (!read_update_location.empty())
{
urbackup_update_url_alt = read_update_location;
urbackup_update_url = urbackup_update_url_alt + "/2.1.x";
}
}
<commit_msg>Fix update url construction<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2016 Martin Raiber
*
* This program 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "server_update.h"
#include "../urlplugin/IUrlFactory.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include "DataplanDb.h"
#include <stdlib.h>
#include <memory>
extern IUrlFactory *url_fak;
namespace
{
std::string urbackup_update_url = "http://update4.urbackup.org/";
std::string urbackup_update_url_alt;
struct SUpdatePlatform
{
SUpdatePlatform(std::string extension,
std::string basename, std::string versionname)
: extension(extension), basename(basename),
versionname(versionname)
{}
std::string extension;
std::string basename;
std::string versionname;
};
}
ServerUpdate::ServerUpdate(void)
{
}
void ServerUpdate::update_client()
{
if(url_fak==NULL)
{
Server->Log("Urlplugin not found. Cannot download client for autoupdate.", LL_ERROR);
return;
}
read_update_location();
std::string http_proxy = Server->getServerParameter("http_proxy");
std::vector<SUpdatePlatform> update_files;
update_files.push_back(SUpdatePlatform("exe", "UrBackupUpdate", "version.txt"));
update_files.push_back(SUpdatePlatform("sh", "UrBackupUpdateMac", "version_osx.txt"));
update_files.push_back(SUpdatePlatform("sh", "UrBackupUpdateLinux", "version_linux.txt"));
std::string curr_update_url = urbackup_update_url;
for (size_t i = 0; i < update_files.size(); ++i)
{
SUpdatePlatform& curr = update_files[i];
std::string errmsg;
Server->Log("Downloading version file...", LL_INFO);
std::string version = url_fak->downloadString(curr_update_url + curr.versionname, http_proxy, &errmsg);
if (version.empty())
{
if (curr_update_url == urbackup_update_url)
{
curr_update_url = urbackup_update_url_alt;
version = url_fak->downloadString(curr_update_url + curr.versionname, http_proxy, &errmsg);
}
if (version.empty())
{
Server->Log("Error while downloading version info from " + curr_update_url + curr.versionname + ": " + errmsg, LL_ERROR);
return;
}
}
std::string curr_version = getFile("urbackup/"+curr.versionname);
if (curr_version.empty()) curr_version = "0";
if (version!=curr_version)
{
Server->Log("Downloading signature...", LL_INFO);
IFile* sig_file = Server->openFile("urbackup/" + curr.basename + ".sig2", MODE_WRITE);
if (sig_file == NULL)
{
Server->Log("Error opening signature output file urbackup/" + curr.basename + ".sig2", LL_ERROR);
return;
}
ObjectScope sig_file_scope(sig_file);
bool b = url_fak->downloadFile(curr_update_url + curr.basename + ".sig2", sig_file, http_proxy, &errmsg);
if (!b)
{
Server->Log("Error while downloading update signature from " + curr_update_url + curr.basename + ".sig2: " + errmsg, LL_ERROR);
}
if (curr.extension == "exe")
{
Server->Log("Downloading old signature...", LL_INFO);
IFile* old_sig_file = Server->openFile("urbackup/" + curr.basename + ".sig", MODE_WRITE);
if (old_sig_file == NULL)
{
Server->Log("Error opening signature output file urbackup/" + curr.basename + ".sig", LL_ERROR);
return;
}
ObjectScope old_sig_file_scope(old_sig_file);
bool b = url_fak->downloadFile(curr_update_url + curr.basename + ".sig", old_sig_file, http_proxy, &errmsg);
if (!b)
{
Server->Log("Error while downloading old update signature from " + curr_update_url + curr.basename + ".sig: " + errmsg, LL_ERROR);
}
}
Server->Log("Getting update file URL...", LL_INFO);
std::string update_url = url_fak->downloadString(curr_update_url + curr.basename + ".url", http_proxy, &errmsg);
if (update_url.empty())
{
Server->Log("Error while downloading update url from " + curr_update_url + curr.basename + ".url: " + errmsg, LL_ERROR);
return;
}
IFile* update_file = Server->openFile("urbackup/" + curr.basename + "." + curr.extension, MODE_WRITE);
if (update_file == NULL)
{
Server->Log("Error opening update output file urbackup/" + curr.basename + "." + curr.extension, LL_ERROR);
return;
}
ObjectScope update_file_scope(update_file);
Server->Log("Downloading update file...", LL_INFO);
b = url_fak->downloadFile(update_url, update_file, http_proxy, &errmsg);
if (!b)
{
Server->Log("Error while downloading update file from " + update_url + ": " + errmsg, LL_ERROR);
return;
}
sig_file->Sync();
update_file->Sync();
Server->Log("Successfully downloaded update file.", LL_INFO);
writestring(version, "urbackup/"+curr.versionname);
}
}
}
void ServerUpdate::update_server_version_info()
{
if(url_fak==NULL)
{
Server->Log("Urlplugin not found. Cannot download server version info.", LL_ERROR);
return;
}
read_update_location();
std::string http_proxy = Server->getServerParameter("http_proxy");
std::string errmsg;
Server->Log("Downloading server version info...", LL_INFO);
std::auto_ptr<IFile> server_version_info(Server->openFile("urbackup/server_version_info.properties.new", MODE_WRITE));
if(!server_version_info.get())
{
Server->Log("Error opening urbackup/server_version_info.properties.new for writing", LL_ERROR);
}
else
{
if(!url_fak->downloadFile(urbackup_update_url+"server_version_info.properties",
server_version_info.get(), http_proxy, &errmsg) )
{
Server->Log("Error downloading server version information: " + errmsg, LL_ERROR);
}
else
{
server_version_info.reset();
if (!os_rename_file("urbackup/server_version_info.properties.new",
"urbackup/server_version_info.properties"))
{
Server->Log("Error renaming server_version_info.properties . " + os_last_error_str(), LL_ERROR);
}
}
}
}
void ServerUpdate::update_dataplan_db()
{
if (url_fak == NULL)
{
Server->Log("Urlplugin not found. Cannot download dataplan database.", LL_ERROR);
return;
}
read_update_location();
std::string http_proxy = Server->getServerParameter("http_proxy");
std::string errmsg;
Server->Log("Downloading dataplan database...", LL_INFO);
std::auto_ptr<IFile> dataplan_db(Server->openFile("urbackup/dataplan_db.txt.new", MODE_WRITE));
if (!dataplan_db.get())
{
Server->Log("Error opening urbackup/dataplan_db.txt.new for writing", LL_ERROR);
}
else
{
if (!url_fak->downloadFile(urbackup_update_url + "dataplan_db.txt",
dataplan_db.get(), http_proxy, &errmsg))
{
Server->Log("Error downloading dataplan database: " + errmsg, LL_ERROR);
}
else
{
dataplan_db.reset();
if (!os_rename_file("urbackup/dataplan_db.txt.new",
"urbackup/dataplan_db.txt"))
{
Server->Log("Error renaming urbackup/dataplan_db.txt. " + os_last_error_str(), LL_ERROR);
}
DataplanDb::getInstance()->read("urbackup/dataplan_db.txt");
}
}
}
void ServerUpdate::read_update_location()
{
std::string read_update_location = trim(getFile("urbackup/server_update_location.url"));
if (!read_update_location.empty())
{
urbackup_update_url_alt = read_update_location;
urbackup_update_url = urbackup_update_url_alt;
if (!urbackup_update_url.empty()
&& urbackup_update_url[urbackup_update_url.size() - 1] != '/')
urbackup_update_url += "/";
urbackup_update_url += "2.1.x/";
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/io/ByteBuffer.h"
using namespace db::io;
ByteBuffer::ByteBuffer(int capacity)
{
// create the byte buffer
mCapacity = capacity;
mBuffer = (capacity > 0) ? (char*)malloc(mCapacity) : NULL;
mOffset = 0;
mLength = 0;
mCleanup = true;
}
ByteBuffer::ByteBuffer(char* b, int offset, int length, bool cleanup)
{
// set the byte buffer
mCleanup = false;
ByteBuffer::setBytes(b, offset, length, cleanup);
}
ByteBuffer::ByteBuffer(const ByteBuffer& copy)
{
// copy bytes
mCapacity = copy.capacity();
mBuffer = (mCapacity > 0) ? (char*)malloc(mCapacity) : NULL;
memcpy(mBuffer, copy.bytes(), copy.capacity());
mOffset = copy.offset();
mLength = copy.length();
mCleanup = true;
}
ByteBuffer::~ByteBuffer()
{
// clean up byte buffer
cleanupBytes();
}
void ByteBuffer::cleanupBytes()
{
if(mCleanup && mBuffer != NULL)
{
::free(mBuffer);
mBuffer = NULL;
}
}
void ByteBuffer::free()
{
cleanupBytes();
mBuffer = NULL;
mCapacity = 0;
mOffset = 0;
mLength = 0;
mCleanup = true;
}
void ByteBuffer::allocateSpace(int length, bool resize)
{
if(resize)
{
// determine if the buffer needs to be resized
int overflow = length - freeSpace();
if(overflow > 0)
{
// resize the buffer by the overflow amount
this->resize(mCapacity + overflow);
}
}
// determine if the data needs to be shifted
if(mOffset > 0)
{
int overflow = length - freeSpace() + mOffset;
if(overflow > 0)
{
if(mLength > 0)
{
// shift the data in the buffer
memmove(mBuffer, data(), mLength);
}
mOffset = 0;
}
}
}
void ByteBuffer::resize(int capacity)
{
if(capacity != mCapacity)
{
// create a new buffer
char* newBuffer = (char*)malloc(capacity);
// copy the data into the new buffer, truncate old count as necessary
mCapacity = capacity;
mLength = (mCapacity < mLength) ? mCapacity : mLength;
memcpy(newBuffer, data(), mLength);
mOffset = 0;
// clean up old buffer
cleanupBytes();
// memory management now on regardless of previous setting
mBuffer = newBuffer;
mCleanup = true;
}
}
int ByteBuffer::put(unsigned char b, bool resize)
{
int rval = 0;
// allocate space for the data
allocateSpace(1, resize);
if(freeSpace() > 0)
{
// put byte into the buffer
udata()[mLength++] = b;
rval++;
}
return rval;
}
int ByteBuffer::put(const char* b, int length, bool resize)
{
// allocate space for the data
allocateSpace(length, resize);
// copy data into the buffer
length = (length < freeSpace()) ? length : freeSpace();
if(length < 10)
{
// optimized over memcpy()
for(int i = 0; i < length; i++)
{
udata()[mLength + i] = ((unsigned char*)b)[i];
}
}
else
{
memcpy(data() + mLength, b, length);
}
mLength += length;
return length;
}
int ByteBuffer::put(ByteBuffer* b, int length, bool resize)
{
length = (length < b->length()) ? length : b->length();
return put(b->bytes() + b->offset(), length, resize);
}
int ByteBuffer::put(InputStream* is)
{
int rval = 0;
// if the buffer is not full, do a read
if(!isFull())
{
// allocate free space
allocateSpace(freeSpace(), false);
// read
rval = is->read(data() + mLength, freeSpace());
if(rval != -1)
{
// increment length
mLength += rval;
}
}
return rval;
}
int ByteBuffer::get(unsigned char& b)
{
int rval = 0;
if(mLength > 0)
{
// get byte
b = udata()[0];
// move internal pointer
mOffset++;
mLength--;
rval++;
}
return rval;
}
int ByteBuffer::get(char* b, int length)
{
length = (length < mLength) ? length : mLength;
memcpy(b, data(), length);
// move internal pointer
mOffset += length;
mLength -= length;
return length;
}
int ByteBuffer::get(ByteBuffer* b, int length, bool resize)
{
// put data into passed buffer
length = (length < mLength) ? length : mLength;
int rval = b->put(data(), length, resize);
// move internal pointer and change length
mOffset += rval;
mLength -= rval;
return rval;
}
int ByteBuffer::get(OutputStream* os)
{
int rval = 0;
if(os->write(data(), mLength))
{
rval = mLength;
mOffset = mLength = 0;
}
return rval;
}
int ByteBuffer::clear(int length)
{
// ensure that the maximum cleared is existing length
int rval = (length > 0) ? ((mLength < length) ? mLength : length) : 0;
// set new length and offset
mLength -= rval;
mOffset = (mLength == 0) ? 0 : mOffset + rval;
return rval;
}
int ByteBuffer::clear()
{
return clear(mLength);
}
int ByteBuffer::reset(int length)
{
// ensure that the most the offset is moved back is the existing offset
int rval = (length > 0) ? ((mOffset < length) ? mOffset : length) : 0;
// set new offset and length
mOffset -= rval;
mLength += rval;
return rval;
}
int ByteBuffer::trim(int length)
{
// ensure that the maximum trimmed is existing length
int rval = (length > 0) ? ((mLength < length) ? mLength : length) : 0;
// set new length
mLength -= rval;
return rval;
}
int ByteBuffer::extend(int length)
{
// ensure that the maximum extended is (free space - offset)
int max = freeSpace() - mOffset;
int rval = (length > 0) ? ((max < length) ? max : length) : 0;
// set new length
mLength += rval;
return rval;
}
unsigned char ByteBuffer::next()
{
mLength--;
mOffset++;
return (udata() - 1)[0];
}
int ByteBuffer::capacity() const
{
return mCapacity;
}
void ByteBuffer::setBytes(ByteBuffer* b, bool cleanup)
{
// set the byte buffer
setBytes(b->bytes(), b->offset(), b->length(), cleanup);
}
void ByteBuffer::setBytes(char* b, int offset, int length, bool cleanup)
{
// cleanup old buffer
cleanupBytes();
mCapacity = length;
mBuffer = b;
mOffset = offset;
mLength = length;
mCleanup = cleanup;
}
inline char* ByteBuffer::bytes() const
{
return mBuffer;
}
inline char* ByteBuffer::data() const
{
return mBuffer + mOffset;
}
inline unsigned char* ByteBuffer::udata() const
{
return (unsigned char*)(mBuffer + mOffset);
}
inline int ByteBuffer::offset() const
{
return mOffset;
}
inline int ByteBuffer::length() const
{
return mLength;
}
inline int ByteBuffer::freeSpace() const
{
return mCapacity - mLength;
}
inline bool ByteBuffer::isFull() const
{
return freeSpace() == 0;
}
inline bool ByteBuffer::isEmpty() const
{
return mLength == 0;
}
inline bool ByteBuffer::isManaged() const
{
return mCleanup;
}
<commit_msg>Added optimization to reallocate existing bytes if ByteBuffer is resized.<commit_after>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/io/ByteBuffer.h"
using namespace db::io;
ByteBuffer::ByteBuffer(int capacity)
{
// create the byte buffer
mCapacity = capacity;
mBuffer = (capacity > 0) ? (char*)malloc(mCapacity) : NULL;
mOffset = 0;
mLength = 0;
mCleanup = true;
}
ByteBuffer::ByteBuffer(char* b, int offset, int length, bool cleanup)
{
// set the byte buffer
mCleanup = false;
ByteBuffer::setBytes(b, offset, length, cleanup);
}
ByteBuffer::ByteBuffer(const ByteBuffer& copy)
{
// copy bytes
mCapacity = copy.capacity();
mBuffer = (mCapacity > 0) ? (char*)malloc(mCapacity) : NULL;
memcpy(mBuffer, copy.bytes(), copy.capacity());
mOffset = copy.offset();
mLength = copy.length();
mCleanup = true;
}
ByteBuffer::~ByteBuffer()
{
// clean up byte buffer
cleanupBytes();
}
void ByteBuffer::cleanupBytes()
{
if(mCleanup && mBuffer != NULL)
{
::free(mBuffer);
mBuffer = NULL;
}
}
void ByteBuffer::free()
{
cleanupBytes();
mBuffer = NULL;
mCapacity = 0;
mOffset = 0;
mLength = 0;
mCleanup = true;
}
void ByteBuffer::allocateSpace(int length, bool resize)
{
if(resize)
{
// determine if the buffer needs to be resized
int overflow = length - freeSpace();
if(overflow > 0)
{
// resize the buffer by the overflow amount
this->resize(mCapacity + overflow);
}
}
// determine if the data needs to be shifted
if(mOffset > 0)
{
int overflow = length - freeSpace() + mOffset;
if(overflow > 0)
{
if(mLength > 0)
{
// shift the data in the buffer
memmove(mBuffer, data(), mLength);
}
mOffset = 0;
}
}
}
void ByteBuffer::resize(int capacity)
{
if(capacity != mCapacity)
{
if(mCleanup && mBuffer != NULL)
{
// reallocate buffer
mBuffer = (char*)realloc(mBuffer, capacity);
mCapacity = capacity;
mLength = (mCapacity < mLength) ? mCapacity : mLength;
}
else
{
// create a new buffer
char* newBuffer = (char*)malloc(capacity);
// copy the data into the new buffer, truncate old count as necessary
mCapacity = capacity;
mLength = (mCapacity < mLength) ? mCapacity : mLength;
memcpy(newBuffer, data(), mLength);
mOffset = 0;
// clean up old buffer
cleanupBytes();
// memory management now on regardless of previous setting
mBuffer = newBuffer;
mCleanup = true;
}
}
}
int ByteBuffer::put(unsigned char b, bool resize)
{
int rval = 0;
// allocate space for the data
allocateSpace(1, resize);
if(freeSpace() > 0)
{
// put byte into the buffer
udata()[mLength++] = b;
rval++;
}
return rval;
}
int ByteBuffer::put(const char* b, int length, bool resize)
{
// allocate space for the data
allocateSpace(length, resize);
// copy data into the buffer
length = (length < freeSpace()) ? length : freeSpace();
if(length < 10)
{
// optimized over memcpy()
for(int i = 0; i < length; i++)
{
udata()[mLength + i] = ((unsigned char*)b)[i];
}
}
else
{
memcpy(data() + mLength, b, length);
}
mLength += length;
return length;
}
int ByteBuffer::put(ByteBuffer* b, int length, bool resize)
{
length = (length < b->length()) ? length : b->length();
return put(b->bytes() + b->offset(), length, resize);
}
int ByteBuffer::put(InputStream* is)
{
int rval = 0;
// if the buffer is not full, do a read
if(!isFull())
{
// allocate free space
allocateSpace(freeSpace(), false);
// read
rval = is->read(data() + mLength, freeSpace());
if(rval != -1)
{
// increment length
mLength += rval;
}
}
return rval;
}
int ByteBuffer::get(unsigned char& b)
{
int rval = 0;
if(mLength > 0)
{
// get byte
b = udata()[0];
// move internal pointer
mOffset++;
mLength--;
rval++;
}
return rval;
}
int ByteBuffer::get(char* b, int length)
{
length = (length < mLength) ? length : mLength;
memcpy(b, data(), length);
// move internal pointer
mOffset += length;
mLength -= length;
return length;
}
int ByteBuffer::get(ByteBuffer* b, int length, bool resize)
{
// put data into passed buffer
length = (length < mLength) ? length : mLength;
int rval = b->put(data(), length, resize);
// move internal pointer and change length
mOffset += rval;
mLength -= rval;
return rval;
}
int ByteBuffer::get(OutputStream* os)
{
int rval = 0;
if(os->write(data(), mLength))
{
rval = mLength;
mOffset = mLength = 0;
}
return rval;
}
int ByteBuffer::clear(int length)
{
// ensure that the maximum cleared is existing length
int rval = (length > 0) ? ((mLength < length) ? mLength : length) : 0;
// set new length and offset
mLength -= rval;
mOffset = (mLength == 0) ? 0 : mOffset + rval;
return rval;
}
int ByteBuffer::clear()
{
return clear(mLength);
}
int ByteBuffer::reset(int length)
{
// ensure that the most the offset is moved back is the existing offset
int rval = (length > 0) ? ((mOffset < length) ? mOffset : length) : 0;
// set new offset and length
mOffset -= rval;
mLength += rval;
return rval;
}
int ByteBuffer::trim(int length)
{
// ensure that the maximum trimmed is existing length
int rval = (length > 0) ? ((mLength < length) ? mLength : length) : 0;
// set new length
mLength -= rval;
return rval;
}
int ByteBuffer::extend(int length)
{
// ensure that the maximum extended is (free space - offset)
int max = freeSpace() - mOffset;
int rval = (length > 0) ? ((max < length) ? max : length) : 0;
// set new length
mLength += rval;
return rval;
}
unsigned char ByteBuffer::next()
{
mLength--;
mOffset++;
return (udata() - 1)[0];
}
int ByteBuffer::capacity() const
{
return mCapacity;
}
void ByteBuffer::setBytes(ByteBuffer* b, bool cleanup)
{
// set the byte buffer
setBytes(b->bytes(), b->offset(), b->length(), cleanup);
}
void ByteBuffer::setBytes(char* b, int offset, int length, bool cleanup)
{
// cleanup old buffer
cleanupBytes();
mCapacity = length;
mBuffer = b;
mOffset = offset;
mLength = length;
mCleanup = cleanup;
}
inline char* ByteBuffer::bytes() const
{
return mBuffer;
}
inline char* ByteBuffer::data() const
{
return mBuffer + mOffset;
}
inline unsigned char* ByteBuffer::udata() const
{
return (unsigned char*)(mBuffer + mOffset);
}
inline int ByteBuffer::offset() const
{
return mOffset;
}
inline int ByteBuffer::length() const
{
return mLength;
}
inline int ByteBuffer::freeSpace() const
{
return mCapacity - mLength;
}
inline bool ByteBuffer::isFull() const
{
return freeSpace() == 0;
}
inline bool ByteBuffer::isEmpty() const
{
return mLength == 0;
}
inline bool ByteBuffer::isManaged() const
{
return mCleanup;
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RIoUring
#define ROOT_RIoUring
#include <liburing.h>
#include <liburing/io_uring.h>
#include <ROOT/RError.hxx>
using ROOT::Experimental::RException;
namespace ROOT {
namespace Internal {
class RIoUring {
private:
struct io_uring fRing;
public:
explicit RIoUring(size_t size) {
int ret = io_uring_queue_init(size, &fRing, 0 /* no flags */);
if (ret) {
throw RException(R__FAIL("couldn't open ring"));
}
}
RIoUring(const RIoUring&) = delete;
RIoUring& operator=(const RIoUring&) = delete;
~RIoUring() {
io_uring_queue_exit(&fRing);
}
/// Check if io_uring is available on this system.
static bool IsAvailable() {
try {
RIoUring(1);
} catch (const RException&) {
return false;
}
return true;
}
};
} // namespace Internal
} // namespace ROOT
#endif
<commit_msg>[io] use thread_locals to cache io_uring IsAvailable result<commit_after>/*************************************************************************
* Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RIoUring
#define ROOT_RIoUring
#include <liburing.h>
#include <liburing/io_uring.h>
#include <ROOT/RError.hxx>
using ROOT::Experimental::RException;
namespace ROOT {
namespace Internal {
class RIoUring {
private:
struct io_uring fRing;
public:
explicit RIoUring(size_t size) {
int ret = io_uring_queue_init(size, &fRing, 0 /* no flags */);
if (ret) {
throw RException(R__FAIL("couldn't open ring"));
}
}
RIoUring(const RIoUring&) = delete;
RIoUring& operator=(const RIoUring&) = delete;
~RIoUring() {
io_uring_queue_exit(&fRing);
}
/// Check if io_uring is available on this system.
static bool IsAvailable() {
thread_local bool couldOpenRing = false;
thread_local bool firstPass = true;
if (firstPass) {
firstPass = false;
try {
RIoUring(1);
couldOpenRing = true;
}
catch (const RException&) {
// ring setup failed
}
}
return couldOpenRing;
}
};
} // namespace Internal
} // namespace ROOT
#endif
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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 "SurgSim/Input/InputComponent.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Input/InputConsumerInterface.h"
#include "SurgSim/Framework/LockedContainer.h"
namespace SurgSim
{
namespace Input
{
/// An input consumer monitors device and signal state update
class InputConsumer: public InputConsumerInterface
{
public:
/// Constructor
InputConsumer()
{
}
/// Destructor
virtual ~InputConsumer()
{
}
/// Handle the input coming from device.
/// \param device The name of the device that is producing the input.
/// \param inputData The input data coming from the device.
virtual void handleInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) override
{
m_lastInput.set(inputData);
}
/// Initialize the input data information stored in this input consumer.
/// \param device The name of the device that is producing the input.
/// \param initialData Initial input data of the device.
virtual void initializeInput(const std::string& device,
const SurgSim::DataStructures::DataGroup& initialData) override
{
m_lastInput.set(initialData);
}
/// Retrieve input data information stored in this input consumer
/// \param [out] dataGroup Used to accept the retrieved input data information
void getData(SurgSim::DataStructures::DataGroup* dataGroup)
{
m_lastInput.get(dataGroup);
}
private:
/// Used to store input data information passed in from device
SurgSim::Framework::LockedContainer<SurgSim::DataStructures::DataGroup> m_lastInput;
};
InputComponent::InputComponent(const std::string& name) :
Component(name),
m_deviceName(),
m_deviceConnected(false),
m_input(std::make_shared<InputConsumer>())
{
}
InputComponent::~InputComponent()
{
}
void InputComponent::setDeviceName(const std::string& deviceName)
{
m_deviceName = deviceName;
}
bool InputComponent::isDeviceConnected()
{
return m_deviceConnected;
}
void InputComponent::getData(SurgSim::DataStructures::DataGroup* dataGroup)
{
SURGSIM_ASSERT(m_deviceConnected) << "No device connected to " << getName() << ". Unable to getData.";
m_input->getData(dataGroup);
}
bool InputComponent::doInitialize()
{
return true;
}
bool InputComponent::doWakeUp()
{
return true;
}
std::string InputComponent::getDeviceName() const
{
return m_deviceName;
}
void InputComponent::connectDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device)
{
device->addInputConsumer(m_input);
m_deviceConnected = true;
}
void InputComponent::disconnectDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device)
{
device->removeInputConsumer(m_input);
m_deviceConnected = false;
}
}; // namespace Input
}; // namespace SurgSim
<commit_msg>InputComponent requires input device on wakeup.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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 "SurgSim/Input/InputComponent.h"
#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Input/InputConsumerInterface.h"
#include "SurgSim/Framework/LockedContainer.h"
namespace SurgSim
{
namespace Input
{
/// An input consumer monitors device and signal state update
class InputConsumer: public InputConsumerInterface
{
public:
/// Constructor
InputConsumer()
{
}
/// Destructor
virtual ~InputConsumer()
{
}
/// Handle the input coming from device.
/// \param device The name of the device that is producing the input.
/// \param inputData The input data coming from the device.
virtual void handleInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) override
{
m_lastInput.set(inputData);
}
/// Initialize the input data information stored in this input consumer.
/// \param device The name of the device that is producing the input.
/// \param initialData Initial input data of the device.
virtual void initializeInput(const std::string& device,
const SurgSim::DataStructures::DataGroup& initialData) override
{
m_lastInput.set(initialData);
}
/// Retrieve input data information stored in this input consumer
/// \param [out] dataGroup Used to accept the retrieved input data information
void getData(SurgSim::DataStructures::DataGroup* dataGroup)
{
m_lastInput.get(dataGroup);
}
private:
/// Used to store input data information passed in from device
SurgSim::Framework::LockedContainer<SurgSim::DataStructures::DataGroup> m_lastInput;
};
InputComponent::InputComponent(const std::string& name) :
Component(name),
m_deviceName(),
m_deviceConnected(false),
m_input(std::make_shared<InputConsumer>())
{
}
InputComponent::~InputComponent()
{
}
void InputComponent::setDeviceName(const std::string& deviceName)
{
m_deviceName = deviceName;
}
bool InputComponent::isDeviceConnected()
{
return m_deviceConnected;
}
void InputComponent::getData(SurgSim::DataStructures::DataGroup* dataGroup)
{
m_input->getData(dataGroup);
}
bool InputComponent::doInitialize()
{
return true;
}
bool InputComponent::doWakeUp()
{
bool result = true;
if (!m_deviceConnected)
{
SURGSIM_LOG_CRITICAL(SurgSim::Framework::Logger::getDefaultLogger()) <<
"No device connected to " << getName() << "...failed to wake up.";
}
return result;
}
std::string InputComponent::getDeviceName() const
{
return m_deviceName;
}
void InputComponent::connectDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device)
{
device->addInputConsumer(m_input);
m_deviceConnected = true;
}
void InputComponent::disconnectDevice(std::shared_ptr<SurgSim::Input::DeviceInterface> device)
{
device->removeInputConsumer(m_input);
m_deviceConnected = false;
}
}; // namespace Input
}; // namespace SurgSim
<|endoftext|> |
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MissionControllerTest.h"
#include "LinkManager.h"
#include "MultiVehicleManager.h"
#include "SimpleMissionItem.h"
#include "MissionSettingsItem.h"
#include "QGCApplication.h"
#include "SettingsManager.h"
#include "AppSettings.h"
MissionControllerTest::MissionControllerTest(void)
: _multiSpyMissionController(NULL)
, _multiSpyMissionItem(NULL)
, _missionController(NULL)
{
}
void MissionControllerTest::cleanup(void)
{
delete _masterController;
_masterController = NULL;
delete _multiSpyMissionController;
_multiSpyMissionController = NULL;
delete _multiSpyMissionItem;
_multiSpyMissionItem = NULL;
MissionControllerManagerTest::cleanup();
}
void MissionControllerTest::_initForFirmwareType(MAV_AUTOPILOT firmwareType)
{
MissionControllerManagerTest::_initForFirmwareType(firmwareType);
// VisualMissionItem signals
_rgVisualItemSignals[coordinateChangedSignalIndex] = SIGNAL(coordinateChanged(const QGeoCoordinate&));
// MissionController signals
_rgMissionControllerSignals[visualItemsChangedSignalIndex] = SIGNAL(visualItemsChanged());
_rgMissionControllerSignals[waypointLinesChangedSignalIndex] = SIGNAL(waypointLinesChanged());
// Master controller pulls offline vehicle info from settings
qgcApp()->toolbox()->settingsManager()->appSettings()->offlineEditingFirmwareType()->setRawValue(firmwareType);
_masterController = new PlanMasterController(this);
_missionController = _masterController->missionController();
_multiSpyMissionController = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpyMissionController);
QCOMPARE(_multiSpyMissionController->init(_missionController, _rgMissionControllerSignals, _cMissionControllerSignals), true);
_masterController->start(false /* flyView */);
// All signals should some through on start
QCOMPARE(_multiSpyMissionController->checkOnlySignalsByMask(visualItemsChangedSignalMask | waypointLinesChangedSignalMask), true);
_multiSpyMissionController->clearAllSignals();
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
// Empty vehicle only has home position
QCOMPARE(visualItems->count(), 1);
// Mission Settings should be in first slot
MissionSettingsItem* settingsItem = visualItems->value<MissionSettingsItem*>(0);
QVERIFY(settingsItem);
// Offline vehicle, so no home position
QCOMPARE(settingsItem->coordinate().isValid(), false);
// Empty mission, so no child items possible
QCOMPARE(settingsItem->childItems()->count(), 0);
// No waypoint lines
QmlObjectListModel* waypointLines = _missionController->waypointLines();
QVERIFY(waypointLines);
QCOMPARE(waypointLines->count(), 0);
}
void MissionControllerTest::_testEmptyVehicleWorker(MAV_AUTOPILOT firmwareType)
{
_initForFirmwareType(firmwareType);
// FYI: A significant amount of empty vehicle testing is in _initForFirmwareType since that
// sets up an empty vehicle
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
VisualMissionItem* visualItem = visualItems->value<VisualMissionItem*>(0);
QVERIFY(visualItem);
_setupVisualItemSignals(visualItem);
}
void MissionControllerTest::_testEmptyVehiclePX4(void)
{
_testEmptyVehicleWorker(MAV_AUTOPILOT_PX4);
}
void MissionControllerTest::_testEmptyVehicleAPM(void)
{
_testEmptyVehicleWorker(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
void MissionControllerTest::_testAddWaypointWorker(MAV_AUTOPILOT firmwareType)
{
_initForFirmwareType(firmwareType);
QGeoCoordinate coordinate(37.803784, -122.462276);
_missionController->insertSimpleMissionItem(coordinate, _missionController->visualItems()->count());
QCOMPARE(_multiSpyMissionController->checkOnlySignalsByMask(waypointLinesChangedSignalMask), true);
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
QCOMPARE(visualItems->count(), 2);
MissionSettingsItem* settingsItem = visualItems->value<MissionSettingsItem*>(0);
SimpleMissionItem* simpleItem = visualItems->value<SimpleMissionItem*>(1);
QVERIFY(settingsItem);
QVERIFY(simpleItem);
QCOMPARE((MAV_CMD)simpleItem->command(), MAV_CMD_NAV_TAKEOFF);
QCOMPARE(simpleItem->childItems()->count(), 0);
// If the first item added specifies a coordinate, then planned home position will be set
bool plannedHomePositionValue = firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA ? false : true;
QCOMPARE(settingsItem->coordinate().isValid(), plannedHomePositionValue);
// ArduPilot takeoff command has no coordinate, so should be child item
QCOMPARE(settingsItem->childItems()->count(), firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA ? 1 : 0);
// Check waypoint line from home to takeoff
int expectedLineCount = firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA ? 0 : 1;
QmlObjectListModel* waypointLines = _missionController->waypointLines();
QVERIFY(waypointLines);
QCOMPARE(waypointLines->count(), expectedLineCount);
}
void MissionControllerTest::_testAddWayppointAPM(void)
{
_testAddWaypointWorker(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
void MissionControllerTest::_testAddWayppointPX4(void)
{
_testAddWaypointWorker(MAV_AUTOPILOT_PX4);
}
#if 0
void MissionControllerTest::_testOfflineToOnlineWorker(MAV_AUTOPILOT firmwareType)
{
// Start offline and add item
_missionController = new MissionController();
Q_CHECK_PTR(_missionController);
_missionController->start(false /* flyView */);
_missionController->insertSimpleMissionItem(QGeoCoordinate(37.803784, -122.462276), _missionController->visualItems()->count());
// Go online to empty vehicle
MissionControllerManagerTest::_initForFirmwareType(firmwareType);
#if 1
// Due to current limitations, offline items will go away
QCOMPARE(_missionController->visualItems()->count(), 1);
#else
//Make sure our offline mission items are still there
QCOMPARE(_missionController->visualItems()->count(), 2);
#endif
}
void MissionControllerTest::_testOfflineToOnlineAPM(void)
{
_testOfflineToOnlineWorker(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
void MissionControllerTest::_testOfflineToOnlinePX4(void)
{
_testOfflineToOnlineWorker(MAV_AUTOPILOT_PX4);
}
#endif
void MissionControllerTest::_setupVisualItemSignals(VisualMissionItem* visualItem)
{
delete _multiSpyMissionItem;
_multiSpyMissionItem = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpyMissionItem);
QCOMPARE(_multiSpyMissionItem->init(visualItem, _rgVisualItemSignals, _cVisualItemSignals), true);
}
void MissionControllerTest::_testGimbalRecalc(void)
{
_initForFirmwareType(MAV_AUTOPILOT_PX4);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 1);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 2);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 3);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 4);
// No specific gimbal yaw set yet
for (int i=1; i<_missionController->visualItems()->count(); i++) {
VisualMissionItem* visualItem = _missionController->visualItems()->value<VisualMissionItem*>(i);
QVERIFY(qIsNaN(visualItem->missionGimbalYaw()));
}
// Specify gimbal yaw on settings item should generate yaw on all items
MissionSettingsItem* settingsItem = _missionController->visualItems()->value<MissionSettingsItem*>(0);
settingsItem->cameraSection()->setSpecifyGimbal(true);
settingsItem->cameraSection()->gimbalYaw()->setRawValue(0.0);
for (int i=1; i<_missionController->visualItems()->count(); i++) {
VisualMissionItem* visualItem = _missionController->visualItems()->value<VisualMissionItem*>(i);
QCOMPARE(visualItem->missionGimbalYaw(), 0.0);
}
}
void MissionControllerTest::_testLoadJsonSectionAvailable(void)
{
_initForFirmwareType(MAV_AUTOPILOT_PX4);
_masterController->loadFromFile(":/unittest/SectionTest.plan");
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
QCOMPARE(visualItems->count(), 5);
// Check that only waypoint items have camera and speed sections
for (int i=1; i<visualItems->count(); i++) {
SimpleMissionItem* item = visualItems->value<SimpleMissionItem*>(i);
QVERIFY(item);
if ((int)item->command() == MAV_CMD_NAV_WAYPOINT) {
QCOMPARE(item->cameraSection()->available(), true);
QCOMPARE(item->speedSection()->available(), true);
} else {
QCOMPARE(item->cameraSection()->available(), false);
QCOMPARE(item->speedSection()->available(), false);
}
}
}
<commit_msg><commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MissionControllerTest.h"
#include "LinkManager.h"
#include "MultiVehicleManager.h"
#include "SimpleMissionItem.h"
#include "MissionSettingsItem.h"
#include "QGCApplication.h"
#include "SettingsManager.h"
#include "AppSettings.h"
MissionControllerTest::MissionControllerTest(void)
: _multiSpyMissionController(NULL)
, _multiSpyMissionItem(NULL)
, _missionController(NULL)
{
}
void MissionControllerTest::cleanup(void)
{
delete _masterController;
_masterController = NULL;
delete _multiSpyMissionController;
_multiSpyMissionController = NULL;
delete _multiSpyMissionItem;
_multiSpyMissionItem = NULL;
MissionControllerManagerTest::cleanup();
}
void MissionControllerTest::_initForFirmwareType(MAV_AUTOPILOT firmwareType)
{
MissionControllerManagerTest::_initForFirmwareType(firmwareType);
// VisualMissionItem signals
_rgVisualItemSignals[coordinateChangedSignalIndex] = SIGNAL(coordinateChanged(const QGeoCoordinate&));
// MissionController signals
_rgMissionControllerSignals[visualItemsChangedSignalIndex] = SIGNAL(visualItemsChanged());
_rgMissionControllerSignals[waypointLinesChangedSignalIndex] = SIGNAL(waypointLinesChanged());
// Master controller pulls offline vehicle info from settings
qgcApp()->toolbox()->settingsManager()->appSettings()->offlineEditingFirmwareType()->setRawValue(firmwareType);
_masterController = new PlanMasterController(this);
_missionController = _masterController->missionController();
_multiSpyMissionController = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpyMissionController);
QCOMPARE(_multiSpyMissionController->init(_missionController, _rgMissionControllerSignals, _cMissionControllerSignals), true);
_masterController->start(false /* flyView */);
// All signals should some through on start
QCOMPARE(_multiSpyMissionController->checkOnlySignalsByMask(visualItemsChangedSignalMask | waypointLinesChangedSignalMask), true);
_multiSpyMissionController->clearAllSignals();
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
// Empty vehicle only has home position
QCOMPARE(visualItems->count(), 1);
// Mission Settings should be in first slot
MissionSettingsItem* settingsItem = visualItems->value<MissionSettingsItem*>(0);
QVERIFY(settingsItem);
// Offline vehicle, so no home position
QCOMPARE(settingsItem->coordinate().isValid(), false);
// Empty mission, so no child items possible
QCOMPARE(settingsItem->childItems()->count(), 0);
// No waypoint lines
QmlObjectListModel* waypointLines = _missionController->waypointLines();
QVERIFY(waypointLines);
QCOMPARE(waypointLines->count(), 0);
}
void MissionControllerTest::_testEmptyVehicleWorker(MAV_AUTOPILOT firmwareType)
{
_initForFirmwareType(firmwareType);
// FYI: A significant amount of empty vehicle testing is in _initForFirmwareType since that
// sets up an empty vehicle
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
VisualMissionItem* visualItem = visualItems->value<VisualMissionItem*>(0);
QVERIFY(visualItem);
_setupVisualItemSignals(visualItem);
}
void MissionControllerTest::_testEmptyVehiclePX4(void)
{
_testEmptyVehicleWorker(MAV_AUTOPILOT_PX4);
}
void MissionControllerTest::_testEmptyVehicleAPM(void)
{
_testEmptyVehicleWorker(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
void MissionControllerTest::_testAddWaypointWorker(MAV_AUTOPILOT firmwareType)
{
_initForFirmwareType(firmwareType);
QGeoCoordinate coordinate(37.803784, -122.462276);
_missionController->insertSimpleMissionItem(coordinate, _missionController->visualItems()->count());
QCOMPARE(_multiSpyMissionController->checkOnlySignalsByMask(waypointLinesChangedSignalMask), true);
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
QCOMPARE(visualItems->count(), 2);
MissionSettingsItem* settingsItem = visualItems->value<MissionSettingsItem*>(0);
SimpleMissionItem* simpleItem = visualItems->value<SimpleMissionItem*>(1);
QVERIFY(settingsItem);
QVERIFY(simpleItem);
QCOMPARE((MAV_CMD)simpleItem->command(), MAV_CMD_NAV_TAKEOFF);
QCOMPARE(simpleItem->childItems()->count(), 0);
// Planned home position should always be set after first item
QVERIFY(settingsItem->coordinate().isValid());
// ArduPilot takeoff command has no coordinate, so should be child item
QCOMPARE(settingsItem->childItems()->count(), firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA ? 1 : 0);
// Check waypoint line from home to takeoff
int expectedLineCount = firmwareType == MAV_AUTOPILOT_ARDUPILOTMEGA ? 0 : 1;
QmlObjectListModel* waypointLines = _missionController->waypointLines();
QVERIFY(waypointLines);
QCOMPARE(waypointLines->count(), expectedLineCount);
}
void MissionControllerTest::_testAddWayppointAPM(void)
{
_testAddWaypointWorker(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
void MissionControllerTest::_testAddWayppointPX4(void)
{
_testAddWaypointWorker(MAV_AUTOPILOT_PX4);
}
#if 0
void MissionControllerTest::_testOfflineToOnlineWorker(MAV_AUTOPILOT firmwareType)
{
// Start offline and add item
_missionController = new MissionController();
Q_CHECK_PTR(_missionController);
_missionController->start(false /* flyView */);
_missionController->insertSimpleMissionItem(QGeoCoordinate(37.803784, -122.462276), _missionController->visualItems()->count());
// Go online to empty vehicle
MissionControllerManagerTest::_initForFirmwareType(firmwareType);
#if 1
// Due to current limitations, offline items will go away
QCOMPARE(_missionController->visualItems()->count(), 1);
#else
//Make sure our offline mission items are still there
QCOMPARE(_missionController->visualItems()->count(), 2);
#endif
}
void MissionControllerTest::_testOfflineToOnlineAPM(void)
{
_testOfflineToOnlineWorker(MAV_AUTOPILOT_ARDUPILOTMEGA);
}
void MissionControllerTest::_testOfflineToOnlinePX4(void)
{
_testOfflineToOnlineWorker(MAV_AUTOPILOT_PX4);
}
#endif
void MissionControllerTest::_setupVisualItemSignals(VisualMissionItem* visualItem)
{
delete _multiSpyMissionItem;
_multiSpyMissionItem = new MultiSignalSpy();
Q_CHECK_PTR(_multiSpyMissionItem);
QCOMPARE(_multiSpyMissionItem->init(visualItem, _rgVisualItemSignals, _cVisualItemSignals), true);
}
void MissionControllerTest::_testGimbalRecalc(void)
{
_initForFirmwareType(MAV_AUTOPILOT_PX4);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 1);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 2);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 3);
_missionController->insertSimpleMissionItem(QGeoCoordinate(0, 0), 4);
// No specific gimbal yaw set yet
for (int i=1; i<_missionController->visualItems()->count(); i++) {
VisualMissionItem* visualItem = _missionController->visualItems()->value<VisualMissionItem*>(i);
QVERIFY(qIsNaN(visualItem->missionGimbalYaw()));
}
// Specify gimbal yaw on settings item should generate yaw on all items
MissionSettingsItem* settingsItem = _missionController->visualItems()->value<MissionSettingsItem*>(0);
settingsItem->cameraSection()->setSpecifyGimbal(true);
settingsItem->cameraSection()->gimbalYaw()->setRawValue(0.0);
for (int i=1; i<_missionController->visualItems()->count(); i++) {
VisualMissionItem* visualItem = _missionController->visualItems()->value<VisualMissionItem*>(i);
QCOMPARE(visualItem->missionGimbalYaw(), 0.0);
}
}
void MissionControllerTest::_testLoadJsonSectionAvailable(void)
{
_initForFirmwareType(MAV_AUTOPILOT_PX4);
_masterController->loadFromFile(":/unittest/SectionTest.plan");
QmlObjectListModel* visualItems = _missionController->visualItems();
QVERIFY(visualItems);
QCOMPARE(visualItems->count(), 5);
// Check that only waypoint items have camera and speed sections
for (int i=1; i<visualItems->count(); i++) {
SimpleMissionItem* item = visualItems->value<SimpleMissionItem*>(i);
QVERIFY(item);
if ((int)item->command() == MAV_CMD_NAV_WAYPOINT) {
QCOMPARE(item->cameraSection()->available(), true);
QCOMPARE(item->speedSection()->available(), true);
} else {
QCOMPARE(item->cameraSection()->available(), false);
QCOMPARE(item->speedSection()->available(), false);
}
}
}
<|endoftext|> |
<commit_before>#include "xchainer/backprop.h"
#include <vector>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#include <gtest/gtest.h>
#include "xchainer/array.h"
#include "xchainer/backprop.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/shape.h"
namespace xchainer {
namespace {
std::vector<Array> MakeFullArrays(const Shape& shape, const std::vector<float>& values, bool requires_grad) {
std::vector<Array> ret;
for (float value : values) {
ret.push_back(Array::Full(shape, value));
ret.back().set_requires_grad(requires_grad);
}
return ret;
}
class BackpropTest : public ::testing::TestWithParam<::testing::tuple<std::string>> {
protected:
virtual void SetUp() {
std::string device_name = ::testing::get<0>(GetParam());
device_scope_ = std::make_unique<DeviceScope>(device_name);
}
virtual void TearDown() { device_scope_.reset(); }
public:
template <typename T>
void ExpectEqual(const Array& expected, const Array& actual) const {
EXPECT_EQ(expected.dtype(), actual.dtype());
EXPECT_EQ(expected.shape(), actual.shape());
ExpectDataEqual<T>(expected, actual);
}
template <typename T>
void ExpectDataEqual(const Array& expected, const Array& actual) const {
#ifdef XCHAINER_ENABLE_CUDA
std::string device_name = ::testing::get<0>(GetParam());
if (device_name == "cuda") {
cuda::CheckError(cudaDeviceSynchronize());
}
#endif // XCHAINER_ENABLE_CUDA
auto total_size = expected.shape().total_size();
const T* expected_data = static_cast<const T*>(expected.data().get());
const T* actual_data = static_cast<const T*>(actual.data().get());
for (decltype(total_size) i = 0; i < total_size; i++) {
EXPECT_EQ(expected_data[i], actual_data[i]);
}
}
// Checks the correctness of Backward() applied to the output of a given function.
// Gradients are only computed w.r.t. target_inputs, and are compared to expected_grads.
template <typename Fprop, typename... Args>
void CheckBackpropImpl(std::vector<Array>& target_inputs, std::vector<Array>& expected_grads, Fprop&& fprop, Args&&... args) const {
ASSERT_EQ(expected_grads.size(), target_inputs.size());
auto y = fprop(target_inputs, args...);
Backward(y);
for (size_t i = 0; i < expected_grads.size(); ++i) {
ExpectEqual<float>(expected_grads[i], *target_inputs[i].grad());
}
}
template <typename Fprop>
void CheckBackprop(std::vector<Array>& target_inputs, std::vector<Array>& expected_grads, Fprop&& fprop) const {
CheckBackpropImpl(target_inputs, expected_grads, fprop);
}
template <typename Fprop>
void CheckBackprop(std::vector<Array>& target_inputs, std::vector<Array>& other_inputs, std::vector<Array>& expected_grads,
Fprop&& fprop) const {
CheckBackpropImpl(target_inputs, expected_grads, fprop, other_inputs);
for (size_t i = 0; i < other_inputs.size(); ++i) {
EXPECT_FALSE(other_inputs[i].grad());
}
}
// Simple versions. It makes and uses an array with one element for each input.
template <typename Fprop>
void CheckBackprop(std::vector<float> target_inputs, std::vector<float> expected_grads, Fprop&& fprop) const {
auto xs = MakeFullArrays({1}, target_inputs, true);
auto expected_gxs = MakeFullArrays({1}, expected_grads, false);
CheckBackprop(xs, expected_gxs, std::forward<Fprop>(fprop));
}
template <typename Fprop>
void CheckBackprop(std::vector<float> target_inputs, std::vector<float> other_inputs, std::vector<float> expected_grads,
Fprop&& fprop) const {
auto xs = MakeFullArrays({1}, target_inputs, true);
auto other_xs = MakeFullArrays({1}, other_inputs, false);
auto expected_gxs = MakeFullArrays({1}, expected_grads, false);
CheckBackprop(xs, other_xs, expected_gxs, std::forward<Fprop>(fprop));
}
private:
std::unique_ptr<DeviceScope> device_scope_;
};
TEST_P(BackpropTest, Backward) {
CheckBackprop({2.0f, 3.0f}, {4.0f}, {3.0f, 6.0f}, [](auto& xs, auto& ys) { return xs[1] * (xs[0] + ys[0]); });
}
TEST_P(BackpropTest, DoubleBackprop) {
auto fprop = [](auto& xs, auto& ys) {
auto z = xs[0] * (xs[0] + ys[0]);
Backward(z);
auto gx = *xs[0].grad();
xs[0].ClearGrad();
return gx;
};
CheckBackprop({2.0f}, {3.0f}, {2.0f}, fprop);
}
TEST_P(BackpropTest, BackwardInputToMultipleOps) {
CheckBackprop({2.0f}, {3.0f}, {7.0f}, [](auto& xs, auto& ys) { return xs[0] * (xs[0] + ys[0]); });
}
TEST_P(BackpropTest, BackwardIdenticalInputs) {
CheckBackprop({2.0f}, {2.0f}, [](auto& xs) { return xs[0] + xs[0]; });
}
TEST_P(BackpropTest, BackwardGivenInputGrad) {
auto fprop = [](auto& xs) {
xs[0].set_grad(Array::OnesLike(xs[0]));
return xs[0];
};
CheckBackprop({1.0f}, {2.0f}, fprop);
}
TEST_P(BackpropTest, BackwardGivenOutputGrad) {
auto fprop = [](auto& xs, auto& ys) {
auto z = xs[0] * ys[0];
z.set_grad(Array::FullLike(z, 2.0f));
return z;
};
CheckBackprop({2.0f}, {3.0f}, {6.0f}, fprop);
}
INSTANTIATE_TEST_CASE_P(ForEachDevice, BackpropTest, ::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
std::string{"cuda"},
#endif // XCHAINER_ENABLE_CUDA
std::string{"cpu"}));
} // namespace
} // namespace xchainer
<commit_msg>Add test to backward sole array node<commit_after>#include "xchainer/backprop.h"
#include <vector>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#include <gtest/gtest.h>
#include "xchainer/array.h"
#include "xchainer/backprop.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/shape.h"
namespace xchainer {
namespace {
std::vector<Array> MakeFullArrays(const Shape& shape, const std::vector<float>& values, bool requires_grad) {
std::vector<Array> ret;
for (float value : values) {
ret.push_back(Array::Full(shape, value));
ret.back().set_requires_grad(requires_grad);
}
return ret;
}
class BackpropTest : public ::testing::TestWithParam<::testing::tuple<std::string>> {
protected:
virtual void SetUp() {
std::string device_name = ::testing::get<0>(GetParam());
device_scope_ = std::make_unique<DeviceScope>(device_name);
}
virtual void TearDown() { device_scope_.reset(); }
public:
template <typename T>
void ExpectEqual(const Array& expected, const Array& actual) const {
EXPECT_EQ(expected.dtype(), actual.dtype());
EXPECT_EQ(expected.shape(), actual.shape());
ExpectDataEqual<T>(expected, actual);
}
template <typename T>
void ExpectDataEqual(const Array& expected, const Array& actual) const {
#ifdef XCHAINER_ENABLE_CUDA
std::string device_name = ::testing::get<0>(GetParam());
if (device_name == "cuda") {
cuda::CheckError(cudaDeviceSynchronize());
}
#endif // XCHAINER_ENABLE_CUDA
auto total_size = expected.shape().total_size();
const T* expected_data = static_cast<const T*>(expected.data().get());
const T* actual_data = static_cast<const T*>(actual.data().get());
for (decltype(total_size) i = 0; i < total_size; i++) {
EXPECT_EQ(expected_data[i], actual_data[i]);
}
}
// Checks the correctness of Backward() applied to the output of a given function.
// Gradients are only computed w.r.t. target_inputs, and are compared to expected_grads.
template <typename Fprop, typename... Args>
void CheckBackpropImpl(std::vector<Array>& target_inputs, std::vector<Array>& expected_grads, Fprop&& fprop, Args&&... args) const {
ASSERT_EQ(expected_grads.size(), target_inputs.size());
auto y = fprop(target_inputs, args...);
Backward(y);
for (size_t i = 0; i < expected_grads.size(); ++i) {
ExpectEqual<float>(expected_grads[i], *target_inputs[i].grad());
}
}
template <typename Fprop>
void CheckBackprop(std::vector<Array>& target_inputs, std::vector<Array>& expected_grads, Fprop&& fprop) const {
CheckBackpropImpl(target_inputs, expected_grads, fprop);
}
template <typename Fprop>
void CheckBackprop(std::vector<Array>& target_inputs, std::vector<Array>& other_inputs, std::vector<Array>& expected_grads,
Fprop&& fprop) const {
CheckBackpropImpl(target_inputs, expected_grads, fprop, other_inputs);
for (size_t i = 0; i < other_inputs.size(); ++i) {
EXPECT_FALSE(other_inputs[i].grad());
}
}
// Simple versions. It makes and uses an array with one element for each input.
template <typename Fprop>
void CheckBackprop(std::vector<float> target_inputs, std::vector<float> expected_grads, Fprop&& fprop) const {
auto xs = MakeFullArrays({1}, target_inputs, true);
auto expected_gxs = MakeFullArrays({1}, expected_grads, false);
CheckBackprop(xs, expected_gxs, std::forward<Fprop>(fprop));
}
template <typename Fprop>
void CheckBackprop(std::vector<float> target_inputs, std::vector<float> other_inputs, std::vector<float> expected_grads,
Fprop&& fprop) const {
auto xs = MakeFullArrays({1}, target_inputs, true);
auto other_xs = MakeFullArrays({1}, other_inputs, false);
auto expected_gxs = MakeFullArrays({1}, expected_grads, false);
CheckBackprop(xs, other_xs, expected_gxs, std::forward<Fprop>(fprop));
}
private:
std::unique_ptr<DeviceScope> device_scope_;
};
TEST_P(BackpropTest, Backward) {
CheckBackprop({2.0f, 3.0f}, {4.0f}, {3.0f, 6.0f}, [](auto& xs, auto& ys) { return xs[1] * (xs[0] + ys[0]); });
}
TEST_P(BackpropTest, BackwardSoleArrayNode) {
auto x = Array::Full({1}, 2.0f);
Backward(x);
auto e = Array::OnesLike(x);
ExpectEqual<float>(e, *x.grad());
}
TEST_P(BackpropTest, DoubleBackprop) {
auto fprop = [](auto& xs, auto& ys) {
auto z = xs[0] * (xs[0] + ys[0]);
Backward(z);
auto gx = *xs[0].grad();
xs[0].ClearGrad();
return gx;
};
CheckBackprop({2.0f}, {3.0f}, {2.0f}, fprop);
}
TEST_P(BackpropTest, BackwardInputToMultipleOps) {
CheckBackprop({2.0f}, {3.0f}, {7.0f}, [](auto& xs, auto& ys) { return xs[0] * (xs[0] + ys[0]); });
}
TEST_P(BackpropTest, BackwardIdenticalInputs) {
CheckBackprop({2.0f}, {2.0f}, [](auto& xs) { return xs[0] + xs[0]; });
}
TEST_P(BackpropTest, BackwardGivenInputGrad) {
auto fprop = [](auto& xs) {
xs[0].set_grad(Array::OnesLike(xs[0]));
return xs[0];
};
CheckBackprop({1.0f}, {2.0f}, fprop);
}
TEST_P(BackpropTest, BackwardGivenOutputGrad) {
auto fprop = [](auto& xs, auto& ys) {
auto z = xs[0] * ys[0];
z.set_grad(Array::FullLike(z, 2.0f));
return z;
};
CheckBackprop({2.0f}, {3.0f}, {6.0f}, fprop);
}
INSTANTIATE_TEST_CASE_P(ForEachDevice, BackpropTest, ::testing::Values(
#ifdef XCHAINER_ENABLE_CUDA
std::string{"cuda"},
#endif // XCHAINER_ENABLE_CUDA
std::string{"cpu"}));
} // namespace
} // namespace xchainer
<|endoftext|> |
<commit_before>/*
* cl_demo_handler.cpp - CL demo handler
*
* Copyright (c) 2015 Intel 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.
*
* Author: Wind Yuan <[email protected]>
*/
#include "xcam_utils.h"
#include "cl_demo_handler.h"
namespace XCam {
CLDemoImageKernel::CLDemoImageKernel (SmartPtr<CLContext> &context)
: CLImageKernel (context, "kernel_demo")
{
}
XCamReturn
CLDemoImageKernel::prepare_arguments (
SmartPtr<DrmBoBuffer> &input, SmartPtr<DrmBoBuffer> &output,
CLArgument args[], uint32_t &arg_count,
CLWorkSize &work_size)
{
SmartPtr<CLContext> context = get_context ();
const VideoBufferInfo & video_info = input->get_video_info ();
cl_libva_image image_info;
xcam_mem_clear (&image_info);
image_info.fmt.image_channel_order = CL_R;
image_info.fmt.image_channel_data_type = CL_UNORM_INT8;
image_info.offset = 0;
image_info.width = video_info.width;
image_info.height = (video_info.size / video_info.strides[0])/4*4;
image_info.row_pitch = video_info.strides[0];
_image_in = new CLVaImage (context, input, &image_info);
_image_out = new CLVaImage (context, output, &image_info);
XCAM_ASSERT (_image_in->is_valid () && _image_out->is_valid ());
XCAM_FAIL_RETURN (
WARNING,
_image_in->is_valid () && _image_out->is_valid (),
XCAM_RETURN_ERROR_MEM,
"cl image kernel(%s) in/out memory not available", get_kernel_name ());
//set args;
args[0].arg_adress = &_image_in->get_mem_id ();
args[0].arg_size = sizeof (cl_mem);
args[1].arg_adress = &_image_out->get_mem_id ();
args[1].arg_size = sizeof (cl_mem);
arg_count = 2;
work_size.dim = XCAM_DEFAULT_IMAGE_DIM;
work_size.global[0] = image_info.row_pitch;
work_size.global[1] = image_info.height;
work_size.local[0] = 8;
work_size.local[1] = 4;
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
CLDemoImageKernel::post_execute ()
{
return CLImageKernel::post_execute ();
}
SmartPtr<CLImageHandler>
create_cl_demo_image_handler (SmartPtr<CLContext> &context)
{
SmartPtr<CLImageHandler> demo_handler;
SmartPtr<CLImageKernel> demo_kernel;
XCamReturn ret = XCAM_RETURN_NO_ERROR;
demo_kernel = new CLDemoImageKernel (context);
{
XCAM_CL_KERNEL_FUNC_SOURCE_BEGIN(kernel_demo)
#include "kernel_demo.cl"
XCAM_CL_KERNEL_FUNC_END;
ret = demo_kernel->load_from_source (kernel_demo_body, strlen (kernel_demo_body));
XCAM_FAIL_RETURN (
WARNING,
ret == XCAM_RETURN_NO_ERROR,
NULL,
"CL image handler(%s) load source failed", demo_kernel->get_kernel_name());
}
XCAM_ASSERT (demo_kernel->is_valid ());
demo_handler = new CLImageHandler ("cl_handler_demo");
demo_handler->add_kernel (demo_kernel);
return demo_handler;
}
};
<commit_msg>cl_demo: fix 16 bits copy<commit_after>/*
* cl_demo_handler.cpp - CL demo handler
*
* Copyright (c) 2015 Intel 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.
*
* Author: Wind Yuan <[email protected]>
*/
#include "xcam_utils.h"
#include "cl_demo_handler.h"
namespace XCam {
CLDemoImageKernel::CLDemoImageKernel (SmartPtr<CLContext> &context)
: CLImageKernel (context, "kernel_demo")
{
}
XCamReturn
CLDemoImageKernel::prepare_arguments (
SmartPtr<DrmBoBuffer> &input, SmartPtr<DrmBoBuffer> &output,
CLArgument args[], uint32_t &arg_count,
CLWorkSize &work_size)
{
SmartPtr<CLContext> context = get_context ();
const VideoBufferInfo & video_info = input->get_video_info ();
cl_libva_image image_info;
uint32_t channel_bits = XCAM_ALIGN_UP (video_info.color_bits, 8);
xcam_mem_clear (&image_info);
image_info.fmt.image_channel_order = CL_R;
if (channel_bits == 8)
image_info.fmt.image_channel_data_type = CL_UNORM_INT8;
else if (channel_bits == 16)
image_info.fmt.image_channel_data_type = CL_UNORM_INT16;
image_info.offset = 0;
image_info.width = video_info.width;
image_info.height = (video_info.size / video_info.strides[0])/4*4;
image_info.row_pitch = video_info.strides[0];
_image_in = new CLVaImage (context, input, &image_info);
_image_out = new CLVaImage (context, output, &image_info);
XCAM_ASSERT (_image_in->is_valid () && _image_out->is_valid ());
XCAM_FAIL_RETURN (
WARNING,
_image_in->is_valid () && _image_out->is_valid (),
XCAM_RETURN_ERROR_MEM,
"cl image kernel(%s) in/out memory not available", get_kernel_name ());
//set args;
args[0].arg_adress = &_image_in->get_mem_id ();
args[0].arg_size = sizeof (cl_mem);
args[1].arg_adress = &_image_out->get_mem_id ();
args[1].arg_size = sizeof (cl_mem);
arg_count = 2;
work_size.dim = XCAM_DEFAULT_IMAGE_DIM;
work_size.global[0] = image_info.row_pitch;
work_size.global[1] = image_info.height;
work_size.local[0] = 8;
work_size.local[1] = 4;
return XCAM_RETURN_NO_ERROR;
}
XCamReturn
CLDemoImageKernel::post_execute ()
{
return CLImageKernel::post_execute ();
}
SmartPtr<CLImageHandler>
create_cl_demo_image_handler (SmartPtr<CLContext> &context)
{
SmartPtr<CLImageHandler> demo_handler;
SmartPtr<CLImageKernel> demo_kernel;
XCamReturn ret = XCAM_RETURN_NO_ERROR;
demo_kernel = new CLDemoImageKernel (context);
{
XCAM_CL_KERNEL_FUNC_SOURCE_BEGIN(kernel_demo)
#include "kernel_demo.cl"
XCAM_CL_KERNEL_FUNC_END;
ret = demo_kernel->load_from_source (kernel_demo_body, strlen (kernel_demo_body));
XCAM_FAIL_RETURN (
WARNING,
ret == XCAM_RETURN_NO_ERROR,
NULL,
"CL image handler(%s) load source failed", demo_kernel->get_kernel_name());
}
XCAM_ASSERT (demo_kernel->is_valid ());
demo_handler = new CLImageHandler ("cl_handler_demo");
demo_handler->add_kernel (demo_kernel);
return demo_handler;
}
};
<|endoftext|> |
<commit_before>// Copyright (C) 2021 Jérôme "Lynix" Leclercq ([email protected])
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/SpriteChainRenderer.hpp>
#include <Nazara/Graphics/Graphics.hpp>
#include <Nazara/Graphics/RenderSpriteChain.hpp>
#include <Nazara/Graphics/ViewerInstance.hpp>
#include <Nazara/Renderer/CommandBufferBuilder.hpp>
#include <Nazara/Renderer/RenderFrame.hpp>
#include <Nazara/Renderer/UploadPool.hpp>
#include <utility>
#include <Nazara/Graphics/Debug.hpp>
namespace Nz
{
SpriteChainRenderer::SpriteChainRenderer(RenderDevice& device, std::size_t maxVertexBufferSize) :
m_device(device),
m_maxVertexBufferSize(maxVertexBufferSize),
m_maxVertexCount(m_maxVertexBufferSize / (2 * sizeof(float))) // Treat vec2 as the minimum declaration possible
{
m_vertexBufferPool = std::make_shared<VertexBufferPool>();
std::size_t maxQuadCount = m_maxVertexCount / 4;
std::size_t indexCount = 6 * maxQuadCount;
m_indexBuffer = m_device.InstantiateBuffer(BufferType::Index);
if (!m_indexBuffer->Initialize(indexCount * sizeof(UInt16), BufferUsage::DeviceLocal))
throw std::runtime_error("failed to initialize index buffer");
// Generate indices for quad (0, 1, 2, 2, 1, 3, ...)
std::vector<UInt16> indices(indexCount);
UInt16* indexPtr = indices.data();
for (std::size_t i = 0; i < maxQuadCount; ++i)
{
UInt16 index = static_cast<UInt16>(i);
*indexPtr++ = index * 4 + 0;
*indexPtr++ = index * 4 + 1;
*indexPtr++ = index * 4 + 2;
*indexPtr++ = index * 4 + 2;
*indexPtr++ = index * 4 + 1;
*indexPtr++ = index * 4 + 3;
}
m_indexBuffer->Fill(indices.data(), 0, indexCount * sizeof(UInt16));
}
std::unique_ptr<ElementRendererData> SpriteChainRenderer::InstanciateData()
{
return std::make_unique<SpriteChainRendererData>();
}
void SpriteChainRenderer::Prepare(const ViewerInstance& viewerInstance, ElementRendererData& rendererData, RenderFrame& currentFrame, const Pointer<const RenderElement>* elements, std::size_t elementCount)
{
Graphics* graphics = Graphics::Instance();
auto& data = static_cast<SpriteChainRendererData&>(rendererData);
std::size_t firstQuadIndex = 0;
SpriteChainRendererData::DrawCall* currentDrawCall = nullptr;
UploadPool::Allocation* currentAllocation = nullptr;
UInt8* currentAllocationMemPtr = nullptr;
const VertexDeclaration* currentVertexDeclaration = nullptr;
AbstractBuffer* currentVertexBuffer = nullptr;
const RenderPipeline* currentPipeline = nullptr;
const ShaderBinding* currentShaderBinding = nullptr;
const Texture* currentTextureOverlay = nullptr;
const WorldInstance* currentWorldInstance = nullptr;
auto FlushDrawCall = [&]()
{
currentDrawCall = nullptr;
};
auto FlushDrawData = [&]()
{
FlushDrawCall();
currentShaderBinding = nullptr;
};
auto Flush = [&]()
{
// changing vertex buffer always mean we have to switch draw calls
FlushDrawCall();
if (currentAllocation)
{
std::size_t size = currentAllocationMemPtr - static_cast<UInt8*>(currentAllocation->mappedPtr);
m_pendingCopies.emplace_back(BufferCopy{
currentVertexBuffer,
currentAllocation,
size
});
firstQuadIndex = 0;
currentAllocation = nullptr;
currentVertexBuffer = nullptr;
}
};
std::size_t oldDrawCallCount = data.drawCalls.size();
const auto& defaultSampler = graphics->GetSamplerCache().Get({});
for (std::size_t i = 0; i < elementCount; ++i)
{
assert(elements[i]->GetElementType() == UnderlyingCast(BasicRenderElement::SpriteChain));
const RenderSpriteChain& spriteChain = static_cast<const RenderSpriteChain&>(*elements[i]);
const VertexDeclaration* vertexDeclaration = spriteChain.GetVertexDeclaration();
std::size_t stride = vertexDeclaration->GetStride();
if (currentVertexDeclaration != vertexDeclaration)
{
// TODO: It's be possible to use another vertex declaration with the same vertex buffer but currently very complicated
// Wait until buffer rewrite
Flush();
currentVertexDeclaration = vertexDeclaration;
}
if (currentPipeline != &spriteChain.GetRenderPipeline())
{
FlushDrawCall();
currentPipeline = &spriteChain.GetRenderPipeline();
}
if (currentWorldInstance != &spriteChain.GetWorldInstance())
{
// TODO: Flushing draw calls on instance binding means we can have e.g. 1000 sprites rendered using a draw call for each one
// which is far from being efficient, using some bindless could help (or at least instancing?)
FlushDrawData();
currentWorldInstance = &spriteChain.GetWorldInstance();
}
if (currentTextureOverlay != spriteChain.GetTextureOverlay())
{
FlushDrawData();
currentTextureOverlay = spriteChain.GetTextureOverlay();
}
std::size_t remainingQuads = spriteChain.GetSpriteCount();
const UInt8* spriteData = static_cast<const UInt8*>(spriteChain.GetSpriteData());
while (remainingQuads > 0)
{
if (!currentAllocation)
{
currentAllocation = ¤tFrame.GetUploadPool().Allocate(m_maxVertexBufferSize);
currentAllocationMemPtr = static_cast<UInt8*>(currentAllocation->mappedPtr);
std::shared_ptr<AbstractBuffer> vertexBuffer;
// Try to reuse vertex buffers from pool if any
if (!m_vertexBufferPool->vertexBuffers.empty())
{
vertexBuffer = std::move(m_vertexBufferPool->vertexBuffers.back());
m_vertexBufferPool->vertexBuffers.pop_back();
}
else
{
vertexBuffer = m_device.InstantiateBuffer(BufferType::Vertex);
vertexBuffer->Initialize(m_maxVertexBufferSize, BufferUsage::DeviceLocal | BufferUsage::Dynamic);
}
currentVertexBuffer = vertexBuffer.get();
data.vertexBuffers.emplace_back(std::move(vertexBuffer));
}
if (!currentShaderBinding)
{
m_bindingCache.clear();
const MaterialPass& materialPass = spriteChain.GetMaterialPass();
materialPass.FillShaderBinding(m_bindingCache);
// Predefined shader bindings
const auto& matSettings = materialPass.GetSettings();
if (std::size_t bindingIndex = matSettings->GetPredefinedBinding(PredefinedShaderBinding::InstanceDataUbo); bindingIndex != MaterialSettings::InvalidIndex)
{
const auto& instanceBuffer = currentWorldInstance->GetInstanceBuffer();
auto& bindingEntry = m_bindingCache.emplace_back();
bindingEntry.bindingIndex = bindingIndex;
bindingEntry.content = ShaderBinding::UniformBufferBinding{
instanceBuffer.get(),
0, instanceBuffer->GetSize()
};
}
if (std::size_t bindingIndex = matSettings->GetPredefinedBinding(PredefinedShaderBinding::ViewerDataUbo); bindingIndex != MaterialSettings::InvalidIndex)
{
const auto& viewerBuffer = viewerInstance.GetViewerBuffer();
auto& bindingEntry = m_bindingCache.emplace_back();
bindingEntry.bindingIndex = bindingIndex;
bindingEntry.content = ShaderBinding::UniformBufferBinding{
viewerBuffer.get(),
0, viewerBuffer->GetSize()
};
}
if (std::size_t bindingIndex = matSettings->GetPredefinedBinding(PredefinedShaderBinding::OverlayTexture); bindingIndex != MaterialSettings::InvalidIndex)
{
auto& bindingEntry = m_bindingCache.emplace_back();
bindingEntry.bindingIndex = bindingIndex;
bindingEntry.content = ShaderBinding::TextureBinding{
currentTextureOverlay, defaultSampler.get()
};
}
ShaderBindingPtr drawDataBinding = currentPipeline->GetPipelineInfo().pipelineLayout->AllocateShaderBinding(0);
drawDataBinding->Update(m_bindingCache.data(), m_bindingCache.size());
currentShaderBinding = drawDataBinding.get();
data.shaderBindings.emplace_back(std::move(drawDataBinding));
}
if (!currentDrawCall)
{
data.drawCalls.push_back(SpriteChainRendererData::DrawCall{
currentVertexBuffer,
currentPipeline,
currentShaderBinding,
6 * firstQuadIndex,
0,
});
currentDrawCall = &data.drawCalls.back();
}
std::size_t remainingSpace = m_maxVertexBufferSize - (currentAllocationMemPtr - static_cast<UInt8*>(currentAllocation->mappedPtr));
std::size_t maxQuads = remainingSpace / (4 * stride);
if (maxQuads == 0)
{
Flush();
continue;
}
std::size_t copiedQuadCount = std::min(maxQuads, remainingQuads);
std::size_t copiedSize = 4 * copiedQuadCount * stride;
std::memcpy(currentAllocationMemPtr, spriteData, copiedSize);
currentAllocationMemPtr += copiedSize;
spriteData += copiedSize;
firstQuadIndex += copiedQuadCount;
currentDrawCall->quadCount += copiedQuadCount;
remainingQuads -= copiedQuadCount;
// If there's still data to copy, it means buffer is full, flush it
if (remainingQuads > 0)
Flush();
}
}
//TODO: Add Finish()/PrepareEnd() call to allow to reuse buffers/draw calls for multiple Prepare calls
Flush();
const RenderSpriteChain* firstSpriteChain = static_cast<const RenderSpriteChain*>(elements[0]);
std::size_t drawCallCount = data.drawCalls.size() - oldDrawCallCount;
data.drawCallPerElement[firstSpriteChain] = SpriteChainRendererData::DrawCallIndices{ oldDrawCallCount, drawCallCount };
if (!m_pendingCopies.empty())
{
currentFrame.Execute([&](CommandBufferBuilder& builder)
{
for (auto& copy : m_pendingCopies)
builder.CopyBuffer(*copy.allocation, copy.targetBuffer, copy.size);
builder.PostTransferBarrier();
}, Nz::QueueType::Transfer);
m_pendingCopies.clear();
}
}
void SpriteChainRenderer::Render(const ViewerInstance& viewerInstance, ElementRendererData& rendererData, CommandBufferBuilder& commandBuffer, const Pointer<const RenderElement>* elements, std::size_t /*elementCount*/)
{
auto& data = static_cast<SpriteChainRendererData&>(rendererData);
commandBuffer.BindIndexBuffer(*m_indexBuffer);
const AbstractBuffer* currentVertexBuffer = nullptr;
const RenderPipeline* currentPipeline = nullptr;
const ShaderBinding* currentShaderBinding = nullptr;
const ViewerInstance* currentViewerInstance = nullptr;
const WorldInstance* currentWorldInstance = nullptr;
const RenderSpriteChain* firstSpriteChain = static_cast<const RenderSpriteChain*>(elements[0]);
auto it = data.drawCallPerElement.find(firstSpriteChain);
assert(it != data.drawCallPerElement.end());
const auto& indices = it->second;
for (std::size_t i = 0; i < indices.count; ++i)
{
const auto& drawCall = data.drawCalls[indices.start + i];
if (currentVertexBuffer != drawCall.vertexBuffer)
{
commandBuffer.BindVertexBuffer(0, *drawCall.vertexBuffer);
currentVertexBuffer = drawCall.vertexBuffer;
}
if (currentPipeline != drawCall.renderPipeline)
{
commandBuffer.BindPipeline(*drawCall.renderPipeline);
currentPipeline = drawCall.renderPipeline;
}
if (currentShaderBinding != drawCall.shaderBinding)
{
commandBuffer.BindShaderBinding(0, *drawCall.shaderBinding);
currentShaderBinding = drawCall.shaderBinding;
}
commandBuffer.DrawIndexed(drawCall.quadCount * 6, 1U, drawCall.firstIndex);
}
}
void SpriteChainRenderer::Reset(ElementRendererData& rendererData, RenderFrame& currentFrame)
{
auto& data = static_cast<SpriteChainRendererData&>(rendererData);
for (auto& vertexBufferPtr : data.vertexBuffers)
{
currentFrame.PushReleaseCallback([pool = m_vertexBufferPool, vertexBuffer = std::move(vertexBufferPtr)]()
{
pool->vertexBuffers.push_back(std::move(vertexBuffer));
});
}
data.vertexBuffers.clear();
for (auto& shaderBinding : data.shaderBindings)
currentFrame.PushForRelease(std::move(shaderBinding));
data.shaderBindings.clear();
data.drawCalls.clear();
}
}
<commit_msg>Graphics/SpriteChainRenderer: Warning fix<commit_after>// Copyright (C) 2021 Jérôme "Lynix" Leclercq ([email protected])
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/SpriteChainRenderer.hpp>
#include <Nazara/Graphics/Graphics.hpp>
#include <Nazara/Graphics/RenderSpriteChain.hpp>
#include <Nazara/Graphics/ViewerInstance.hpp>
#include <Nazara/Renderer/CommandBufferBuilder.hpp>
#include <Nazara/Renderer/RenderFrame.hpp>
#include <Nazara/Renderer/UploadPool.hpp>
#include <utility>
#include <Nazara/Graphics/Debug.hpp>
namespace Nz
{
SpriteChainRenderer::SpriteChainRenderer(RenderDevice& device, std::size_t maxVertexBufferSize) :
m_device(device),
m_maxVertexBufferSize(maxVertexBufferSize),
m_maxVertexCount(m_maxVertexBufferSize / (2 * sizeof(float))) // Treat vec2 as the minimum declaration possible
{
m_vertexBufferPool = std::make_shared<VertexBufferPool>();
std::size_t maxQuadCount = m_maxVertexCount / 4;
std::size_t indexCount = 6 * maxQuadCount;
m_indexBuffer = m_device.InstantiateBuffer(BufferType::Index);
if (!m_indexBuffer->Initialize(indexCount * sizeof(UInt16), BufferUsage::DeviceLocal))
throw std::runtime_error("failed to initialize index buffer");
// Generate indices for quad (0, 1, 2, 2, 1, 3, ...)
std::vector<UInt16> indices(indexCount);
UInt16* indexPtr = indices.data();
for (std::size_t i = 0; i < maxQuadCount; ++i)
{
UInt16 index = static_cast<UInt16>(i);
*indexPtr++ = index * 4 + 0;
*indexPtr++ = index * 4 + 1;
*indexPtr++ = index * 4 + 2;
*indexPtr++ = index * 4 + 2;
*indexPtr++ = index * 4 + 1;
*indexPtr++ = index * 4 + 3;
}
m_indexBuffer->Fill(indices.data(), 0, indexCount * sizeof(UInt16));
}
std::unique_ptr<ElementRendererData> SpriteChainRenderer::InstanciateData()
{
return std::make_unique<SpriteChainRendererData>();
}
void SpriteChainRenderer::Prepare(const ViewerInstance& viewerInstance, ElementRendererData& rendererData, RenderFrame& currentFrame, const Pointer<const RenderElement>* elements, std::size_t elementCount)
{
Graphics* graphics = Graphics::Instance();
auto& data = static_cast<SpriteChainRendererData&>(rendererData);
std::size_t firstQuadIndex = 0;
SpriteChainRendererData::DrawCall* currentDrawCall = nullptr;
UploadPool::Allocation* currentAllocation = nullptr;
UInt8* currentAllocationMemPtr = nullptr;
const VertexDeclaration* currentVertexDeclaration = nullptr;
AbstractBuffer* currentVertexBuffer = nullptr;
const RenderPipeline* currentPipeline = nullptr;
const ShaderBinding* currentShaderBinding = nullptr;
const Texture* currentTextureOverlay = nullptr;
const WorldInstance* currentWorldInstance = nullptr;
auto FlushDrawCall = [&]()
{
currentDrawCall = nullptr;
};
auto FlushDrawData = [&]()
{
FlushDrawCall();
currentShaderBinding = nullptr;
};
auto Flush = [&]()
{
// changing vertex buffer always mean we have to switch draw calls
FlushDrawCall();
if (currentAllocation)
{
std::size_t size = currentAllocationMemPtr - static_cast<UInt8*>(currentAllocation->mappedPtr);
m_pendingCopies.emplace_back(BufferCopy{
currentVertexBuffer,
currentAllocation,
size
});
firstQuadIndex = 0;
currentAllocation = nullptr;
currentVertexBuffer = nullptr;
}
};
std::size_t oldDrawCallCount = data.drawCalls.size();
const auto& defaultSampler = graphics->GetSamplerCache().Get({});
for (std::size_t i = 0; i < elementCount; ++i)
{
assert(elements[i]->GetElementType() == UnderlyingCast(BasicRenderElement::SpriteChain));
const RenderSpriteChain& spriteChain = static_cast<const RenderSpriteChain&>(*elements[i]);
const VertexDeclaration* vertexDeclaration = spriteChain.GetVertexDeclaration();
std::size_t stride = vertexDeclaration->GetStride();
if (currentVertexDeclaration != vertexDeclaration)
{
// TODO: It's be possible to use another vertex declaration with the same vertex buffer but currently very complicated
// Wait until buffer rewrite
Flush();
currentVertexDeclaration = vertexDeclaration;
}
if (currentPipeline != &spriteChain.GetRenderPipeline())
{
FlushDrawCall();
currentPipeline = &spriteChain.GetRenderPipeline();
}
if (currentWorldInstance != &spriteChain.GetWorldInstance())
{
// TODO: Flushing draw calls on instance binding means we can have e.g. 1000 sprites rendered using a draw call for each one
// which is far from being efficient, using some bindless could help (or at least instancing?)
FlushDrawData();
currentWorldInstance = &spriteChain.GetWorldInstance();
}
if (currentTextureOverlay != spriteChain.GetTextureOverlay())
{
FlushDrawData();
currentTextureOverlay = spriteChain.GetTextureOverlay();
}
std::size_t remainingQuads = spriteChain.GetSpriteCount();
const UInt8* spriteData = static_cast<const UInt8*>(spriteChain.GetSpriteData());
while (remainingQuads > 0)
{
if (!currentAllocation)
{
currentAllocation = ¤tFrame.GetUploadPool().Allocate(m_maxVertexBufferSize);
currentAllocationMemPtr = static_cast<UInt8*>(currentAllocation->mappedPtr);
std::shared_ptr<AbstractBuffer> vertexBuffer;
// Try to reuse vertex buffers from pool if any
if (!m_vertexBufferPool->vertexBuffers.empty())
{
vertexBuffer = std::move(m_vertexBufferPool->vertexBuffers.back());
m_vertexBufferPool->vertexBuffers.pop_back();
}
else
{
vertexBuffer = m_device.InstantiateBuffer(BufferType::Vertex);
vertexBuffer->Initialize(m_maxVertexBufferSize, BufferUsage::DeviceLocal | BufferUsage::Dynamic);
}
currentVertexBuffer = vertexBuffer.get();
data.vertexBuffers.emplace_back(std::move(vertexBuffer));
}
if (!currentShaderBinding)
{
m_bindingCache.clear();
const MaterialPass& materialPass = spriteChain.GetMaterialPass();
materialPass.FillShaderBinding(m_bindingCache);
// Predefined shader bindings
const auto& matSettings = materialPass.GetSettings();
if (std::size_t bindingIndex = matSettings->GetPredefinedBinding(PredefinedShaderBinding::InstanceDataUbo); bindingIndex != MaterialSettings::InvalidIndex)
{
const auto& instanceBuffer = currentWorldInstance->GetInstanceBuffer();
auto& bindingEntry = m_bindingCache.emplace_back();
bindingEntry.bindingIndex = bindingIndex;
bindingEntry.content = ShaderBinding::UniformBufferBinding{
instanceBuffer.get(),
0, instanceBuffer->GetSize()
};
}
if (std::size_t bindingIndex = matSettings->GetPredefinedBinding(PredefinedShaderBinding::ViewerDataUbo); bindingIndex != MaterialSettings::InvalidIndex)
{
const auto& viewerBuffer = viewerInstance.GetViewerBuffer();
auto& bindingEntry = m_bindingCache.emplace_back();
bindingEntry.bindingIndex = bindingIndex;
bindingEntry.content = ShaderBinding::UniformBufferBinding{
viewerBuffer.get(),
0, viewerBuffer->GetSize()
};
}
if (std::size_t bindingIndex = matSettings->GetPredefinedBinding(PredefinedShaderBinding::OverlayTexture); bindingIndex != MaterialSettings::InvalidIndex)
{
auto& bindingEntry = m_bindingCache.emplace_back();
bindingEntry.bindingIndex = bindingIndex;
bindingEntry.content = ShaderBinding::TextureBinding{
currentTextureOverlay, defaultSampler.get()
};
}
ShaderBindingPtr drawDataBinding = currentPipeline->GetPipelineInfo().pipelineLayout->AllocateShaderBinding(0);
drawDataBinding->Update(m_bindingCache.data(), m_bindingCache.size());
currentShaderBinding = drawDataBinding.get();
data.shaderBindings.emplace_back(std::move(drawDataBinding));
}
if (!currentDrawCall)
{
data.drawCalls.push_back(SpriteChainRendererData::DrawCall{
currentVertexBuffer,
currentPipeline,
currentShaderBinding,
6 * firstQuadIndex,
0,
});
currentDrawCall = &data.drawCalls.back();
}
std::size_t remainingSpace = m_maxVertexBufferSize - (currentAllocationMemPtr - static_cast<UInt8*>(currentAllocation->mappedPtr));
std::size_t maxQuads = remainingSpace / (4 * stride);
if (maxQuads == 0)
{
Flush();
continue;
}
std::size_t copiedQuadCount = std::min(maxQuads, remainingQuads);
std::size_t copiedSize = 4 * copiedQuadCount * stride;
std::memcpy(currentAllocationMemPtr, spriteData, copiedSize);
currentAllocationMemPtr += copiedSize;
spriteData += copiedSize;
firstQuadIndex += copiedQuadCount;
currentDrawCall->quadCount += copiedQuadCount;
remainingQuads -= copiedQuadCount;
// If there's still data to copy, it means buffer is full, flush it
if (remainingQuads > 0)
Flush();
}
}
//TODO: Add Finish()/PrepareEnd() call to allow to reuse buffers/draw calls for multiple Prepare calls
Flush();
const RenderSpriteChain* firstSpriteChain = static_cast<const RenderSpriteChain*>(elements[0]);
std::size_t drawCallCount = data.drawCalls.size() - oldDrawCallCount;
data.drawCallPerElement[firstSpriteChain] = SpriteChainRendererData::DrawCallIndices{ oldDrawCallCount, drawCallCount };
if (!m_pendingCopies.empty())
{
currentFrame.Execute([&](CommandBufferBuilder& builder)
{
for (auto& copy : m_pendingCopies)
builder.CopyBuffer(*copy.allocation, copy.targetBuffer, copy.size);
builder.PostTransferBarrier();
}, Nz::QueueType::Transfer);
m_pendingCopies.clear();
}
}
void SpriteChainRenderer::Render(const ViewerInstance& /*viewerInstance*/, ElementRendererData& rendererData, CommandBufferBuilder& commandBuffer, const Pointer<const RenderElement>* elements, std::size_t /*elementCount*/)
{
auto& data = static_cast<SpriteChainRendererData&>(rendererData);
commandBuffer.BindIndexBuffer(*m_indexBuffer);
const AbstractBuffer* currentVertexBuffer = nullptr;
const RenderPipeline* currentPipeline = nullptr;
const ShaderBinding* currentShaderBinding = nullptr;
const RenderSpriteChain* firstSpriteChain = static_cast<const RenderSpriteChain*>(elements[0]);
auto it = data.drawCallPerElement.find(firstSpriteChain);
assert(it != data.drawCallPerElement.end());
const auto& indices = it->second;
for (std::size_t i = 0; i < indices.count; ++i)
{
const auto& drawCall = data.drawCalls[indices.start + i];
if (currentVertexBuffer != drawCall.vertexBuffer)
{
commandBuffer.BindVertexBuffer(0, *drawCall.vertexBuffer);
currentVertexBuffer = drawCall.vertexBuffer;
}
if (currentPipeline != drawCall.renderPipeline)
{
commandBuffer.BindPipeline(*drawCall.renderPipeline);
currentPipeline = drawCall.renderPipeline;
}
if (currentShaderBinding != drawCall.shaderBinding)
{
commandBuffer.BindShaderBinding(0, *drawCall.shaderBinding);
currentShaderBinding = drawCall.shaderBinding;
}
commandBuffer.DrawIndexed(drawCall.quadCount * 6, 1U, drawCall.firstIndex);
}
}
void SpriteChainRenderer::Reset(ElementRendererData& rendererData, RenderFrame& currentFrame)
{
auto& data = static_cast<SpriteChainRendererData&>(rendererData);
for (auto& vertexBufferPtr : data.vertexBuffers)
{
currentFrame.PushReleaseCallback([pool = m_vertexBufferPool, vertexBuffer = std::move(vertexBufferPtr)]()
{
pool->vertexBuffers.push_back(std::move(vertexBuffer));
});
}
data.vertexBuffers.clear();
for (auto& shaderBinding : data.shaderBindings)
currentFrame.PushForRelease(std::move(shaderBinding));
data.shaderBindings.clear();
data.drawCalls.clear();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/common/shell_switches.h"
namespace switches {
// Makes Content Shell use the given path for its data directory.
const char kContentShellDataPath[] = "data-path";
// Enable developer tools
const char kDeveloper[] = "developer";
// Display no toolbar
const char kNoToolbar[] = "no-toolbar";
// Open specified url
const char kUrl[] = "url";
// Set current working directory.
const char kWorkingDirectory[] = "working-directory";
// Pass the main script to node.
const char kNodeMain[] = "node-main";
const char kmMain[] = "main";
const char kmName[] = "name";
const char kmWebkit[] = "webkit";
const char kmNodejs[] = "nodejs";
const char kmWindow[] = "window";
// Allows only one instance of the app.
const char kmSingleInstance[] = "single-instance";
const char kmTitle[] = "title";
const char kmToolbar[] = "toolbar";
const char kmIcon[] = "icon";
const char kmFrame[] = "frame";
const char kmShow[] = "show";
const char kmPosition[] = "position";
const char kmX[] = "x";
const char kmY[] = "y";
const char kmWidth[] = "width";
const char kmHeight[] = "height";
const char kmMinWidth[] = "min_width";
const char kmMinHeight[] = "min_height";
const char kmMaxWidth[] = "max_width";
const char kmMaxHeight[] = "max_height";
const char kmResizable[] = "resizable";
const char kmAsDesktop[] = "as_desktop";
const char kmFullscreen[] = "fullscreen";
// Start with the kiosk mode, see Opera's page for description:
// http://www.opera.com/support/mastering/kiosk/
const char kmKiosk[] = "kiosk";
// Make windows stays on the top of all other windows.
const char kmAlwaysOnTop[] = "always-on-top";
// Whether we should support WebGL.
const char kmWebgl[] = "webgl";
// Whether to enable Java applets in web page.
const char kmJava[] = "java";
// Whether to enable third party NPAPI plugins.
const char kmPlugin[] = "plugin";
// Whether to enable page caches.
const char kmPageCache[] = "page-cache";
const char kmUserAgent[] = "user-agent";
// rules to turn on Node for remote pages
const char kmRemotePages[] = "access-node-remote";
} // namespace switches
<commit_msg>rename "access-node-remote" to "node-remote"<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/common/shell_switches.h"
namespace switches {
// Makes Content Shell use the given path for its data directory.
const char kContentShellDataPath[] = "data-path";
// Enable developer tools
const char kDeveloper[] = "developer";
// Display no toolbar
const char kNoToolbar[] = "no-toolbar";
// Open specified url
const char kUrl[] = "url";
// Set current working directory.
const char kWorkingDirectory[] = "working-directory";
// Pass the main script to node.
const char kNodeMain[] = "node-main";
const char kmMain[] = "main";
const char kmName[] = "name";
const char kmWebkit[] = "webkit";
const char kmNodejs[] = "nodejs";
const char kmWindow[] = "window";
// Allows only one instance of the app.
const char kmSingleInstance[] = "single-instance";
const char kmTitle[] = "title";
const char kmToolbar[] = "toolbar";
const char kmIcon[] = "icon";
const char kmFrame[] = "frame";
const char kmShow[] = "show";
const char kmPosition[] = "position";
const char kmX[] = "x";
const char kmY[] = "y";
const char kmWidth[] = "width";
const char kmHeight[] = "height";
const char kmMinWidth[] = "min_width";
const char kmMinHeight[] = "min_height";
const char kmMaxWidth[] = "max_width";
const char kmMaxHeight[] = "max_height";
const char kmResizable[] = "resizable";
const char kmAsDesktop[] = "as_desktop";
const char kmFullscreen[] = "fullscreen";
// Start with the kiosk mode, see Opera's page for description:
// http://www.opera.com/support/mastering/kiosk/
const char kmKiosk[] = "kiosk";
// Make windows stays on the top of all other windows.
const char kmAlwaysOnTop[] = "always-on-top";
// Whether we should support WebGL.
const char kmWebgl[] = "webgl";
// Whether to enable Java applets in web page.
const char kmJava[] = "java";
// Whether to enable third party NPAPI plugins.
const char kmPlugin[] = "plugin";
// Whether to enable page caches.
const char kmPageCache[] = "page-cache";
const char kmUserAgent[] = "user-agent";
// rules to turn on Node for remote pages
const char kmRemotePages[] = "node-remote";
} // namespace switches
<|endoftext|> |
<commit_before>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
const auto RED = cv::Scalar(0,0,255);
const auto PINK = cv::Scalar(230,130,255);
const auto BLUE = cv::Scalar(255,0,0);
const auto LIGHTBLUE = cv::Scalar(255,255,160);
const auto GREEN = cv::Scalar(0,255,0);
const auto IMAGE_SCALE = .25;
class MyData
{
public:
const cv::Mat original_image;
cv::Mat image;
MyData( auto _image ) : original_image(_image)
{
original_image.copyTo(image);
}
void reset() { original_image.copyTo(image); };
void update(auto _newImage) { _newImage.copyTo(image); };
};
class MyWindow
{
protected:
const string winName;
MyData d;
public:
/* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */
MyWindow( auto _winName, auto _image ):
winName( _winName ), d( _image )
{
cv::namedWindow( winName, WINDOW_AUTOSIZE );
}
virtual ~MyWindow(void);
virtual void showImage();
virtual void reset();
};
MyWindow::~MyWindow()
{
cv::destroyWindow( winName );
}
void MyWindow::reset()
{
d.reset();
showImage();
}
void MyWindow::showImage()
{
cv::imshow( winName, d.image );
}
class MyOperationWindow : public MyWindow
{
protected:
virtual void setControls(){};
virtual string getDescription() = 0;
public:
void apply( MyData& _d, std::vector<string>& _process_pile )
{
_d.update(d.image);
_process_pile.push_back(getDescription());
}
};
class MyThreshold : public MyOperationWindow
{
int th;
public:
MyThreshold( auto _winName, auto _image)
: MyWindow( _winName, _image ), th(125) { setControls(); };
MyThreshold( auto _winName, auto _image, auto _th )
: MyWindow( _winName, _image ), th(_th) { setControls(); };
private:
string getDescription() override;
void setControls() override; //
void thresholdImage();
static void thresholdCallback( int _th, void* ); //
};
string MyThreshold::getDescription()
{
return "th " + std::to_string(th);
}
void MyThreshold::setControls() //
{
const std::string bar_name = winName + "_thBar";
cv::createTrackbar( bar_name, winName, &th, 255, thresholdCallback );
}
void MyThreshold::thresholdCallback( int _th, void* ) //
{
th = _th;
thresholdImage();
showImage();
}
void MyThreshold::thresholdImage()
{
enum ThresholdType {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,
THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };
ThresholdType const threshold_type = BINARY;
int const max_BINARY_value = 255;
threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );
}
class MyApp : public MyWindow
{
vector<string> process;
MyOperationWindow* current_operation;
public:
void showImage();
char option(auto _option);
};
static void help()
{
cout << "L (or a) - list image transformations\n"
<< "R (or s) - restore original image\n"
<< "t (or d) - activate threshold window\n"
<< "r (or f) - reset the operation window\n"
<< "(enter) (or g) - accept changes and kill the operation window\n"
<< "(backspace) (or h)- ignore changes and kill the operation window\n"
<< endl;
}
MyApp::option( auto _option )
{
switch(_option)
{
case 't': case 'd':
/// create the threshold window
if (!current_operation)
current_operation = new MyThreshold("theshold", d.image);
break;
case 'R': case 's':
/// reset the whole application
reset();
case 'r': case 'f':
/// reset the threshold window
if (!current_operation)
current_operation->reset();
break;
case 'L': case 'a':
/// print the processes applied to the image until now
for (const auto& p : process)
std::cout << p << std::endl;
case 'g':
if (!current_operation){
current_operation->apply(d.image, process);
delete(current_operation);
}
break;
case 'h':
if (!current_operation)
delete(current_operation);
break;
}
return _option;
}
const char* keys =
{
"{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}"
};
int main( int argc, const char** argv )
{
cv::CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
std::string inputImage = parser.get<string>(0);
// Load the source image. HighGUI use.
cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );
if(image.empty())
{
std::cerr << "Cannot read image file: " << inputImage << std::endl;
return -1;
}
// TODO: check size and reduce it only if needed
cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);
help();
/// Create the GUI
std::string winName = "main window"
MyApp appHandle = MyApp(winName, image);
/// Loop until the user kills the program
const auto ESC_KEY = '\x1b';
for (;;){
// TODO: why the fuck appHandle is not declared???
// TODO: Why this does not work? if ( appHandle.option((char) waitKey(0)) == ESC_KEY )
int c = waitKey(0);
if ( (char) c == ESC_KEY )
goto exit_main;
else
appHandle.option((char) c);
}
exit_main:
std::cout << "Exit" << std::endl;
destroyWindow(winName);
return 0;
}
<commit_msg>Changed: * the main loop * parent constructors * use of std::uniq_ptr<commit_after>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
const auto RED = cv::Scalar(0,0,255);
const auto PINK = cv::Scalar(230,130,255);
const auto BLUE = cv::Scalar(255,0,0);
const auto LIGHTBLUE = cv::Scalar(255,255,160);
const auto GREEN = cv::Scalar(0,255,0);
const auto IMAGE_SCALE = .25;
class MyData
{
public:
const cv::Mat original_image;
cv::Mat image;
MyData( auto _image ) : original_image(_image)
{
original_image.copyTo(image);
}
void reset() { original_image.copyTo(image); };
void update(auto _newImage) { _newImage.copyTo(image); };
};
class MyWindow
{
protected:
const string winName;
MyData d;
public:
/* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */
MyWindow( auto _winName, auto _image ):
winName( _winName ), d( _image )
{
cv::namedWindow( winName, WINDOW_AUTOSIZE );
}
virtual ~MyWindow(void);
virtual void showImage();
virtual void reset();
};
MyWindow::~MyWindow()
{
cv::destroyWindow( winName );
}
void MyWindow::reset()
{
d.reset();
showImage();
}
void MyWindow::showImage()
{
cv::imshow( winName, d.image );
}
class MyOperationWindow : public MyWindow
{
protected:
virtual void setControls(){};
virtual string getDescription() = 0;
public:
MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) { setControls(); };
void apply( MyData& _d, std::vector<string>& _process_pile )
{
_d.update(d.image);
_process_pile.push_back(getDescription());
}
};
class MyThreshold : public MyOperationWindow
{
int th;
public:
MyThreshold( auto _winName, auto _image)
: MyOperationWindow( _winName, _image ), th(125) { setControls(); };
MyThreshold( auto _winName, auto _image, auto _th )
: MyOperationWindow( _winName, _image ), th(_th) { setControls(); };
private:
string getDescription() override;
void setControls() override; //
void thresholdImage();
static void thresholdCallback( int _th, void* ); //
};
string MyThreshold::getDescription()
{
return "th " + std::to_string(th);
}
void MyThreshold::setControls() //
{
const std::string bar_name = winName + "_thBar";
cv::createTrackbar( bar_name, winName, &th, 255, thresholdCallback );
}
static void MyThreshold::thresholdCallback( int _th, void* ) //
{
th = _th;
thresholdImage();
showImage();
}
void MyThreshold::thresholdImage()
{
enum ThresholdType {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,
THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };
ThresholdType const threshold_type = BINARY;
int const max_BINARY_value = 255;
threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );
}
class MyApp : public MyWindow
{
vector<string> process;
std::unique_ptr<MyOperationWindow> current_operation;
public:
MyApp( auto _winName, auto _image) : MyWindow( _winName, _image ) {};
void showImage();
char option(auto _option);
};
static void help()
{
cout << "L (or a) - list image transformations\n"
<< "R (or s) - restore original image\n"
<< "t (or d) - activate threshold window\n"
<< "r (or f) - reset the operation window\n"
<< "(enter) (or g) - accept changes and kill the operation window\n"
<< "(backspace) (or h)- ignore changes and kill the operation window\n"
<< endl;
}
char MyApp::option( auto _option )
{
switch(_option)
{
case 't': case 'd':
/// create the threshold window
current_operation = new MyThreshold("theshold", d.image);
break;
case 'R': case 's':
/// reset the whole application
reset();
case 'r': case 'f':
/// reset the threshold window
if (current_operation)
current_operation->reset();
break;
case 'L': case 'a':
/// print the processes applied to the image until now
for (const auto& p : process)
std::cout << p << std::endl;
case 'g':
if (current_operation){
current_operation->apply(d.image, process);
delete(current_operation);
}
break;
case 'h':
if (current_operation)
delete(current_operation);
break;
}
return _option;
}
const char* keys =
{
"{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}"
};
int main( int argc, const char** argv )
{
cv::CommandLineParser parser(argc, argv, keys);
if (parser.has("help"))
{
help();
return 0;
}
std::string inputImage = parser.get<string>(0);
// Load the source image. HighGUI use.
cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );
if(image.empty())
{
std::cerr << "Cannot read image file: " << inputImage << std::endl;
return -1;
}
// TODO: check size and reduce it only if needed
cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);
help();
/// Create the GUI
std::string winName = "main window";
MyApp appHandle = MyApp(winName, image);
/// Loop until the user kills the program
const auto ESC_KEY = '\x1b';
while ( appHandle.option((char) waitKey(0)) != ESC_KEY )
{
/* until ESC */
}
std::cout << "Exit" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: stringlistitem.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-03-19 17:52:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBAUI_STRINGLISTITEM_HXX_
#define _DBAUI_STRINGLISTITEM_HXX_
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= OStringListItem
//=========================================================================
/** <type>SfxPoolItem</type> which transports a sequence of <type scope="rtl">OUString</type>'s
*/
class OStringListItem : public SfxPoolItem
{
::com::sun::star::uno::Sequence< ::rtl::OUString > m_aList;
public:
TYPEINFO();
OStringListItem(sal_Int16 nWhich, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rList);
OStringListItem(const OStringListItem& _rSource);
virtual int operator==(const SfxPoolItem& _rItem) const;
virtual SfxPoolItem* Clone(SfxItemPool* _pPool = NULL) const;
::com::sun::star::uno::Sequence< ::rtl::OUString > getList() const { return m_aList; }
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_STRINGLISTITEM_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.434); FILE MERGED 2005/09/05 17:35:01 rt 1.2.434.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stringlistitem.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:04:18 $
*
* 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 _DBAUI_STRINGLISTITEM_HXX_
#define _DBAUI_STRINGLISTITEM_HXX_
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= OStringListItem
//=========================================================================
/** <type>SfxPoolItem</type> which transports a sequence of <type scope="rtl">OUString</type>'s
*/
class OStringListItem : public SfxPoolItem
{
::com::sun::star::uno::Sequence< ::rtl::OUString > m_aList;
public:
TYPEINFO();
OStringListItem(sal_Int16 nWhich, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rList);
OStringListItem(const OStringListItem& _rSource);
virtual int operator==(const SfxPoolItem& _rItem) const;
virtual SfxPoolItem* Clone(SfxItemPool* _pPool = NULL) const;
::com::sun::star::uno::Sequence< ::rtl::OUString > getList() const { return m_aList; }
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_STRINGLISTITEM_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ToolBoxHelper.cxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: oj $ $Date: 2002-04-29 07:59:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_TOOLBOXHELPER_HXX
#include "ToolBoxHelper.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
#include <svtools/miscopt.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _SVTOOLS_IMGDEF_HXX
#include <svtools/imgdef.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
namespace dbaui
{
OToolBoxHelper::OToolBoxHelper()
: m_bIsHiContrast(sal_False)
,m_pToolBox(NULL)
,m_nBitmapSet(SFX_SYMBOLS_SMALL)
{
SvtMiscOptions().AddListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
}
// -----------------------------------------------------------------------------
OToolBoxHelper::~OToolBoxHelper()
{
SvtMiscOptions().RemoveListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
}
// -----------------------------------------------------------------------------
void OToolBoxHelper::checkImageList()
{
if ( m_pToolBox )
{
sal_Int16 nCurBitmapSet = SvtMiscOptions().GetSymbolSet();
if ( nCurBitmapSet != m_nBitmapSet ||
m_bIsHiContrast != m_pToolBox->GetBackground().GetColor().IsDark() )
{
m_nBitmapSet = nCurBitmapSet;
m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();
m_pToolBox->SetImageList( ModuleRes( getImageListId(m_nBitmapSet,m_bIsHiContrast) ) );
Size aTbOldSize = m_pToolBox->GetSizePixel();
adjustToolBoxSize(m_pToolBox);
Size aTbNewSize = m_pToolBox->GetSizePixel();
resizeControls(Size(aTbNewSize.Width() - aTbOldSize.Width(),
aTbNewSize.Height() - aTbOldSize.Height())
);
}
}
}
// -----------------------------------------------------------------------------
IMPL_LINK(OToolBoxHelper, ConfigOptionsChanged, SvtMiscOptions*, _pOptions)
{
if ( m_pToolBox )
{
SvtMiscOptions aOptions;
// check if imagelist changed
checkImageList();
if ( aOptions.GetToolboxStyle() != m_pToolBox->GetOutStyle() )
m_pToolBox->SetOutStyle(aOptions.GetToolboxStyle());
}
return 0L;
}
// -----------------------------------------------------------------------------
void OToolBoxHelper::setToolBox(ToolBox* _pTB)
{
sal_Bool bFirstTime = (m_pToolBox == NULL);
m_pToolBox = _pTB;
if ( m_pToolBox )
{
// m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();
ConfigOptionsChanged(NULL);
if ( bFirstTime )
adjustToolBoxSize(m_pToolBox);
}
}
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS os8 (1.1.68); FILE MERGED 2003/04/03 06:41:23 cd 1.1.68.1: #108520# Support automatic toolbar button size depending on menu text height<commit_after>/*************************************************************************
*
* $RCSfile: ToolBoxHelper.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2003-04-17 13:26:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_TOOLBOXHELPER_HXX
#include "ToolBoxHelper.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_MISCOPT_HXX
#include <svtools/miscopt.hxx>
#endif
#ifndef DBAUI_TOOLS_HXX
#include "UITools.hxx"
#endif
#ifndef _SVTOOLS_IMGDEF_HXX
#include <svtools/imgdef.hxx>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
namespace dbaui
{
OToolBoxHelper::OToolBoxHelper()
: m_bIsHiContrast(sal_False)
,m_pToolBox(NULL)
,m_nBitmapSet( getCurrentSymbolSet() )
{
SvtMiscOptions().AddListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
Application::AddEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );
}
// -----------------------------------------------------------------------------
OToolBoxHelper::~OToolBoxHelper()
{
SvtMiscOptions().RemoveListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );
Application::RemoveEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );
}
// -----------------------------------------------------------------------------
sal_Int16 OToolBoxHelper::getCurrentSymbolSet()
{
sal_Int16 eOptSymbolSet = SvtMiscOptions().GetSymbolSet();
if ( eOptSymbolSet == SFX_SYMBOLS_AUTO )
{
// Use system settings, we have to retrieve the toolbar icon size from the
// Application class
ULONG nStyleIconSize = Application::GetSettings().GetStyleSettings().GetToolbarIconSize();
if ( nStyleIconSize == STYLE_TOOLBAR_ICONSIZE_LARGE )
eOptSymbolSet = SFX_SYMBOLS_LARGE;
else
eOptSymbolSet = SFX_SYMBOLS_SMALL;
}
return eOptSymbolSet;
}
// -----------------------------------------------------------------------------
void OToolBoxHelper::checkImageList()
{
if ( m_pToolBox )
{
sal_Int16 nCurBitmapSet = getCurrentSymbolSet();
if ( nCurBitmapSet != m_nBitmapSet ||
m_bIsHiContrast != m_pToolBox->GetBackground().GetColor().IsDark() )
{
m_nBitmapSet = nCurBitmapSet;
m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();
m_pToolBox->SetImageList( ModuleRes( getImageListId(m_nBitmapSet,m_bIsHiContrast) ) );
Size aTbOldSize = m_pToolBox->GetSizePixel();
adjustToolBoxSize(m_pToolBox);
Size aTbNewSize = m_pToolBox->GetSizePixel();
resizeControls(Size(aTbNewSize.Width() - aTbOldSize.Width(),
aTbNewSize.Height() - aTbOldSize.Height())
);
}
}
}
// -----------------------------------------------------------------------------
IMPL_LINK(OToolBoxHelper, ConfigOptionsChanged, SvtMiscOptions*, _pOptions)
{
if ( m_pToolBox )
{
SvtMiscOptions aOptions;
// check if imagelist changed
checkImageList();
if ( aOptions.GetToolboxStyle() != m_pToolBox->GetOutStyle() )
m_pToolBox->SetOutStyle(aOptions.GetToolboxStyle());
}
return 0L;
}
// -----------------------------------------------------------------------------
IMPL_LINK(OToolBoxHelper, SettingsChanged, void*, _pVoid)
{
if ( m_pToolBox )
{
// check if imagelist changed
checkImageList();
}
return 0L;
}
// -----------------------------------------------------------------------------
void OToolBoxHelper::setToolBox(ToolBox* _pTB)
{
sal_Bool bFirstTime = (m_pToolBox == NULL);
m_pToolBox = _pTB;
if ( m_pToolBox )
{
// m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();
ConfigOptionsChanged(NULL);
if ( bFirstTime )
adjustToolBoxSize(m_pToolBox);
}
}
// -----------------------------------------------------------------------------
} // namespace
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>// Time: O(nlogn)
// Space: O(n)
// BIT solution.
class Solution {
public:
/**
* @param A an array
* @return total of reverse pairs
*/
long long reversePairs(vector<int>& A) {
// Get the place (position in the ascending order) of each number.
vector<int> sorted_A(A), places(A.size());
sort(sorted_A.begin(), sorted_A.end());
for (int i = 0; i < A.size(); ++i) {
places[i] =
lower_bound(sorted_A.begin(), sorted_A.end(), A[i]) -
sorted_A.begin();
}
// Count the smaller elements after the number.
long long count = 0;
vector<int> bit(A.size() + 1);
for (int i = A.size() - 1; i >= 0; --i) {
count += query(bit, places[i]);
add(bit, places[i] + 1, 1);
}
return count;
}
private:
void add(vector<int>& bit, int i, int val) {
for (; i < bit.size(); i += lower_bit(i)) {
bit[i] += val;
}
}
int query(const vector<int>& bit, int i) {
int sum = 0;
for (; i > 0; i -= lower_bit(i)) {
sum += bit[i];
}
return sum;
}
int lower_bit(int i) {
return i & -i;
}
};
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
/**
* @param A an array
* @return total of reverse pairs
*/
long long reversePairs(vector<int>& A) {
long long count = 0;
vector<pair<int, int>> num_idxs;
for (int i = 0; i < A.size(); ++i) {
num_idxs.emplace_back(A[i], i);
}
countAndMergeSort(&num_idxs, 0, num_idxs.size() - 1, &count);
return count;
}
private:
void countAndMergeSort(vector<pair<int, int>> *num_idxs, int start, int end, long long *count) {
if (end - start <= 0) { // The number of range [start, end] of which size is less than 2 doesn't need sort.
return;
}
int mid = start + (end - start) / 2;
countAndMergeSort(num_idxs, start, mid, count);
countAndMergeSort(num_idxs, mid + 1, end, count);
int l = start;
vector<pair<int, int>> tmp;
for (int i = mid + 1; i <= end; ++i) {
// Merge the two sorted arrays into tmp.
while (l <= mid && (*num_idxs)[l].first <= (*num_idxs)[i].first) {
tmp.emplace_back((*num_idxs)[l++]);
}
tmp.emplace_back((*num_idxs)[i]);
*count += mid - l + 1;
}
while (l <= mid) {
tmp.emplace_back((*num_idxs)[l++]);
}
// Copy tmp back to num_idxs.
copy(tmp.begin(), tmp.end(), num_idxs->begin() + start);
}
};
<commit_msg>Update reverse-pairs.cpp<commit_after>// Time: O(nlogn)
// Space: O(n)
// BIT solution.
class Solution {
public:
/**
* @param A an array
* @return total of reverse pairs
*/
long long reversePairs(vector<int>& A) {
// Get the place (position in the ascending order) of each number.
vector<int> sorted_A(A), places(A.size());
sort(sorted_A.begin(), sorted_A.end());
for (int i = 0; i < A.size(); ++i) {
places[i] =
lower_bound(sorted_A.begin(), sorted_A.end(), A[i]) -
sorted_A.begin();
}
// Count the smaller elements after the number.
long long count = 0;
vector<int> bit(A.size() + 1);
for (int i = A.size() - 1; i >= 0; --i) {
count += query(bit, places[i]);
add(bit, places[i] + 1, 1);
}
return count;
}
private:
void add(vector<int>& bit, int i, int val) {
for (; i < bit.size(); i += lower_bit(i)) {
bit[i] += val;
}
}
int query(const vector<int>& bit, int i) {
int sum = 0;
for (; i > 0; i -= lower_bit(i)) {
sum += bit[i];
}
return sum;
}
int lower_bit(int i) {
return i & -i;
}
};
// Time: O(nlogn)
// Space: O(n)
// Merge sort solution.
class Solution2 {
public:
/**
* @param A an array
* @return total of reverse pairs
*/
long long reversePairs(vector<int>& A) {
long long count = 0;
vector<pair<int, int>> num_idxs;
for (int i = 0; i < A.size(); ++i) {
num_idxs.emplace_back(A[i], i);
}
countAndMergeSort(&num_idxs, 0, num_idxs.size() - 1, &count);
return count;
}
private:
void countAndMergeSort(vector<pair<int, int>> *num_idxs, int start, int end, long long *count) {
if (end - start <= 0) { // The number of range [start, end] of which size is less than 2 doesn't need sort.
return;
}
int mid = start + (end - start) / 2;
countAndMergeSort(num_idxs, start, mid, count);
countAndMergeSort(num_idxs, mid + 1, end, count);
int l = start;
vector<pair<int, int>> tmp;
for (int i = mid + 1; i <= end; ++i) {
// Merge the two sorted arrays into tmp.
while (l <= mid && (*num_idxs)[l].first <= (*num_idxs)[i].first) {
tmp.emplace_back((*num_idxs)[l++]);
}
tmp.emplace_back((*num_idxs)[i]);
*count += mid - l + 1;
}
while (l <= mid) {
tmp.emplace_back((*num_idxs)[l++]);
}
// Copy tmp back to num_idxs.
copy(tmp.begin(), tmp.end(), num_idxs->begin() + start);
}
};
<|endoftext|> |
<commit_before>#include "main_window.hpp"
#include "key_event.hpp"
#include "open_dialog.hpp"
#include "save_dialog.hpp"
#include "text_file.hpp"
#include "dialog.hpp"
#include "application.hpp"
MainWindow::MainWindow(Widget *parent):
Widget(parent),
screen_(this),
tabs_(this),
statusBar_(this),
layout_(Layout::Vertical)
{
connect(SIGNAL(&tabs_, setTextBuffer), SLOT(&screen_, setTextBuffer));
screen_.setStatusBar(&statusBar_);
setLayout(&layout_);
layout_.addWidget(&tabs_);
layout_.addWidget(&screen_);
layout_.addWidget(&statusBar_);
screen_.setFocus();
}
bool MainWindow::keyPressEvent(KeyEvent &e)
{
bool result1 = true;
switch (e.modifiers())
{
case KeyEvent::MLCtrl:
case KeyEvent::MRCtrl:
switch (e.key())
{
case KeyEvent::KO:
{
auto openDialog = new OpenDialog(&screen_);
connect(SIGNAL(openDialog, openFile), SLOT(this, openFile));
tabs_.addTextBuffer(openDialog);
break;
}
case KeyEvent::KS:
save();
break;
case KeyEvent::KN:
tabs_.addTextBuffer(new TextFile);
break;
case KeyEvent::KW:
if (dynamic_cast<TextFile *>(tabs_.activeTextBuffer()) && tabs_.activeTextBuffer()->isModified())
{
if (!statusBar_.textBuffer())
{
auto d = new Dialog(L"The file is modified. Do you want to save it before closing?");
statusBar_.setTextBuffer(d);
connect(SIGNAL(d, result), SLOT(this, closeActiveTextBuffer));
}
}
else
tabs_.closeActiveTextBuffer();
break;
case KeyEvent::KLeft:
tabs_.switchToPrevTextBuffer();
break;
case KeyEvent::KRight:
tabs_.switchToNextTextBuffer();
break;
default:
result1 = false;
}
default:
result1 = false;
}
bool result2 = true;
if ((e.modifiers() & KeyEvent::MCtrl) != 0 && (e.modifiers() & KeyEvent::MShift) != 0)
{
switch (e.key())
{
case KeyEvent::KLeft:
tabs_.moveTextBufferLeft();
break;
case KeyEvent::KRight:
tabs_.moveTextBufferRight();
break;
default:
result2 = false;
}
}
else
result2 = false;
return result1 || result2;
}
void MainWindow::openFile(OpenDialog *sender, std::string fileName)
{
tabs_.closeTextBuffer(sender);
tabs_.addTextBuffer(new TextFile(fileName));
}
void MainWindow::saveAs(SaveDialog *sender, TextFile *textFile, std::string fileName)
{
tabs_.closeTextBuffer(sender);
tabs_.setActiveTextBuffer(textFile);
textFile->saveAs(fileName);
}
void MainWindow::saveAndClose(SaveDialog *sender, TextFile *textFile, std::string fileName)
{
tabs_.closeTextBuffer(sender);
tabs_.closeTextBuffer(textFile);
textFile->saveAs(fileName);
}
void MainWindow::closeActiveTextBuffer(Dialog::Answer value)
{
auto d = statusBar_.textBuffer();
Application::instance()->queueDelete(d);
statusBar_.setTextBuffer(nullptr);
if (auto textFile = dynamic_cast<TextFile *>(screen_.textBuffer()))
{
switch (value)
{
case Dialog::Yes:
if (textFile->fileName().empty())
{
auto saveDialog = new SaveDialog(&screen_, textFile);
tabs_.addTextBuffer(saveDialog);
connect(SIGNAL(saveDialog, saveAs), SLOT(this, saveAndClose));
}
else
{
textFile->save();
tabs_.closeActiveTextBuffer();
}
break;
case Dialog::No:
tabs_.closeActiveTextBuffer();
break;
case Dialog::Cancel:
break;
}
tabs_.update();
}
}
void MainWindow::save()
{
if (auto textFile = dynamic_cast<TextFile *>(screen_.textBuffer()))
{
if (textFile->fileName().empty())
{
auto saveDialog = new SaveDialog(&screen_, textFile);
tabs_.addTextBuffer(saveDialog);
connect(SIGNAL(saveDialog, saveAs), SLOT(this, saveAs));
}
else
textFile->save();
tabs_.update();
}
}
<commit_msg>Set the cursor on the second line in the save dialog<commit_after>#include "main_window.hpp"
#include "key_event.hpp"
#include "open_dialog.hpp"
#include "save_dialog.hpp"
#include "text_file.hpp"
#include "dialog.hpp"
#include "application.hpp"
MainWindow::MainWindow(Widget *parent):
Widget(parent),
screen_(this),
tabs_(this),
statusBar_(this),
layout_(Layout::Vertical)
{
connect(SIGNAL(&tabs_, setTextBuffer), SLOT(&screen_, setTextBuffer));
screen_.setStatusBar(&statusBar_);
setLayout(&layout_);
layout_.addWidget(&tabs_);
layout_.addWidget(&screen_);
layout_.addWidget(&statusBar_);
screen_.setFocus();
}
bool MainWindow::keyPressEvent(KeyEvent &e)
{
bool result1 = true;
switch (e.modifiers())
{
case KeyEvent::MLCtrl:
case KeyEvent::MRCtrl:
switch (e.key())
{
case KeyEvent::KO:
{
auto openDialog = new OpenDialog(&screen_);
connect(SIGNAL(openDialog, openFile), SLOT(this, openFile));
tabs_.addTextBuffer(openDialog);
break;
}
case KeyEvent::KS:
save();
break;
case KeyEvent::KN:
tabs_.addTextBuffer(new TextFile);
break;
case KeyEvent::KW:
if (dynamic_cast<TextFile *>(tabs_.activeTextBuffer()) && tabs_.activeTextBuffer()->isModified())
{
if (!statusBar_.textBuffer())
{
auto d = new Dialog(L"The file is modified. Do you want to save it before closing?");
statusBar_.setTextBuffer(d);
connect(SIGNAL(d, result), SLOT(this, closeActiveTextBuffer));
}
}
else
tabs_.closeActiveTextBuffer();
break;
case KeyEvent::KLeft:
tabs_.switchToPrevTextBuffer();
break;
case KeyEvent::KRight:
tabs_.switchToNextTextBuffer();
break;
default:
result1 = false;
}
default:
result1 = false;
}
bool result2 = true;
if ((e.modifiers() & KeyEvent::MCtrl) != 0 && (e.modifiers() & KeyEvent::MShift) != 0)
{
switch (e.key())
{
case KeyEvent::KLeft:
tabs_.moveTextBufferLeft();
break;
case KeyEvent::KRight:
tabs_.moveTextBufferRight();
break;
default:
result2 = false;
}
}
else
result2 = false;
return result1 || result2;
}
void MainWindow::openFile(OpenDialog *sender, std::string fileName)
{
tabs_.closeTextBuffer(sender);
tabs_.addTextBuffer(new TextFile(fileName));
}
void MainWindow::saveAs(SaveDialog *sender, TextFile *textFile, std::string fileName)
{
tabs_.closeTextBuffer(sender);
tabs_.setActiveTextBuffer(textFile);
textFile->saveAs(fileName);
}
void MainWindow::saveAndClose(SaveDialog *sender, TextFile *textFile, std::string fileName)
{
tabs_.closeTextBuffer(sender);
tabs_.closeTextBuffer(textFile);
textFile->saveAs(fileName);
}
void MainWindow::closeActiveTextBuffer(Dialog::Answer value)
{
auto d = statusBar_.textBuffer();
Application::instance()->queueDelete(d);
statusBar_.setTextBuffer(nullptr);
if (auto textFile = dynamic_cast<TextFile *>(screen_.textBuffer()))
{
switch (value)
{
case Dialog::Yes:
if (textFile->fileName().empty())
{
auto saveDialog = new SaveDialog(&screen_, textFile);
tabs_.addTextBuffer(saveDialog);
screen_.setCursor(0, 1);
connect(SIGNAL(saveDialog, saveAs), SLOT(this, saveAndClose));
}
else
{
textFile->save();
tabs_.closeActiveTextBuffer();
}
break;
case Dialog::No:
tabs_.closeActiveTextBuffer();
break;
case Dialog::Cancel:
break;
}
tabs_.update();
}
}
void MainWindow::save()
{
if (auto textFile = dynamic_cast<TextFile *>(screen_.textBuffer()))
{
if (textFile->fileName().empty())
{
auto saveDialog = new SaveDialog(&screen_, textFile);
tabs_.addTextBuffer(saveDialog);
screen_.setCursor(0, 1);
connect(SIGNAL(saveDialog, saveAs), SLOT(this, saveAs));
}
else
textFile->save();
tabs_.update();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Milian Wolff <[email protected]>
*
* This program 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 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 <cstdio>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <atomic>
#include <mutex>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
#include <tuple>
#include <boost/functional/hash.hpp>
#include <dlfcn.h>
#include <unistd.h>
#include <link.h>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
using namespace std;
using Trace = vector<unw_word_t>;
namespace std {
template<>
struct hash<Trace>
{
size_t operator() (const Trace& trace) const
{
std::size_t seed = 0;
for (auto ip : trace) {
boost::hash_combine(seed, ip);
}
return seed;
}
};
}
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
atomic<unsigned int> next_thread_id(0);
atomic<unsigned int> next_module_id(1);
atomic<unsigned int> next_ipCache_id(0);
atomic<unsigned int> next_trace_id(0);
struct ThreadData;
/**
* Central thread registry.
*
* All functions are threadsafe.
*/
class ThreadRegistry
{
public:
void addThread(ThreadData* thread)
{
lock_guard<mutex> lock(m_mutex);
m_threads.push_back(thread);
}
void removeThread(ThreadData* thread)
{
lock_guard<mutex> lock(m_mutex);
m_threads.erase(remove(m_threads.begin(), m_threads.end(), thread), m_threads.end());
}
/**
* Mark the module cache of all threads dirty.
*/
void setModuleCacheDirty();
private:
mutex m_mutex;
vector<ThreadData*> m_threads;
};
ThreadRegistry threadRegistry;
// must be kept separately from ThreadData to ensure it stays valid
// even until after ThreadData is destroyed
thread_local bool in_handler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
struct Module
{
string fileName;
uintptr_t baseAddress;
uint32_t size;
unsigned int id;
bool isExe;
bool operator<(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) < make_tuple(module.baseAddress, module.size, module.fileName);
}
bool operator!=(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) != make_tuple(module.baseAddress, module.size, module.fileName);
}
};
//TODO: merge per-thread output into single file
struct ThreadData
{
ThreadData()
: thread_id(next_thread_id++)
, out(nullptr)
, moduleCacheDirty(true)
{
bool wasInHandler = in_handler;
in_handler = true;
threadRegistry.addThread(this);
modules.reserve(32);
ipCache.reserve(65536);
traceCache.reserve(16384);
allocationInfo.reserve(16384);
string outputFileName = env("DUMP_MALLOC_TRACE_OUTPUT") + to_string(getpid()) + '.' + to_string(thread_id);
out = fopen(outputFileName.c_str(), "wa");
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
in_handler = wasInHandler;
}
~ThreadData()
{
in_handler = true;
threadRegistry.removeThread(this);
fclose(out);
}
void updateModuleCache()
{
// check list of loaded modules for unknown ones
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *data)
{
auto threadData = reinterpret_cast<ThreadData*>(data);
auto& modules = threadData->modules;
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (modules.empty()) {
isExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
uintptr_t addressStart = 0;
uintptr_t addressEnd = 0;
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
if (addressEnd == 0) {
addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
} else {
uintptr_t addr = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr + info->dlpi_phdr[i].p_memsz;
if (addr > addressEnd) {
addressEnd = addr;
}
}
}
}
Module module{fileName, addressStart, static_cast<uint32_t>(addressEnd - addressStart), 0, isExe};
auto it = lower_bound(modules.begin(), modules.end(), module);
if (it == modules.end() || *it != module) {
module.id = next_module_id++;
fprintf(threadData->out, "m %u %s %lx %d\n", module.id, module.fileName.c_str(), module.baseAddress, module.isExe);
modules.insert(it, module);
}
return 0;
}
unsigned int trace(const int skip = 2)
{
unw_context_t uc;
unw_getcontext (&uc);
unw_cursor_t cursor;
unw_init_local (&cursor, &uc);
// skip functions we are not interested in
for (int i = 0; i < skip; ++i) {
if (unw_step(&cursor) <= 0) {
return 0;
}
}
traceBuffer.clear();
const size_t MAX_TRACE_SIZE = 64;
while (unw_step(&cursor) > 0 && traceBuffer.size() < MAX_TRACE_SIZE) {
unw_word_t ip;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
auto it = ipCache.find(ip);
if (it == ipCache.end()) {
auto ipId = next_ipCache_id++;
// find module and offset from cache
auto module = lower_bound(modules.begin(), modules.end(), ip,
[] (const Module& module, const unw_word_t addr) -> bool {
return module.baseAddress + module.size < addr;
});
if (module != modules.end()) {
fprintf(out, "i %lu %lu %lx\n", ipId, module->id, ip - module->baseAddress);
} else {
fprintf(out, "i %lu 0 %lx\n", ipId, ip);
}
it = ipCache.insert(it, {ip, ipId});
}
traceBuffer.push_back(it->second);
}
auto it = traceCache.find(traceBuffer);
if (it == traceCache.end()) {
auto traceId = next_trace_id++;
it = traceCache.insert(it, {traceBuffer, traceId});
fprintf(out, "t %lu ", traceId);
for (auto ipId : traceBuffer) {
fprintf(out, "%lu ", ipId);
}
fputc('\n', out);
}
return it->second;
}
void handleMalloc(void* ptr, size_t size)
{
if (moduleCacheDirty) {
updateModuleCache();
}
auto traceId = trace();
if (!traceId) {
return;
}
allocationInfo[ptr] = {size, traceId};
fprintf(out, "+ %lu %lu\n", size, traceId);
}
void handleFree(void* ptr)
{
auto it = allocationInfo.find(ptr);
if (it == allocationInfo.end()) {
return;
}
fprintf(out, "- %lu %lu\n", it->second.size, it->second.traceId);
allocationInfo.erase(it);
}
vector<Module> modules;
unordered_map<unw_word_t, unw_word_t> ipCache;
unordered_map<vector<unw_word_t>, unsigned int> traceCache;
struct AllocationInfo
{
size_t size;
unsigned int traceId;
};
unordered_map<void*, AllocationInfo> allocationInfo;
unsigned int thread_id;
FILE* out;
atomic<bool> moduleCacheDirty;
vector<unw_word_t> traceBuffer;
};
void ThreadRegistry::setModuleCacheDirty()
{
lock_guard<mutex> lock(m_mutex);
for (auto t : m_threads) {
t->moduleCacheDirty = true;
}
}
thread_local ThreadData threadData;
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "could not find original function %s\n", name);
exit(1);
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
exit(1);
}
return buf + oldOffset;
}
void init()
{
if (in_handler) {
fprintf(stderr, "initialization recursion detected\n");
exit(1);
}
in_handler = true;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
in_handler = false;
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !in_handler) {
in_handler = true;
threadData.handleMalloc(ret, size);
in_handler = false;
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
real_free(ptr);
if (ptr && !in_handler) {
in_handler = true;
threadData.handleFree(ptr);
in_handler = false;
}
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !in_handler) {
in_handler = true;
threadData.handleFree(ptr);
threadData.handleMalloc(ret, size);
in_handler = false;
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !in_handler) {
in_handler = true;
threadData.handleMalloc(ret, num*size);
in_handler = false;
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (ret && !in_handler) {
in_handler = true;
threadData.handleMalloc(*memptr, size);
in_handler = false;
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !in_handler) {
in_handler = true;
threadData.handleMalloc(ret, size);
in_handler = false;
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !in_handler) {
in_handler = true;
threadData.handleMalloc(ret, size);
in_handler = false;
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret && !in_handler) {
threadRegistry.setModuleCacheDirty();
}
return ret;
}
}
<commit_msg>Refactor malloc tracing, synchronize most of the stuff after all.<commit_after>/*
* Copyright 2014 Milian Wolff <[email protected]>
*
* This program 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 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 <cstdio>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <atomic>
#include <mutex>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
#include <tuple>
#include <boost/functional/hash.hpp>
#include <dlfcn.h>
#include <unistd.h>
#include <link.h>
#define UNW_LOCAL_ONLY
#include <libunwind.h>
using namespace std;
using Trace = vector<unw_word_t>;
namespace std {
template<>
struct hash<Trace>
{
size_t operator() (const Trace& trace) const
{
size_t seed = 0;
for (auto ip : trace) {
boost::hash_combine(seed, ip);
}
return seed;
}
};
}
namespace {
using malloc_t = void* (*) (size_t);
using free_t = void (*) (void*);
using realloc_t = void* (*) (void*, size_t);
using calloc_t = void* (*) (size_t, size_t);
using posix_memalign_t = int (*) (void **, size_t, size_t);
using valloc_t = void* (*) (size_t);
using aligned_alloc_t = void* (*) (size_t, size_t);
using dlopen_t = void* (*) (const char*, int);
malloc_t real_malloc = nullptr;
free_t real_free = nullptr;
realloc_t real_realloc = nullptr;
calloc_t real_calloc = nullptr;
posix_memalign_t real_posix_memalign = nullptr;
valloc_t real_valloc = nullptr;
aligned_alloc_t real_aligned_alloc = nullptr;
dlopen_t real_dlopen = nullptr;
// threadsafe stuff
atomic<bool> moduleCacheDirty(true);
thread_local Trace traceBuffer;
void trace(const int skip = 2)
{
traceBuffer.clear();
unw_context_t uc;
unw_getcontext (&uc);
unw_cursor_t cursor;
unw_init_local (&cursor, &uc);
// skip functions we are not interested in
for (int i = 0; i < skip; ++i) {
if (unw_step(&cursor) <= 0) {
return;
}
}
const size_t MAX_TRACE_SIZE = 64;
while (unw_step(&cursor) > 0 && traceBuffer.size() < MAX_TRACE_SIZE) {
unw_word_t ip;
unw_get_reg(&cursor, UNW_REG_IP, &ip);
traceBuffer.push_back(ip);
}
}
struct HandleGuard
{
HandleGuard()
: wasLocked(inHandler)
{
inHandler = true;
}
~HandleGuard()
{
inHandler = wasLocked;
}
const bool wasLocked;
static thread_local bool inHandler;
};
thread_local bool HandleGuard::inHandler = false;
string env(const char* variable)
{
const char* value = getenv(variable);
return value ? string(value) : string();
}
struct Module
{
string fileName;
uintptr_t baseAddress;
uint32_t size;
unsigned int id;
bool isExe;
bool operator<(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) < make_tuple(module.baseAddress, module.size, module.fileName);
}
bool operator!=(const Module& module) const
{
return make_tuple(baseAddress, size, fileName) != make_tuple(module.baseAddress, module.size, module.fileName);
}
};
struct Data
{
Data()
{
modules.reserve(32);
ipCache.reserve(65536);
traceCache.reserve(16384);
allocationInfo.reserve(16384);
string outputFileName = env("DUMP_MALLOC_TRACE_OUTPUT") + to_string(getpid());
out = fopen(outputFileName.c_str(), "wa");
if (!out) {
fprintf(stderr, "Failed to open output file: %s\n", outputFileName.c_str());
exit(1);
}
}
~Data()
{
HandleGuard::inHandler = true;
fclose(out);
}
void updateModuleCache()
{
// check list of loaded modules for unknown ones
dl_iterate_phdr(dlopen_notify_callback, this);
moduleCacheDirty = false;
}
/**
* Mostly copied from vogl's src/libbacktrace/btrace.cpp
*/
static int dlopen_notify_callback(struct dl_phdr_info *info, size_t /*size*/, void *_data)
{
auto data = reinterpret_cast<Data*>(_data);
auto& modules = data->modules;
bool isExe = false;
const char *fileName = info->dlpi_name;
const int BUF_SIZE = 1024;
char buf[BUF_SIZE];
// If we don't have a filename and we haven't added our main exe yet, do it now.
if (!fileName || !fileName[0]) {
if (modules.empty()) {
isExe = true;
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if ((ret > 0) && (ret < (ssize_t)sizeof(buf))) {
buf[ret] = 0;
fileName = buf;
}
}
if (!fileName || !fileName[0]) {
return 0;
}
}
uintptr_t addressStart = 0;
uintptr_t addressEnd = 0;
for (int i = 0; i < info->dlpi_phnum; i++) {
if (info->dlpi_phdr[i].p_type == PT_LOAD) {
if (addressEnd == 0) {
addressStart = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr;
addressEnd = addressStart + info->dlpi_phdr[i].p_memsz;
} else {
uintptr_t addr = info->dlpi_addr + info->dlpi_phdr[i].p_vaddr + info->dlpi_phdr[i].p_memsz;
if (addr > addressEnd) {
addressEnd = addr;
}
}
}
}
Module module{fileName, addressStart, static_cast<uint32_t>(addressEnd - addressStart), 0, isExe};
auto it = lower_bound(modules.begin(), modules.end(), module);
if (it == modules.end() || *it != module) {
module.id = data->next_module_id++;
fprintf(data->out, "m %u %s %lx %d\n", module.id, module.fileName.c_str(), module.baseAddress, module.isExe);
modules.insert(it, module);
}
return 0;
}
void handleMalloc(void* ptr, size_t size)
{
trace();
lock_guard<mutex> lock(m_mutex);
if (moduleCacheDirty) {
updateModuleCache();
}
auto it = traceCache.find(traceBuffer);
if (it == traceCache.end()) {
// cache before converting
auto traceId = next_trace_id++;
it = traceCache.insert(it, {traceBuffer, traceId});
// ensure ip cache is up2date
for (auto& ip : traceBuffer) {
auto ipIt = ipCache.find(ip);
if (ipIt == ipCache.end()) {
auto ipId = next_ipCache_id++;
// find module and offset from cache
auto module = lower_bound(modules.begin(), modules.end(), ip,
[] (const Module& module, const unw_word_t addr) -> bool {
return module.baseAddress + module.size < addr;
});
if (module != modules.end()) {
fprintf(out, "i %u %u %lx\n", ipId, module->id, ip - module->baseAddress);
} else {
fprintf(out, "i %u 0 %lx\n", ipId, ip);
}
ipIt = ipCache.insert(ipIt, {ip, ipId});
}
ip = ipIt->second;
}
// print trace
fprintf(out, "t %u ", traceId);
for (auto ipId : traceBuffer) {
fprintf(out, "%lu ", ipId);
}
fputc('\n', out);
}
allocationInfo[ptr] = {size, it->second};
fprintf(out, "+ %lu %u\n", size, it->second);
}
void handleFree(void* ptr)
{
lock_guard<mutex> lock(m_mutex);
auto it = allocationInfo.find(ptr);
if (it == allocationInfo.end()) {
return;
}
fprintf(out, "- %lu %u\n", it->second.size, it->second.traceId);
allocationInfo.erase(it);
}
mutex m_mutex;
unsigned int next_module_id = 1;
unsigned int next_thread_id = 0;
unsigned int next_ipCache_id = 0;
unsigned int next_trace_id = 0;
vector<Module> modules;
unordered_map<unw_word_t, unw_word_t> ipCache;
unordered_map<vector<unw_word_t>, unsigned int> traceCache;
struct AllocationInfo
{
size_t size;
unsigned int traceId;
};
unordered_map<void*, AllocationInfo> allocationInfo;
FILE* out = nullptr;
};
unique_ptr<Data> data;
template<typename T>
T findReal(const char* name)
{
auto ret = dlsym(RTLD_NEXT, name);
if (!ret) {
fprintf(stderr, "Could not find original function %s\n", name);
exit(1);
}
return reinterpret_cast<T>(ret);
}
/**
* Dummy implementation, since the call to dlsym from findReal triggers a call to calloc.
*
* This is only called at startup and will eventually be replaced by the "proper" calloc implementation.
*/
void* dummy_calloc(size_t num, size_t size)
{
const size_t MAX_SIZE = 1024;
static char* buf[MAX_SIZE];
static size_t offset = 0;
if (!offset) {
memset(buf, 0, MAX_SIZE);
}
size_t oldOffset = offset;
offset += num * size;
if (offset >= MAX_SIZE) {
fprintf(stderr, "failed to initialize, dummy calloc buf size exhausted: %lu requested, %lu available\n", offset, MAX_SIZE);
exit(1);
}
return buf + oldOffset;
}
void init()
{
if (data || HandleGuard::inHandler) {
fprintf(stderr, "initialization recursion detected\n");
exit(1);
}
HandleGuard guard;
real_calloc = &dummy_calloc;
real_calloc = findReal<calloc_t>("calloc");
real_dlopen = findReal<dlopen_t>("dlopen");
real_malloc = findReal<malloc_t>("malloc");
real_free = findReal<free_t>("free");
real_realloc = findReal<realloc_t>("realloc");
real_posix_memalign = findReal<posix_memalign_t>("posix_memalign");
real_valloc = findReal<valloc_t>("valloc");
real_aligned_alloc = findReal<aligned_alloc_t>("aligned_alloc");
data.reset(new Data);
}
}
extern "C" {
/// TODO: memalign, pvalloc, ...?
void* malloc(size_t size)
{
if (!real_malloc) {
init();
}
void* ret = real_malloc(size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void free(void* ptr)
{
if (!real_free) {
init();
}
real_free(ptr);
if (ptr && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleFree(ptr);
}
}
void* realloc(void* ptr, size_t size)
{
if (!real_realloc) {
init();
}
void* ret = real_realloc(ptr, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleFree(ptr);
data->handleMalloc(ret, size);
}
return ret;
}
void* calloc(size_t num, size_t size)
{
if (!real_calloc) {
init();
}
void* ret = real_calloc(num, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, num*size);
}
return ret;
}
int posix_memalign(void **memptr, size_t alignment, size_t size)
{
if (!real_posix_memalign) {
init();
}
int ret = real_posix_memalign(memptr, alignment, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(*memptr, size);
}
return ret;
}
void* aligned_alloc(size_t alignment, size_t size)
{
if (!real_aligned_alloc) {
init();
}
void* ret = real_aligned_alloc(alignment, size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void* valloc(size_t size)
{
if (!real_valloc) {
init();
}
void* ret = real_valloc(size);
if (ret && !HandleGuard::inHandler) {
HandleGuard guard;
data->handleMalloc(ret, size);
}
return ret;
}
void *dlopen(const char *filename, int flag)
{
if (!real_dlopen) {
init();
}
void* ret = real_dlopen(filename, flag);
if (ret) {
moduleCacheDirty = true;
}
return ret;
}
}
<|endoftext|> |
<commit_before><commit_msg>Skip non-interface points in symbolic square analysis phase<commit_after><|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XalanSourceTreeText.hpp"
#include <XalanDOM/XalanDOMException.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include "XalanSourceTreeComment.hpp"
#include "XalanSourceTreeElement.hpp"
#include "XalanSourceTreeProcessingInstruction.hpp"
#include "XalanSourceTreeHelper.hpp"
static const XalanDOMString s_emptyString;
XalanSourceTreeText::XalanSourceTreeText(
const XalanDOMString& theData,
XalanSourceTreeElement* theParentElement,
XalanNode* thePreviousSibling,
XalanNode* theNextSibling,
unsigned int theIndex) :
XalanText(),
m_data(theData),
m_parentElement(theParentElement),
m_previousSibling(thePreviousSibling),
m_nextSibling(theNextSibling),
m_index(theIndex)
{
}
XalanSourceTreeText::~XalanSourceTreeText()
{
}
XalanSourceTreeText::XalanSourceTreeText(
const XalanSourceTreeText& theSource,
bool /* deep */) :
XalanText(theSource),
m_data(theSource.m_data),
m_parentElement(0),
m_previousSibling(0),
m_nextSibling(0),
m_index(0)
{
}
const XalanDOMString&
XalanSourceTreeText::getNodeName() const
{
return s_nameString;
}
const XalanDOMString&
XalanSourceTreeText::getNodeValue() const
{
return m_data;
}
XalanSourceTreeText::NodeType
XalanSourceTreeText::getNodeType() const
{
return TEXT_NODE;
}
XalanNode*
XalanSourceTreeText::getParentNode() const
{
return m_parentElement;
}
const XalanNodeList*
XalanSourceTreeText::getChildNodes() const
{
return 0;
}
XalanNode*
XalanSourceTreeText::getFirstChild() const
{
return 0;
}
XalanNode*
XalanSourceTreeText::getLastChild() const
{
return 0;
}
XalanNode*
XalanSourceTreeText::getPreviousSibling() const
{
return m_previousSibling;
}
XalanNode*
XalanSourceTreeText::getNextSibling() const
{
return m_nextSibling;
}
const XalanNamedNodeMap*
XalanSourceTreeText::getAttributes() const
{
return 0;
}
XalanDocument*
XalanSourceTreeText::getOwnerDocument() const
{
assert(m_parentElement != 0);
return m_parentElement->getOwnerDocument();
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
XalanNode*
#else
XalanSourceTreeText*
#endif
XalanSourceTreeText::cloneNode(bool deep) const
{
return new XalanSourceTreeText(*this, deep);
}
XalanNode*
XalanSourceTreeText::insertBefore(
XalanNode* /* newChild */,
XalanNode* /* refChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
XalanNode*
XalanSourceTreeText::replaceChild(
XalanNode* /* newChild */,
XalanNode* /* oldChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
XalanNode*
XalanSourceTreeText::removeChild(XalanNode* /* oldChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
XalanNode*
XalanSourceTreeText::appendChild(XalanNode* /* newChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
bool
XalanSourceTreeText::hasChildNodes() const
{
return false;
}
void
XalanSourceTreeText::setNodeValue(const XalanDOMString& /* nodeValue */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::normalize()
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
bool
XalanSourceTreeText::supports(
const XalanDOMString& /* feature */,
const XalanDOMString& /* version */) const
{
return false;
}
const XalanDOMString&
XalanSourceTreeText::getNamespaceURI() const
{
return s_emptyString;
}
const XalanDOMString&
XalanSourceTreeText::getPrefix() const
{
return s_emptyString;
}
const XalanDOMString&
XalanSourceTreeText::getLocalName() const
{
return s_emptyString;
}
void
XalanSourceTreeText::setPrefix(const XalanDOMString& /* prefix */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
bool
XalanSourceTreeText::isIndexed() const
{
return true;
}
unsigned long
XalanSourceTreeText::getIndex() const
{
return m_index;
}
const XalanDOMString&
XalanSourceTreeText::getData() const
{
return m_data;
}
unsigned int
XalanSourceTreeText::getLength() const
{
return length(m_data);
}
XalanDOMString
XalanSourceTreeText::substringData(
unsigned int offset,
unsigned int count) const
{
return substring(m_data, offset, count);
}
void
XalanSourceTreeText::appendData(const XalanDOMString& /* arg */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::insertData(
unsigned int /* offset */,
const XalanDOMString& /* arg */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::deleteData(
unsigned int /* offset */,
unsigned int /* count */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::replaceData(
unsigned int /* offset */,
unsigned int /* count */,
const XalanDOMString& /* arg */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
XalanText*
XalanSourceTreeText::splitText(unsigned int /* offset */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
bool
XalanSourceTreeText::isIgnorableWhitespace() const
{
return false;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeComment* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeElement* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeProcessingInstruction* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeText* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeComment* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeElement* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeProcessingInstruction* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeText* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
static XalanDOMString s_nameString;
const XalanDOMString& XalanSourceTreeText::s_nameString = ::s_nameString;
void
XalanSourceTreeText::initialize()
{
::s_nameString = XALAN_STATIC_UCODE_STRING("#text");
}
void
XalanSourceTreeText::terminate()
{
clear(::s_nameString);
}
<commit_msg>Return type required for non-void functions. Warning on HP.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XalanSourceTreeText.hpp"
#include <XalanDOM/XalanDOMException.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include "XalanSourceTreeComment.hpp"
#include "XalanSourceTreeElement.hpp"
#include "XalanSourceTreeProcessingInstruction.hpp"
#include "XalanSourceTreeHelper.hpp"
static const XalanDOMString s_emptyString;
XalanSourceTreeText::XalanSourceTreeText(
const XalanDOMString& theData,
XalanSourceTreeElement* theParentElement,
XalanNode* thePreviousSibling,
XalanNode* theNextSibling,
unsigned int theIndex) :
XalanText(),
m_data(theData),
m_parentElement(theParentElement),
m_previousSibling(thePreviousSibling),
m_nextSibling(theNextSibling),
m_index(theIndex)
{
}
XalanSourceTreeText::~XalanSourceTreeText()
{
}
XalanSourceTreeText::XalanSourceTreeText(
const XalanSourceTreeText& theSource,
bool /* deep */) :
XalanText(theSource),
m_data(theSource.m_data),
m_parentElement(0),
m_previousSibling(0),
m_nextSibling(0),
m_index(0)
{
}
const XalanDOMString&
XalanSourceTreeText::getNodeName() const
{
return s_nameString;
}
const XalanDOMString&
XalanSourceTreeText::getNodeValue() const
{
return m_data;
}
XalanSourceTreeText::NodeType
XalanSourceTreeText::getNodeType() const
{
return TEXT_NODE;
}
XalanNode*
XalanSourceTreeText::getParentNode() const
{
return m_parentElement;
}
const XalanNodeList*
XalanSourceTreeText::getChildNodes() const
{
return 0;
}
XalanNode*
XalanSourceTreeText::getFirstChild() const
{
return 0;
}
XalanNode*
XalanSourceTreeText::getLastChild() const
{
return 0;
}
XalanNode*
XalanSourceTreeText::getPreviousSibling() const
{
return m_previousSibling;
}
XalanNode*
XalanSourceTreeText::getNextSibling() const
{
return m_nextSibling;
}
const XalanNamedNodeMap*
XalanSourceTreeText::getAttributes() const
{
return 0;
}
XalanDocument*
XalanSourceTreeText::getOwnerDocument() const
{
assert(m_parentElement != 0);
return m_parentElement->getOwnerDocument();
}
#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
XalanNode*
#else
XalanSourceTreeText*
#endif
XalanSourceTreeText::cloneNode(bool deep) const
{
return new XalanSourceTreeText(*this, deep);
}
XalanNode*
XalanSourceTreeText::insertBefore(
XalanNode* /* newChild */,
XalanNode* /* refChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
XalanNode*
XalanSourceTreeText::replaceChild(
XalanNode* /* newChild */,
XalanNode* /* oldChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
XalanNode*
XalanSourceTreeText::removeChild(XalanNode* /* oldChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
XalanNode*
XalanSourceTreeText::appendChild(XalanNode* /* newChild */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
// Dummy return value...
return 0;
}
bool
XalanSourceTreeText::hasChildNodes() const
{
return false;
}
void
XalanSourceTreeText::setNodeValue(const XalanDOMString& /* nodeValue */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::normalize()
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
bool
XalanSourceTreeText::supports(
const XalanDOMString& /* feature */,
const XalanDOMString& /* version */) const
{
return false;
}
const XalanDOMString&
XalanSourceTreeText::getNamespaceURI() const
{
return s_emptyString;
}
const XalanDOMString&
XalanSourceTreeText::getPrefix() const
{
return s_emptyString;
}
const XalanDOMString&
XalanSourceTreeText::getLocalName() const
{
return s_emptyString;
}
void
XalanSourceTreeText::setPrefix(const XalanDOMString& /* prefix */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
bool
XalanSourceTreeText::isIndexed() const
{
return true;
}
unsigned long
XalanSourceTreeText::getIndex() const
{
return m_index;
}
const XalanDOMString&
XalanSourceTreeText::getData() const
{
return m_data;
}
unsigned int
XalanSourceTreeText::getLength() const
{
return length(m_data);
}
XalanDOMString
XalanSourceTreeText::substringData(
unsigned int offset,
unsigned int count) const
{
return substring(m_data, offset, count);
}
void
XalanSourceTreeText::appendData(const XalanDOMString& /* arg */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::insertData(
unsigned int /* offset */,
const XalanDOMString& /* arg */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::deleteData(
unsigned int /* offset */,
unsigned int /* count */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
void
XalanSourceTreeText::replaceData(
unsigned int /* offset */,
unsigned int /* count */,
const XalanDOMString& /* arg */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
}
XalanText*
XalanSourceTreeText::splitText(unsigned int /* offset */)
{
throw XalanDOMException(XalanDOMException::NO_MODIFICATION_ALLOWED_ERR);
return 0;
}
bool
XalanSourceTreeText::isIgnorableWhitespace() const
{
return false;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeComment* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeElement* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeProcessingInstruction* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::setPreviousSibling(XalanSourceTreeText* thePreviousSibling)
{
m_previousSibling = thePreviousSibling;
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeComment* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeElement* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeProcessingInstruction* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
void
XalanSourceTreeText::appendSiblingNode(XalanSourceTreeText* theSibling)
{
XalanSourceTreeHelper::appendSibling(this, m_nextSibling, theSibling);
}
static XalanDOMString s_nameString;
const XalanDOMString& XalanSourceTreeText::s_nameString = ::s_nameString;
void
XalanSourceTreeText::initialize()
{
::s_nameString = XALAN_STATIC_UCODE_STRING("#text");
}
void
XalanSourceTreeText::terminate()
{
clear(::s_nameString);
}
<|endoftext|> |
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program 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.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "ed2nav.h"
#include "conf.h"
#include "utils/timer.h"
#include "utils/exception.h"
#include "ed_reader.h"
#include "type/data.h"
#include "utils/init.h"
#include "utils/functions.h"
#include "type/meta_data.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
#include <pqxx/pqxx>
#include <iostream>
#include <fstream>
namespace po = boost::program_options;
namespace pt = boost::posix_time;
namespace georef = navitia::georef;
namespace ed {
// A functor that first asks to GeoRef the admins of coord, and, if
// GeoRef found nothing, asks to the cities database.
struct FindAdminWithCities {
typedef std::unordered_map<std::string, navitia::georef::Admin*> AdminMap;
typedef std::vector<georef::Admin*> result_type;
boost::shared_ptr<pqxx::connection> conn;
georef::GeoRef& georef;
AdminMap added_admins;
AdminMap insee_admins_map;
size_t nb_call = 0;
size_t nb_uninitialized = 0;
size_t nb_georef = 0;
std::map<size_t, size_t> cities_stats; // number of response for size of the result
FindAdminWithCities(const std::string& connection_string, georef::GeoRef& gr)
: conn(boost::make_shared<pqxx::connection>(connection_string)), georef(gr) {}
FindAdminWithCities(const FindAdminWithCities&) = default;
FindAdminWithCities& operator=(const FindAdminWithCities&) = default;
~FindAdminWithCities() {
if (nb_call == 0)
return;
auto log = log4cplus::Logger::getInstance("ed2nav::FindAdminWithCities");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << nb_call << " calls");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << nb_uninitialized << " calls with uninitialized or zeroed coord");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << nb_georef << " GeoRef responses");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << added_admins.size() << " admins added using cities");
for (const auto& elt : cities_stats) {
LOG4CPLUS_INFO(
log, "FindAdminWithCities: " << elt.second << " cities responses with " << elt.first << " admins.");
}
for (const auto& admin : added_admins) {
LOG4CPLUS_INFO(log, "FindAdminWithCities: "
<< "We have added the following admin: " << admin.second->label
<< " insee: " << admin.second->insee << " uri: " << admin.second->uri);
}
}
void init() {
for (auto* admin : georef.admins) {
if (!admin->insee.empty()) {
insee_admins_map[admin->insee] = admin;
}
}
}
result_type operator()(const navitia::type::GeographicalCoord& c, navitia::georef::AdminRtree& admin_tree) {
if (nb_call == 0) {
init();
}
++nb_call;
if (!c.is_initialized()) {
++nb_uninitialized;
return {};
}
const auto& georef_res = georef.find_admins(c, admin_tree);
if (!georef_res.empty()) {
++nb_georef;
return georef_res;
}
std::stringstream request;
request << "SELECT uri, name, coalesce(insee, '') as insee, level, coalesce(post_code, '') as post_code, "
<< "ST_X(coord::geometry) as lon, ST_Y(coord::geometry) as lat "
<< "FROM administrative_regions "
<< "WHERE ST_DWithin(ST_GeographyFromText('POINT(" << std::setprecision(16) << c.lon() << " " << c.lat()
<< ")'), boundary, 0.001)";
pqxx::work work(*conn);
pqxx::result result = work.exec(request);
result_type res;
for (auto it = result.begin(); it != result.end(); ++it) {
const std::string uri = it["uri"].as<std::string>();
const std::string insee = it["insee"].as<std::string>();
// we try to find the admin in georef by using it's insee code (only work in France)
navitia::georef::Admin* admin = nullptr;
if (!insee.empty()) {
admin = find_or_default(insee, insee_admins_map);
}
if (!admin) {
admin = find_or_default(uri, added_admins);
}
if (!admin) {
georef.admins.push_back(new navitia::georef::Admin());
admin = georef.admins.back();
admin->comment = "from cities";
admin->uri = uri;
it["name"].to(admin->name);
admin->insee = insee;
it["level"].to(admin->level);
admin->coord.set_lon(it["lon"].as<double>());
admin->coord.set_lat(it["lat"].as<double>());
admin->idx = georef.admins.size() - 1;
admin->from_original_dataset = false;
std::string postal_code;
it["post_code"].to(postal_code);
if (!postal_code.empty()) {
boost::split(admin->postal_codes, postal_code, boost::is_any_of("-"));
}
added_admins[uri] = admin;
}
res.push_back(admin);
}
++cities_stats[res.size()];
return res;
}
};
bool write_data_to_file(const std::string& output_filename, navitia::type::Data& data) {
auto logger = log4cplus::Logger::getInstance("log");
std::string temp_output = output_filename + ".temp";
try {
data.save(temp_output);
try {
remove(output_filename.c_str());
rename(temp_output.c_str(), output_filename.c_str());
LOG4CPLUS_INFO(logger, "Data saved");
} catch (const navitia::exception& e) {
LOG4CPLUS_ERROR(logger, "Error deleting file: No such file or directory");
LOG4CPLUS_ERROR(logger, e.what());
}
} catch (const navitia::exception& f) {
LOG4CPLUS_ERROR(logger, "Unable to save");
LOG4CPLUS_ERROR(logger, f.what());
try {
remove("temp.data.nav.lz4");
LOG4CPLUS_INFO(logger, "Temp data removed because it was corrupted");
} catch (const navitia::exception& g) {
LOG4CPLUS_ERROR(logger, "Error deleting file: No such file or directory");
}
return false;
}
return true;
}
int ed2nav(int argc, const char* argv[]) {
std::string output, connection_string, region_name, cities_connection_string;
double min_non_connected_graph_ratio;
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("help,h", "Show this message")
("version,v", "Show version")
("config-file", po::value<std::string>(), "Path to config file")
("output,o", po::value<std::string>(&output)->default_value("data.nav.lz4"),
"Output file")
("name,n", po::value<std::string>(®ion_name)->default_value("default"),
"Name of the region you are extracting")
("min_non_connected_ratio,m",
po::value<double>(&min_non_connected_graph_ratio)->default_value(0.01),
"min ratio for the size of non connected graph")
("full_street_network_geometries", "If true export street network geometries allowing kraken to return accurate"
"geojson for street network sections. Also improve projections accuracy. "
"WARNING : memory intensive. The lz4 can more than double in size and kraken will consume significantly more memory.")
("connection-string", po::value<std::string>(&connection_string)->required(),
"database connection parameters: host=localhost user=navitia dbname=navitia password=navitia")
("cities-connection-string", po::value<std::string>(&cities_connection_string)->default_value(""),
"cities database connection parameters: host=localhost user=navitia dbname=cities password=navitia")
("local_syslog", "activate log redirection within local syslog")
("log_comment", po::value<std::string>(), "optional field to add extra information like coverage name");
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
bool export_georef_edges_geometries(vm.count("full_street_network_geometries"));
if (vm.count("version")) {
std::cout << argv[0] << " " << navitia::config::project_version << " " << navitia::config::navitia_build_type
<< std::endl;
return 0;
}
// Construct logger and signal handling
std::string log_comment = "";
if (vm.count("log_comment")) {
log_comment = vm["log_comment"].as<std::string>();
}
navitia::init_app("ed2nav", "DEBUG", vm.count("local_syslog"), log_comment);
auto logger = log4cplus::Logger::getInstance("log");
if (vm.count("config-file")) {
std::ifstream stream;
stream.open(vm["config-file"].as<std::string>());
if (!stream.is_open()) {
throw navitia::exception("Unable to load config file");
} else {
po::store(po::parse_config_file(stream, desc), vm);
}
}
if (vm.count("help") || !vm.count("connection-string")) {
std::cout << "Extracts data from a database to a file readable by kraken" << std::endl;
std::cout << desc << std::endl;
return 1;
}
po::notify(vm);
pt::ptime start, now;
int read, save;
navitia::type::Data data;
// on init now pour le moment à now, à rendre paramétrable pour le debug
now = start = pt::microsec_clock::local_time();
ed::EdReader reader(connection_string);
if (!cities_connection_string.empty()) {
data.find_admins = FindAdminWithCities(cities_connection_string, *data.geo_ref);
}
try {
reader.fill(data, min_non_connected_graph_ratio, export_georef_edges_geometries);
} catch (const navitia::exception& e) {
LOG4CPLUS_ERROR(logger, "error while reading the database " << e.what());
LOG4CPLUS_ERROR(logger, "stack: " << e.backtrace());
throw;
}
read = (pt::microsec_clock::local_time() - start).total_milliseconds();
data.complete();
data.meta->publication_date = pt::microsec_clock::local_time();
LOG4CPLUS_INFO(logger, "line: " << data.pt_data->lines.size());
LOG4CPLUS_INFO(logger, "line_groups: " << data.pt_data->line_groups.size());
LOG4CPLUS_INFO(logger, "route: " << data.pt_data->routes.size());
LOG4CPLUS_INFO(logger, "stoparea: " << data.pt_data->stop_areas.size());
LOG4CPLUS_INFO(logger, "stoppoint: " << data.pt_data->stop_points.size());
LOG4CPLUS_INFO(logger, "vehiclejourney: " << data.pt_data->vehicle_journeys.size());
LOG4CPLUS_INFO(logger, "stop: " << data.pt_data->nb_stop_times());
LOG4CPLUS_INFO(logger, "connection: " << data.pt_data->stop_point_connections.size());
LOG4CPLUS_INFO(logger, "modes: " << data.pt_data->physical_modes.size());
LOG4CPLUS_INFO(logger, "validity pattern : " << data.pt_data->validity_patterns.size());
LOG4CPLUS_INFO(logger, "calendars: " << data.pt_data->calendars.size());
LOG4CPLUS_INFO(logger, "synonyms : " << data.geo_ref->synonyms.size());
LOG4CPLUS_INFO(logger, "fare tickets: " << data.fare->fare_map.size());
LOG4CPLUS_INFO(logger, "fare transitions: " << data.fare->nb_transitions());
LOG4CPLUS_INFO(logger, "fare od: " << data.fare->od_tickets.size());
LOG4CPLUS_INFO(logger, "Begin to save ...");
start = pt::microsec_clock::local_time();
if (!write_data_to_file(output, data))
return 1;
save = (pt::microsec_clock::local_time() - start).total_milliseconds();
LOG4CPLUS_INFO(logger, "Computing times");
LOG4CPLUS_INFO(logger, "\t File reading: " << read << "ms");
LOG4CPLUS_INFO(logger, "\t Data writing: " << save << "ms");
return 0;
}
} // namespace ed
<commit_msg>Replaced try/catch by if/else to check `rename` & `remove` returns<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program 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.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "ed2nav.h"
#include "conf.h"
#include "utils/timer.h"
#include "utils/exception.h"
#include "ed_reader.h"
#include "type/data.h"
#include "utils/init.h"
#include "utils/functions.h"
#include "type/meta_data.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
#include <pqxx/pqxx>
#include <iostream>
#include <fstream>
namespace po = boost::program_options;
namespace pt = boost::posix_time;
namespace georef = navitia::georef;
namespace ed {
// A functor that first asks to GeoRef the admins of coord, and, if
// GeoRef found nothing, asks to the cities database.
struct FindAdminWithCities {
typedef std::unordered_map<std::string, navitia::georef::Admin*> AdminMap;
typedef std::vector<georef::Admin*> result_type;
boost::shared_ptr<pqxx::connection> conn;
georef::GeoRef& georef;
AdminMap added_admins;
AdminMap insee_admins_map;
size_t nb_call = 0;
size_t nb_uninitialized = 0;
size_t nb_georef = 0;
std::map<size_t, size_t> cities_stats; // number of response for size of the result
FindAdminWithCities(const std::string& connection_string, georef::GeoRef& gr)
: conn(boost::make_shared<pqxx::connection>(connection_string)), georef(gr) {}
FindAdminWithCities(const FindAdminWithCities&) = default;
FindAdminWithCities& operator=(const FindAdminWithCities&) = default;
~FindAdminWithCities() {
if (nb_call == 0)
return;
auto log = log4cplus::Logger::getInstance("ed2nav::FindAdminWithCities");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << nb_call << " calls");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << nb_uninitialized << " calls with uninitialized or zeroed coord");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << nb_georef << " GeoRef responses");
LOG4CPLUS_INFO(log, "FindAdminWithCities: " << added_admins.size() << " admins added using cities");
for (const auto& elt : cities_stats) {
LOG4CPLUS_INFO(
log, "FindAdminWithCities: " << elt.second << " cities responses with " << elt.first << " admins.");
}
for (const auto& admin : added_admins) {
LOG4CPLUS_INFO(log, "FindAdminWithCities: "
<< "We have added the following admin: " << admin.second->label
<< " insee: " << admin.second->insee << " uri: " << admin.second->uri);
}
}
void init() {
for (auto* admin : georef.admins) {
if (!admin->insee.empty()) {
insee_admins_map[admin->insee] = admin;
}
}
}
result_type operator()(const navitia::type::GeographicalCoord& c, navitia::georef::AdminRtree& admin_tree) {
if (nb_call == 0) {
init();
}
++nb_call;
if (!c.is_initialized()) {
++nb_uninitialized;
return {};
}
const auto& georef_res = georef.find_admins(c, admin_tree);
if (!georef_res.empty()) {
++nb_georef;
return georef_res;
}
std::stringstream request;
request << "SELECT uri, name, coalesce(insee, '') as insee, level, coalesce(post_code, '') as post_code, "
<< "ST_X(coord::geometry) as lon, ST_Y(coord::geometry) as lat "
<< "FROM administrative_regions "
<< "WHERE ST_DWithin(ST_GeographyFromText('POINT(" << std::setprecision(16) << c.lon() << " " << c.lat()
<< ")'), boundary, 0.001)";
pqxx::work work(*conn);
pqxx::result result = work.exec(request);
result_type res;
for (auto it = result.begin(); it != result.end(); ++it) {
const std::string uri = it["uri"].as<std::string>();
const std::string insee = it["insee"].as<std::string>();
// we try to find the admin in georef by using it's insee code (only work in France)
navitia::georef::Admin* admin = nullptr;
if (!insee.empty()) {
admin = find_or_default(insee, insee_admins_map);
}
if (!admin) {
admin = find_or_default(uri, added_admins);
}
if (!admin) {
georef.admins.push_back(new navitia::georef::Admin());
admin = georef.admins.back();
admin->comment = "from cities";
admin->uri = uri;
it["name"].to(admin->name);
admin->insee = insee;
it["level"].to(admin->level);
admin->coord.set_lon(it["lon"].as<double>());
admin->coord.set_lat(it["lat"].as<double>());
admin->idx = georef.admins.size() - 1;
admin->from_original_dataset = false;
std::string postal_code;
it["post_code"].to(postal_code);
if (!postal_code.empty()) {
boost::split(admin->postal_codes, postal_code, boost::is_any_of("-"));
}
added_admins[uri] = admin;
}
res.push_back(admin);
}
++cities_stats[res.size()];
return res;
}
};
bool write_data_to_file(const std::string& output_filename, navitia::type::Data& data) {
auto logger = log4cplus::Logger::getInstance("log");
std::string temp_output = output_filename + ".temp";
try {
data.save(temp_output);
if (remove(output_filename.c_str()) == 0) {
if (rename(temp_output.c_str(), output_filename.c_str()) == 0)
LOG4CPLUS_INFO(logger, "Data saved");
else
LOG4CPLUS_ERROR(logger, "Unable to rename the new data file");
} else {
LOG4CPLUS_ERROR(logger, "Error deleting file: No such file or directory");
}
} catch (const navitia::exception& e) {
LOG4CPLUS_ERROR(logger, "Unable to save");
LOG4CPLUS_ERROR(logger, e.what());
if (remove(temp_output.c_str()) == 0)
LOG4CPLUS_INFO(logger, "Temp data removed because it was corrupted");
else
LOG4CPLUS_ERROR(logger, "Error deleting temp file: No such file or directory");
return false;
}
return true;
}
int ed2nav(int argc, const char* argv[]) {
std::string output, connection_string, region_name, cities_connection_string;
double min_non_connected_graph_ratio;
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("help,h", "Show this message")
("version,v", "Show version")
("config-file", po::value<std::string>(), "Path to config file")
("output,o", po::value<std::string>(&output)->default_value("data.nav.lz4"),
"Output file")
("name,n", po::value<std::string>(®ion_name)->default_value("default"),
"Name of the region you are extracting")
("min_non_connected_ratio,m",
po::value<double>(&min_non_connected_graph_ratio)->default_value(0.01),
"min ratio for the size of non connected graph")
("full_street_network_geometries", "If true export street network geometries allowing kraken to return accurate"
"geojson for street network sections. Also improve projections accuracy. "
"WARNING : memory intensive. The lz4 can more than double in size and kraken will consume significantly more memory.")
("connection-string", po::value<std::string>(&connection_string)->required(),
"database connection parameters: host=localhost user=navitia dbname=navitia password=navitia")
("cities-connection-string", po::value<std::string>(&cities_connection_string)->default_value(""),
"cities database connection parameters: host=localhost user=navitia dbname=cities password=navitia")
("local_syslog", "activate log redirection within local syslog")
("log_comment", po::value<std::string>(), "optional field to add extra information like coverage name");
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
bool export_georef_edges_geometries(vm.count("full_street_network_geometries"));
if (vm.count("version")) {
std::cout << argv[0] << " " << navitia::config::project_version << " " << navitia::config::navitia_build_type
<< std::endl;
return 0;
}
// Construct logger and signal handling
std::string log_comment = "";
if (vm.count("log_comment")) {
log_comment = vm["log_comment"].as<std::string>();
}
navitia::init_app("ed2nav", "DEBUG", vm.count("local_syslog"), log_comment);
auto logger = log4cplus::Logger::getInstance("log");
if (vm.count("config-file")) {
std::ifstream stream;
stream.open(vm["config-file"].as<std::string>());
if (!stream.is_open()) {
throw navitia::exception("Unable to load config file");
} else {
po::store(po::parse_config_file(stream, desc), vm);
}
}
if (vm.count("help") || !vm.count("connection-string")) {
std::cout << "Extracts data from a database to a file readable by kraken" << std::endl;
std::cout << desc << std::endl;
return 1;
}
po::notify(vm);
pt::ptime start, now;
int read, save;
navitia::type::Data data;
// on init now pour le moment à now, à rendre paramétrable pour le debug
now = start = pt::microsec_clock::local_time();
ed::EdReader reader(connection_string);
if (!cities_connection_string.empty()) {
data.find_admins = FindAdminWithCities(cities_connection_string, *data.geo_ref);
}
try {
reader.fill(data, min_non_connected_graph_ratio, export_georef_edges_geometries);
} catch (const navitia::exception& e) {
LOG4CPLUS_ERROR(logger, "error while reading the database " << e.what());
LOG4CPLUS_ERROR(logger, "stack: " << e.backtrace());
throw;
}
read = (pt::microsec_clock::local_time() - start).total_milliseconds();
data.complete();
data.meta->publication_date = pt::microsec_clock::local_time();
LOG4CPLUS_INFO(logger, "line: " << data.pt_data->lines.size());
LOG4CPLUS_INFO(logger, "line_groups: " << data.pt_data->line_groups.size());
LOG4CPLUS_INFO(logger, "route: " << data.pt_data->routes.size());
LOG4CPLUS_INFO(logger, "stoparea: " << data.pt_data->stop_areas.size());
LOG4CPLUS_INFO(logger, "stoppoint: " << data.pt_data->stop_points.size());
LOG4CPLUS_INFO(logger, "vehiclejourney: " << data.pt_data->vehicle_journeys.size());
LOG4CPLUS_INFO(logger, "stop: " << data.pt_data->nb_stop_times());
LOG4CPLUS_INFO(logger, "connection: " << data.pt_data->stop_point_connections.size());
LOG4CPLUS_INFO(logger, "modes: " << data.pt_data->physical_modes.size());
LOG4CPLUS_INFO(logger, "validity pattern : " << data.pt_data->validity_patterns.size());
LOG4CPLUS_INFO(logger, "calendars: " << data.pt_data->calendars.size());
LOG4CPLUS_INFO(logger, "synonyms : " << data.geo_ref->synonyms.size());
LOG4CPLUS_INFO(logger, "fare tickets: " << data.fare->fare_map.size());
LOG4CPLUS_INFO(logger, "fare transitions: " << data.fare->nb_transitions());
LOG4CPLUS_INFO(logger, "fare od: " << data.fare->od_tickets.size());
LOG4CPLUS_INFO(logger, "Begin to save ...");
start = pt::microsec_clock::local_time();
if (!write_data_to_file(output, data))
return 1;
save = (pt::microsec_clock::local_time() - start).total_milliseconds();
LOG4CPLUS_INFO(logger, "Computing times");
LOG4CPLUS_INFO(logger, "\t File reading: " << read << "ms");
LOG4CPLUS_INFO(logger, "\t Data writing: " << save << "ms");
return 0;
}
} // namespace ed
<|endoftext|> |
<commit_before><commit_msg>:construction: chore(gc): updated the base gc definitions<commit_after><|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.